Exploring UDP with ESP32
|ESP32 is fun to work with, once you got it into a network, you can do lot of things. We have seen how to make use it as a TCP Client or a TCP Server. TCP is great when you need reliability and ok with overhead of sending some extra information. If you want something near real time UDP is your best bet. In this post we will see how to send some information from ESP32 to other nodes in the network using UDP.
API is very similar to TCP, instead of SOCK_STREAM we will create socket with SOCK_DGRAM . Since UDP is connection less protocol we will not be initiating connection with peer before sending data. We simply send data to the peer. We need to know the IP of the destination in order send a message. We can use broadcast if we don’t know the destination address. Broadcasts can be received by any node present in the network.
s = socket(AF_INET, SOCK_DGRAM, 0);
We use the sendto
method to send data
sendto(s,dataptr,size,flags,to,tolen)
s is the socket we created,dataptr refers to the data we want to send. to indicates sockaddr_in (receiver address, we are sending broadcast so we will use broadcast address which is 192.168.0.255 in my case)
Using UDP we will develop a remote control for servo hooked to ESP32. We will be controlling the Servo from command line. There is a android app also for controlling the servo angle over network