Wiznet makers

ronpang

Published December 27, 2023 ©

125 UCC

10 WCC

32 VAR

0 Contests

1 Followers

0 Following

Original Link

5. MicroPython development for W5100S/W5500+RP2040<TCP Server example>

5. MicroPython development for W5100S/W5500+RP2040<TCP Server example>

COMPONENTS Hardware components

WIZnet - W5500-EVB-Pico

x 1


WIZnet - W5100S-EVB-Pico

x 1

Software Apps and online services

micropython - MicroPython

x 1


PROJECT DESCRIPTION

1 Introduction

In this era of smart hardware and the Internet of Things, MicroPython and Raspberry Pi PICO are leading the new trend of embedded development with their unique advantages. MicroPython, as a streamlined and optimized Python 3 language, provides efficient development and easy debugging for microcontrollers and embedded devices.

 When we combine it with the WIZnet W5100S/W5500 network module, the development potential of MicroPython and Raspberry Pi PICO is further amplified. Both modules have built-in TCP/IP protocol stacks, making it easier to implement network connections on embedded devices. Whether it is data transmission, remote control, or building IoT applications, they provide powerful support.

 In this chapter, we will take WIZnet W5100S as an example and use MicroPython development method to perform TCP_Server parsing example.

2 Related network information

2 .1 Protocol Introduction

TCP Server is a server-side program that uses the TCP protocol to communicate. TCP is a connection-oriented, reliable, byte stream-based transport protocol used to transmit data over computer networks. TCP Server plays an important role in computer networks. It monitors client connection requests and establishes reliable connections with clients to realize data transmission. In TCP Server, the server program needs to specify the listening port number and use the TCP protocol to establish a connection with the client. Once a client connects, the server program will establish a separate connection for each client and interact with the client through the data stream object (NetworkStream).

2.2 TCP Server working steps

General TCP server creation steps:

Create a socket.

Binds the socket to the specified IP address and port number.

Start listening for connection requests from clients.

When a client requests a connection, the connection request is accepted and a new socket (often called a subsocket) is created to handle communication with the client.

Data exchange with client via subsocket.

After completing the data exchange, close the subsocket and continue to listen for connection requests from other clients.

2.3 Advantages of TCP Server

The advantages of TCP Server mainly include:

Connection-oriented transmission: TCP is a connection-oriented protocol, which requires a connection to be established before data transmission. This connection can ensure the reliability and sequence of data transmission.

Reliable data transmission: TCP provides reliable data transmission services. It uses confirmation mechanisms, retransmission mechanisms and other means to ensure that data will not be lost or repeated during the transmission process.

Full-duplex transmission: TCP supports full-duplex transmission, that is, data can be transmitted in both directions at the same time, improving transmission efficiency.

Byte stream mode: TCP transmits data in the form of byte stream, which can better handle large amounts of data and control the flow of data.

Emergency data transmission function: TCP provides an emergency data transmission function, which can prioritize data transmission in emergencies.

2.4 Application scenarios

TCP Server has a wide range of application scenarios. The following are some main scenarios:

E-commerce platform: TCP Server can be used as the back-end service of the e-commerce platform to process user orders, payments and other operations to ensure the security and reliability of transactions.

Online games: TCP Server can be used on the server side of online games to handle game player connections, data exchange and other operations, providing a stable and efficient gaming experience.

Instant messaging: TCP Server can be used on the server side of the instant messaging system to handle operations such as user login, message sending and receiving, etc. to ensure the stability and reliability of communication.

Remote monitoring: TCP Server can be used on the server side of the remote monitoring system to receive and process monitoring data and provide real-time monitoring pictures and alarm information.

File transfer: TCP Server can be used on the server side of the file transfer system to handle operations such as file upload and download, ensuring the integrity and reliability of file transfer.

Online video conferencing: TCP Server can be used on the server side of the online video conferencing system to handle operations such as the transmission and processing of audio and video data, providing a stable and smooth conference experience.

3 WIZnet Ethernet chip

WIZnet mainstream hardware protocol stack Ethernet chip parameter comparison

ModelEmbedded CoreHost I/FTX/RX BufferHW SocketNetwork Performance
W5100STCP/IPv4, MAC & PHY8bit BUS, SPI16KB4Max.25Mbps
W6100TCP/IPv4/IPv6, MAC & PHY8bit BUS, Fast SPI32KB8Max.25Mbps
W5500TCP/IPv4, MAC & PHYFast SPI32KB8Max.15Mbps

W5100S/W6100 supports 8-bit data bus interface, and the network transmission speed will be better than W5500.

W6100 supports IPv6 and is compatible with W5100S hardware. If users who already use W5100S need to support IPv6, they can be Pin to Pin compatible.

W5500 has more Sockets and send and receive buffers than W5100S.

4 TCP Server network setting example overview and usage

4.1 Flowchart

The running block diagram of the program is as follows:

4.2 Core preparation work

Software

Thonny

WIZnet UartTool

SocketTester

Hardware

