(click here to see index of all ESP8266 posts)
This is just a different twist to my prior post
ESP8266 Reading/Writing GPIO and Transmitting/Receiving UDP Packets
In that post I send UDP packets to a Raspberry Pi running the echo service. In this post, I send the same packet in the same manner, but it is received by a LUA program being run on the Raspberry Pi.
To make this work, LUA and the lua-sockets package must be installed on the RPI. Please see here to make that happen:
Installing LUA on Raspberry Pi and Getting it Running
I used the following resource as an aid to writing the LAU program on the Raspberry Pi:
https://love2d.org/wiki/Tutorial:Networking_with_UDP-TheServer
The ESP8266 program used in the last ESP8266 post is almost right for this new experiment. The difference is I no longer want to use the echo service port, but will simply use UDP port 9999 instead. Here is the new code:
-- interrupt called when button is pressed function btnINT(level) if inInt then -- don't allow interrupt in interrupt return else inInt = true end tmr.delay(100000) -- 100ms debounce cu:send('1234') gpio.write(4, gpio.LOW) inInt = false end -- btnINT -- function called when UDP packet received function rxPkt(cu,c) if c == '1234' then print('correct response') gpio.write(4, gpio.HIGH) else print('incorrect response') end end -- rxPkt -- setup gpio pins gpio.mode(3, gpio.INT, gpio.PULLUP) gpio.trig(3, 'down', btnINT) gpio.mode(4, gpio.OUTPUT) gpio.write(4, gpio.LOW) -- setup UDP port cu=net.createConnection(net.UDP) cu:on('receive',rxPkt) cu:connect(9999,'192.8.50.106') inInt = false
Now, I need a LUA program on the RPI that will accept a UDP packet, and simply echo it back (for this example, I’m not going to do anything any fancier than that, but it illustrates the necessary techniques I’ll need later down the road).
#!/usr/bin/lua -- Setup UDP socket. Bind to localhost, port 9999. local socket = require "socket" local udp = socket.udp() udp:settimeout(0) -- indicates not to wait. If no data, return immediately udp:setsockname('*', 9999) local data, msg_or_ip, port_or_nil print "Beginning server loop." while true do data, msg_or_ip, port_or_nil = udp:receivefrom() -- receive UDP packet if data then print('data ', data) print('msg ', msg_or_ip) print('port ', port_or_nil) udp:sendto(data, msg_or_ip, port_or_nil) -- xmit same UDP packet back elseif msg_or_ip ~= 'timeout' then error("Unknown network error: "..tostring(msg)) end socket.sleep(0.01) -- sleep .01 secs end
My understanding is this will work exactly the same way on any linux or windows implementation of LUA. So if you don’t have a Raspberry Pi but have a PC, you can still use this code.
Pingback: ESP8266 UDP to/from Raspberry Pi running Lazaraus / Free Pascal | Big Dan the Blogging Man
Pingback: SNMP Environmental Monitoring using ESP8266-based Sensors | Big Dan the Blogging Man