NodeMCU serial Communication with Nextion using LUA

  1. Never forget to set a fuse in init.lua
gpio.mode(6, gpio.INPUT)
EnableBoot=gpio.read(6)
 
if EnableBoot==0 then dofile("main.lua") 
else print("Device will not continue booting...")
end

Consider we have a text with id t0 on Nextion.
To test two way communication, we put a button on Nextion, which send “Hello from Nextion” over serial.
This incoming data is also printed to the debug screen.
The last component on Nextion is a gauge with id z0.

Below you can found main.lua file wihch does two way communication with Nextion. It sends the Pot value to the Nextion on input trigger. And at at every second it sends Pot value to Nextion’s gauge as integer value.

print("Normal Boot")
 
local MyInput=5
local Threshold=1000
local LastTrig=0
local PotValue=0
 
gpio.mode(MyInput,gpio.INT)
 
local mytimer = tmr.create()
 
local function SendToNextion(Object,Property,Value,IsInt)
    if IsInt then
        uart.write(0,Object.."."..Property.."="..Value..(string.char (255))..(string.char (255))..(string.char (255)))
    else 
        uart.write(0,Object.."."..Property.."=\""..Value.."\""..(string.char (255))..(string.char (255))..(string.char (255)))
    end  
end
 
local function InputTrigger(State, Time)
    local ms=tmr.now()/1000
    local diff=ms-LastTrig
    if diff<Threshold then return end
    LastTrig=ms
    PotValue=adc.read(0)
    SendToNextion("t0","txt","POT:"..tostring(PotValue),false)
end
 
gpio.trig(MyInput, "up", InputTrigger)
 
uart.setup(0, 9600, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
 
uart.on("data", "\r",
  function(data)
    print("receive from uart:", data)
    if data=="quit\r" then
      uart.on("data")
    end
end, 0)
 
local function SendPotValue()
    PotValue=adc.read(0)
    Degree=PotValue/6
 
    SendToNextion("z0","val",Degree,true)
    mytimer:unregister()
    mytimer:register(1000, tmr.ALARM_SINGLE,SendPotValue)
    mytimer:start()
end
 
mytimer:register(1000, tmr.ALARM_SINGLE,SendPotValue)
mytimer:start()

I hope this helps.

Yorum yaz