1. 程式人生 > >ESP8266學習之路 十三 (SPI讀取max6675)

ESP8266學習之路 十三 (SPI讀取max6675)

通過spi模組讀取四路max6675溫度資料

 

max6675.lua檔案:

SpiPinCS1 = 8--GPIO15  
SpiPinCS2 = 7--GPIO13
SpiPinCS3 = 0--GPIO16
SpiPinCS4 = 1--GPIO5     --定義四路spi片選引腳

spi.setup(1, spi.MASTER, spi.CPOL_HIGH, spi.CPHA_HIGH, 8, 8)
gpio.mode(SpiPinCS1, gpio.OUTPUT, gpio.PULLUP)
gpio.mode(SpiPinCS2, gpio.OUTPUT, gpio.PULLUP)
gpio.mode(SpiPinCS3, gpio.OUTPUT, gpio.PULLUP)
gpio.mode(SpiPinCS4, gpio.OUTPUT, gpio.PULLUP)  --設定片選引腳模式


local SpiCount = 0  --計數定時1秒 把資料傳送到ESP8266模組串列埠


tmr.alarm(1,100,1,function()
    SpiCount = SpiCount + 1
    if SpiCount >= 10 and SpiCount <= 11 then
        SpiCount = 11
        gpio.write(SpiPinCS1,0)     --拉低片選開始讀資料
        --spi.send(1,0xff)
        SpiData1 = spi.recv(1,1)
        SpiData2 = spi.recv(1,1)    --讀取max6675原始資料
        num=SpiData1:byte(1)*256 + SpiData2:byte(1)  --byte(1)轉換為整數
        num=num*2
        num= num/16
        num=num*0.25            --計算得出實際溫度
        print("temperture1:"..num)--串列埠列印溫度資料
        gpio.write(SpiPinCS1,1)   --拉高片選,停止讀資料

     elseif SpiCount >=20 and SpiCount <= 21 then
        SpiCount = 21
        gpio.write(SpiPinCS2,0)
        --spi.send(1,0xff)
        SpiData1 = spi.recv(1,1)
        SpiData2 = spi.recv(1,1)
        num=SpiData1:byte(1)*256 + SpiData2:byte(1)
        num=num*2
        num= num/16
        num=num*0.25
        print("temperture2:"..num)
        gpio.write(SpiPinCS2,1)

     elseif SpiCount >=30 and SpiCount <= 31 then
        SpiCount = 31
        gpio.write(SpiPinCS3,0)
        --spi.send(1,0xff)
        SpiData1 = spi.recv(1,1)
        SpiData2 = spi.recv(1,1)
        num=SpiData1:byte(1)*256 + SpiData2:byte(1)
        num=num*2
        num= num/16
        num=num*0.25
        print("temperture3:"..num)
        gpio.write(SpiPinCS3,1)

     elseif SpiCount >=40 and SpiCount <= 41 then
        SpiCount = 0
        gpio.write(SpiPinCS4,0)
        --spi.send(1,0xff)
        SpiData1 = spi.recv(1,1)
        SpiData2 = spi.recv(1,1)
        num=SpiData1:byte(1)*256 + SpiData2:byte(1)
        num=num*2
        num= num/16
        num=num*0.25
        print("temperture4:"..num)
        gpio.write(SpiPinCS4,1)
     end
end)