STM32 ETHENRET #2. UDP SERVER
This is second tutorial in the STM32 ETHERNET Series, ands today we will see how to create UDP Server using STM32.
UDP is the simplest protocol, and this is why I am starting with it.
This tutorial will simply cover the UDP SERVER mode, the next one will cover UDP Client mode, and similarly we will move to TCP, and then later with HTTP.
The cube MX Setup is same as that in the previous tutorial. Now let’s see some code.
Initialize the UDP SERVER
To initialize the UDP Server, the following steps are taken
- Create a new UDP control block using
- Bind the block to the local IP address and Port
- To do this we will first convert the IP address to the integer form
- Then we will use the local IP address to bind the control block using the function
- Once the bind is complete, the server will wait for the client to send the data.
- To do this, we can set a callback (udp_recv), which will be called whenever the server will receive the data from the client.
- Once the data is received, we can process the data, and send some reply to the client.
The Receive Callback
The receive callback is called, when the server receives some data from the client. The following shows a way to handle this data.
- First of all I am creating a new Packet Buffer (txBuf), which will be used to send the data.
char *remoteIP = ipaddr_ntoa(addr);converts the IP address from integer format to the regular IP format.
- This is just in case if we want to utilize the address and port of the client.
- Next I am mixing the incoming data with some additional data.
- To send this new data to the client, first we need to allocate some memory for the packet buffer.
- This can be done with
- Then we will copy the data into the packet buffer using
- Next we will connect to the client.
- This can be done by using
udp_connect. The parameters, address and port of the client, are the part of the function, where udp_connect is being called.
- Then we send the data using the
Here upcb is the control block which have all the information about the local and remote connection.
txBuf is the packet buffer, and it have all the information about the data.
- Once the data is sent, we will disconnect the client, so that a new client can connect.
- And in the end we will free all the memories.
The main code
- Here everything is similar to the previous tutorial, except that we will also call the
- ethernetif_input basically handles all the incoming requests.
- It calls the appropriate low level function, based on what protocol is being used.
- So we can just use the same code in the TCP also.
You can see above, the data sent and received by the client.
- #Modbus 1. STM32 Master Reads Holding and Input Registers October 1, 2022
- MODBUS PROTOCOL 101 September 29, 2022
- RS485 Module and STM32 September 23, 2022
- FDCAN in Normal Mode || STM32H7 September 15, 2022
- STM32 FDCAN in Loopback Mode August 19, 2022
- I2C in ESP32 || ESP-IDF || LCD 1602 July 15, 2022