UDP
Basics
The first internet protocol we will have a look at is UDP, or the User Datagram Protocol.
UDP is a very simple protocol on top of IP that basically only adds a notion of ports to IP packets so that multiple applications can be addressed on a single host.
NodeMCU Server
First we will be receiving UDP packets
on the microcontroller boards.
For this to work replace the content
of the current application.lua
with the
following:
function on_udp_packet(ip, data, port)
local stripped= data:gsub("\n", "")
print("Received: "..stripped)
end
function setup_udp()
local socket = net.createUDPSocket()
socket:on("receive", on_udp_packet)
socket:listen(5000)
print("listening on port 5000")
end
setup_udp()
upload it, connect picocom
and reset the board.
If everything went well the output should look something like the following:
[user@computer ~]$ picocom -b 115200 /dev/ttyUSB0
…
init: got IP address 192.168.94.158 via DHCP
init: startup will continue in 3s
init: handing over to application
listening on port 5000
Meaning, in this case, that the application is listening
on 192.168.94.158:5000
for UDP packets.
Netcat client
To send packets to the server we will use the Netcat commandline utility.
To make netcat send UDP packets to your microcontroller it has to be started like the following:
[user@computer ~]$ nc -u 192.168.94.158 5000
Hint: The IP address and port you use in the command have to match the IP and port you see in picocom.
Hint: Open a new terminal emulator so that you can have picocom and netcat running at the same time.
Now whenever you enter text into the terminal running netcat and hit enter a UDP packet is sent to the microcontroller.
In picocom you should see output like the following:
[user@computer ~]$ picocom -b 115200 /dev/ttyUSB0
…
listening on port 5000
Received: Hello World from Netcat
Received: Test
Task: Adapt the application.lua
to turn on an
LED when the word “on” is received and off when the
word “off” is received.