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).
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