Micropython UDP on ESP8266

TCP is to establish reliable connection, and both sides of communication can send data in the form of flow. Compared to TCP, UDP aims at connectionless protocol. When using UDP, you don’t need to establish connection and only need to know the IP address and port no. of the other part. Then you can send data packets directly.

Here we will use serial/network debugging assistant. Download address is: http://www.daxia.com/sscom/sscom5.12.1.rar

Program is as follows:

import socket
port = 10086
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('',port)) #绑定端口binding the port
while True:   #接收数据receiving data

Connect esp8266 with burnt micropython to PC. Open our putty terminal in the said methods. Before doing udp, we must finish some necessary preparation. Firstly, connect esp8266 to wireless network, and then we are able to get the needed ip address.

Enter the following command in the terminal until esp8266 is successfully connected to wifi. We can use wlan.isconnected to check whether it is connected. wlan.scan() is used to scan nearby wireless networks. Use wlan.connect(‘ssid’,’password’) to connect our wireless network (ssid: our wifi name. password: password of wireless network).

After entering command of connecting wifi, appearance of condition as shown below means successful connection to wifi. At the same time, we can see the needed ip address. Remember the ip address, which we will use in the following udpserver program.

Operate our program in the terminal in the said methods. Correct running result is shown below:

Open the downloaded serial debugging assistant.Now we can use the recorded ip address. Select udp at our port no. Enter the recorded ip address at remote. Fill the port no. of our program in the port behind remote.

Click link. You can see whether connect is successful at the bottom line.

Enter nihao in the blank next to the send button, and then click send. We will receive the sent message and sent address at putty terminal as shown below:

Then our udp connection and receiving and sending message are completed.

There is a direct method to realize the function. Code is as follows:

import network[/align]import socket
import time
wlan = network.WLAN(network.STA_IF)
wlan.connect('dfyanfa', 'df123456')
while(wlan.isconnected() == False):
ip = wlan.ifconfig()[0]
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:

Directly entering the said code is ok. Use serial/network debugging assistant as UDP client to establish connection with server. Operating method is the same as the said. Try it if you are interested or for the sake of convenience.

Reference link: ESP8266 Micropython -Tutorial 5: Micropython UDP