W5100SIO module + RP2040 Raspberry Pi Pico development board or WIZnet W5100S-EVB-Pico development board

Micro USB interface data cable

TTL to USB

cable

4.3 Connection method

Connect the USB port of the PC through the data cable (mainly used for burning programs, but can also be used as a virtual serial port)

Convert TTL serial port to USB and connect the default pin of UART0:

RP2040 GPIO0 (UART0 TX) <----> USB_TTL_RX

RP2040 GPIO1 (UART0 RX) <----> USB_TTL_TX

When wiring using module connection RP2040

RP2040 GPIO16 <----> W5100S MISO

RP2040 GPIO17 <----> W5100S CS

RP2040 GPIO18 <----> W5100S SCK

RP2040 GPIO19 <----> W5100S MOSI

RP2040 GPIO20 <----> W5100S RST

Connect the PC and device to the router LAN port through network cables

4.4 Main code overview

We open the TCP_Server.py file directly.

Step one: You can see that SPI is initialized in the w5x00_init() function. And register the spi-related pins and reset pins into the library. The subsequent step is to activate the network and use DHCP to configure the network address information. When DHCP fails, configure the static network address information. When the configuration is not successful, the information about the network address-related registers will be printed out, which can help us better troubleshoot the problem.

Step 2: Then perform the client monitoring operation. When a client is connected, perform a data sending and receiving test.

''' TCP Server example.
  date: 2023-11-23
'''
from usocket import socket
from machine import Pin,SPI,UART
import time, network

''' static netinfo
'''
ip = '192.168.1.11'
sn = '255.255.255.0'
gw = '192.168.1.1'
dns= '8.8.8.8'

netinfo=(ip, sn, gw, dns)

localip = ''
localport = 8000
listen_info = (localip, localport)

''' uart0 init
  baudrate: 115200
  tx pin : gpio0
  rx pin : gpio1
'''
uart = UART(0, 115200, tx=Pin(0), rx=Pin(1))  
uart.init(115200, bits=8, parity=None, stop=1)
uart.write('WIZnet chip tcp server example.\r\n')
   
def w5x00_init():
   global localip
   ''' spi0 init
      baudrate: 2000000
      mosi pin: gpio19
      miso pin: gpio16
      sck pin: gpio18
      cs   pin: gpio17
      rst pin: gpio20
  '''
   spi=SPI(0,2_000_000, mosi=Pin(19),miso=Pin(16),sck=Pin(18))
   nic = network.WIZNET5K(spi,Pin(17),Pin(20))
   nic.active(True)
   # use dhcp, if fail use static netinfo
   try:
       nic.ifconfig('dhcp')
   except:
       nic.ifconfig(netinfo)
   localip = nic.ifconfig()[0]
   print('ip :', nic.ifconfig()[0])
   print('sn :', nic.ifconfig()[1])
   print('gw :', nic.ifconfig()[2])
   print('dns:', nic.ifconfig()[3])
   uart.write('ip :{0}\r\n'.format(nic.ifconfig()[0]))
   uart.write('sn :{0}\r\n'.format(nic.ifconfig()[1]))
   uart.write('gw :{0}\r\n'.format(nic.ifconfig()[2]))
   uart.write('dns:{0}\r\n'.format(nic.ifconfig()[3]))
   
   while not nic.isconnected():
       time.sleep(1)
#         print(nic.regs())
       print('no link')
       uart.write('no link\r\n')

conn_flag = False

def server_loop():
   global localip
   global conn_flag
   while True:
       if(conn_flag == False):
           uart.write('socket open\r\n')
           s = socket()
           s.bind(listen_info) # Source IP Address and Port
           s.listen(5) # max conncet counts
           conn_flag = True
           print("TEST server Loop")
           uart.write('TCP Server:{0} ,listen port:{1}\r\n'.format(localip, listen_info[1]))
           conn, addr = s.accept()
           print('Connect from %s' % str(addr))
           uart.write('Connect from {0}:{1}\r\n'.format(addr[0], addr[1]))
       else:
           
           try:
               
               data = conn.recv(2048)
               data = data.decode('utf-8')

               data+='\r\n'
               uart.write(data)
               if data != 'NULL':
                   conn.send(data)
           except:
               uart.write('disconnect')
               conn_flag = False
           
def main():
   w5x00_init()
   server_loop()
if __name__ == "__main__":
   main()



 

4.5 Burning Verification

To test the Ethernet examples, the development environment must be configured to use a Raspberry Pi Pico.

Required development environment

Thonny

If you must compile MicroPython, you must use a Linux or Unix environment.

After copying the code to Thonny, select the running environment as Raspberry Pi Pico, and then click Run. Open SocketTester, select the client to connect to the server and send a message to get the response. Open WIZnet UartTool and open the serial port. If you can see the message sent by the client, it means the test is successful.

5 Precautions

If you use WIZnet's W5500 to implement the examples in this chapter, you only need to burn the firmware of the W5500 and run the example program.

Documents
  • Code for this article

  • YouTube Demo

  • YouTube Demo [Eng]

Comments Write