Post your best Lua script examples here

User avatar
By StefanL38
#12393 Here is a small democode how to exchange serial data:
Code: Select all-- simple example for receiving serial commands
-- this is a small testcode for using with LuaLoader or any other
-- serial terminal software to show how sending serial data to the ESP826 under the nodeMCU-firmware works:


-- setup UART for receiving data
-- parameters uart.setup( UART-id, baud, databits, parity, stopbits, echo )
uart.setup(0,9600,8,0,1)

print ("uart.setup(0,9600,8,0,1) finished")
print ("waiting for serial data....")

-- My opinion: Lua is crazy flexible
-- You just send the NAME of a function with parameters and Lua knows what do to
-- Execute the defined function with parameters
-- example: sending the following string to the ESP makes the code execute function 'cmd_2'
-- with parameter '78'    string to send towards ESP "cmd_2(78)"

function cmd_1(value)
  print("cmd_1("..value..") received")
end

function cmd_2(value)
  print("cmd_2("..value..") received")
end


hope this helps get other people started.

So it's up to you to expand this code for better usability and more functionality.
As I'm a newbee to Lua and also a newbee to the deeper concepts of object-oriented programming
there may exist better ways to do this serial communication but it is a start.

You are welcome to improve this serial Lua-example-code or demontrate other ways how to realise serial communication.
I'm still very impressed by the power of Lua and how compact code can be written in Lua.
best regards

Stefan
User avatar
By Vitoa
#12401 Hi, take a look at https://github.com/nodemcu/nodemcu-firm ... _en#uarton

uart.setup(0,9600,8,0,1,0) --this uart setup disables echo
uart.on("data", 1, --1 byte received
function(data)
print("receive from uart:", data) --print byte received
if data=="x" then --press x to quit
uart.on("data")
uart.setup(0,9600,8,0,1,1) --this enables echo to see what ur writing
print("Quit uart monitor")
end
end, 0)