ESP8266学习之路 十二 (读写文件)

  1. 通过串口发送指令控制继电器, 掉电记忆继电器状态,再次上电恢复继电器状态。
  2. 通过串口发送"open"打开继电器, 发送"close"关闭继电器 ,并把继电器状态写入mode.lua文件; 发送"rest"系统软件复位
  3. 测试通过串口发送"open"打开继电器后, 点击板子的复位按键, 系统复位, 松开后程序会获取断电前的继电器状态,恢复继电器状态

init.lua文件

RELAY_Stat = ""
RELAY_Pin = 1
gpio.mode(RELAY_Pin, gpio.OUTPUT)
if file.open("mode.lua", "r") then
     RELAY_Stat = file.readline()
     print(RELAY_Stat)
     file.close()
end
if string.find(RELAY_Stat,"RELAY=1",1) then
    gpio.write(RELAY_Pin,1) 
elseif string.find(RELAY_Stat,"RELAY=0",1) then
    gpio.write(RELAY_Pin,0)
end
tmr.alarm(0,4000,0,function() 
    dofile("file.lua") 
end)

file.lua文件

UartReceCnt = 0        
UartReceTempCnt = 0    
UartReceData = ""    
uart.on("data",0,function(data) 
            UartReceData = UartReceData..data 
            UartReceCnt = UartReceCnt + 1     
end,0)   
tmr.alarm(1,10,1,function()
    if UartReceCnt ~= 0 then 
        if UartReceTempCnt == UartReceCnt then  
            UartReceCnt = 0
            UartReceTempCnt = 0 
            if UartReceData == "open" then  
                gpio.write(RELAY_Pin,1)
                if  file.open("mode.lua", "w+") then
                    file.writeline("RELAY=1")
                    file.flush()
                else
                    print("open mode.lua faild") 
                end
                file.close()
            elseif UartReceData == "close" then
                gpio.write(RELAY_Pin,0)  
                if  file.open("mode.lua", "w+") then
                    file.writeline("RELAY=0")
                    file.flush()
                else
                    print("open mode.lua faild") 
                end
                 file.close()
            elseif UartReceData == "rest" then
                node.restart()
            end
             uart.write(0,UartReceData) 
             UartReceData = ""  
             UartReceCnt = 0
        else
            UartReceTempCnt = UartReceCnt  
        end
     end
end)

 

演示视频:https://v.youku.com/v_show/id_XMzkxMTAyOTI0MA==.html?spm=a2h0j.11185381.listitem_page1.5~A

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值