I couldn't find the lua code to read a MCP3008 ADC so I adapted Adafruit python code (https://github.com/adafruit/Adafruit-Ra ... mcp3008.py) to lua. Many thanks to Rahul K (viewtopic.php?f=11&t=8671&p=42878#p42878) for an example of how to use SPI.
MISO = 6 --> GPIO12
MOSI = 7 --> GPIO13
CLK = 5 --> GPIO14
CS = 8 --> GPIO15
-- Pin Initialization
gpio.mode(CS, gpio.OUTPUT)
gpio.mode(CLK, gpio.OUTPUT)
gpio.mode(MOSI, gpio.OUTPUT)
gpio.mode(MISO, gpio.INPUT)
-- Function to read MCP3008
function readMCP3008(adc_ch)
if adc_ch >=0 and adc_ch < 8 then
-- MCP3008 has eight channels 0-8
gpio.write(CS,gpio.HIGH)
tmr.delay(5)
gpio.write(CLK, gpio.LOW)
gpio.write(CS, gpio.LOW) -->Activate the chip
tmr.delay(1) -->1us Delay
commandout = adc_ch
commandout=bit.bor(commandout, 0x18)
commandout=bit.lshift(commandout, 3)
for i=1,5 do
if bit.band(commandout,0x80) >0 then
gpio.write(MOSI, gpio.HIGH)
else
gpio.write(MOSI, gpio.LOW)
end
commandout=bit.lshift(commandout,1)
gpio.write(CLK, gpio.HIGH)
tmr.delay(1)
gpio.write(CLK, gpio.LOW)
tmr.delay(1)
end
adcout = 0
for i=1,12 do
gpio.write(CLK, gpio.HIGH)
tmr.delay(1)
gpio.write(CLK, gpio.LOW)
tmr.delay(1)
adcout = bit.lshift(adcout,1);
if gpio.read(MISO)>0 then
adcout = bit.bor(adcout, 0x1)
end
end
gpio.write(CS, gpio.HIGH)
adcout = bit.rshift(adcout,1)
return adcout
else
return -1
end
end