spi.start(MOSI, MISO, CLK, CS, speed_hz)
Starts the SPI in Master Mode.
- MOSI: MOSI (Master Out Slave In) pin
- MISO: MISO (Master In Slave Out) pin
- CLK: Clock pin
- CS: Chip Select pin
- speed_hz: Communication speed (e.g., 1 * 1000 * 1000 for 1MHz).
Occupancy and Retention
An SPI session initiated from Lua is exclusively reserved for Lua, making it unavailable for external use by other interfaces like obniz.js.
Additionally, once an SPI session is started, it cannot be terminated until the device is rebooted. Therefore, if you call spi.start() again from Lua while the device is running, the new settings may not take effect, or it may result in an error. A reboot is required if you wish to change configurations such as the MOSI pin.
If you do not need to change the configurations, the SPI interface remains active even if a subsequent spi.start() call fails. As a result, you can continue to use SPI-related functions such as spi.write().
spi.write(string)
Sends and receives data over the SPI bus.
Once the process is complete, you can retrieve the values received in the shift register.
Example
The following example demonstrates how to periodically control a relay mounted on an Intelligent Edge Kilo via SPI.
function plugin_name()
return "spi_test" -- max 30 chars
end
function on_event(event)
if event == "power_on" then
os.log(" - Lua PowerOn");
init();
end
end
local tick = 0
local flag = false
local initialized = false
function init()
if initialized then
return
end
initialized = true
-- Kilo Internal Shared SPI for MCP23S08
io.retain(8, true); -- CLK
-- Parameters: MOSI, MISO, CLK, CS (CS can be null for non-shared SPI), baudrate
local err = spi.start(20, 21, 19, 8, 100 * 1000);
if err > 0 then
os.log("SPI Error: " .. err);
return
end
os.log("SPI Started");
-- Configuration: Write address / Direction Address / Values
-- Change I/O Direction
spi.write(string.char(0x40, 0x00, 0xC0));
end
init();
function on_offline_loop()
loop()
end
function on_online_loop()
loop()
end
tick = 0;
function loop()
local current = os.getTick()
if tick == 0 then
tick = current
end
-- Execute every 3 seconds
if current - tick >= 3 * 1000 then
tick = current
if flag then
-- Set Relay to On
local ret = spi.write(string.char(0x40, 0x09, 0x3C));
os.log("Relay On");
else
-- Set Relay to Off
local ret = spi.write(string.char(0x40, 0x09, 0x1C));
os.log("Relay Off");
end
flag = not flag
end
end