Wiznet makers

ronpang

Published December 27, 2023 ©

125 UCC

10 WCC

32 VAR

0 Contests

1 Followers

0 Following

Original Link

4. MicroPython development for W5100S/W5500+RP2040<TCP Client example>

4. MicroPython development for W5100S/W5500+RP2040<TCP Client example>

COMPONENTS Hardware components

WIZnet - W5100S-EVB-Pico

x 1


WIZnet - W5500-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_Client parsing example.

2 Related network information

2.1 Protocol Introduction

TCP_Client is a client of a network protocol, typically used to establish reliable data connections between devices or applications. It establishes a connection with the remote server through the TCP/IP protocol and sends request information. After receiving the request information, the server provides services on the corresponding port and returns a response. After TCP_Client parses the response information, it can process it accordingly.

 TCP_Client is usually used for data interaction between devices and servers, and is one of the most commonly used networking communication methods. It has the concept of connection and disconnection, thus ensuring reliable exchange of data.

2.2 TCP_Client working steps

During the three-way handshake:

First handshake: The client sends a TCP message with the SYN flag to the server and waits for confirmation from the server.

Second handshake: After the server receives the SYN message, it will send a TCP message with SYN and ACK flags to the client, and at the same time initialize a sequence number for itself, and the confirmation number is set to the sequence number of the SYN message received from the client. Add 1 and wait for confirmation from the client.

Third handshake: After receiving the message with the SYN and ACK flags sent by the server, the client sends a TCP message with the ACK flag to the server. The confirmation number is set to the sequence number of the SYN message received from the server plus 1. Set its own serial number to the serial number of the SYN message received from the server plus 1, enter the ESTABLISHED state, and complete the three-way handshake.

Data exchange is possible if the connection is successful.

During the four waves:

The first wave: the client sends a FIN message to the server to close the data transmission from the client to the server.

The second wave: After receiving the FIN message, the server sends a TCP message with the ACK flag to the client. The confirmation number is set to the sequence number of the client's FIN message plus 1.

The third wave: the server sends a TCP message with the FIN flag to the client, closing the data transmission from the server to the client.

The fourth wave: After receiving the message with the FIN flag sent by the server, the client sends a TCP message with the ACK flag to the server. The confirmation number is set to the sequence number of the FIN message received from the server plus 1.

2.3 Advantages of TCP Client

The advantages of TCP Client mainly include:

Reliable connection: TCP protocol is a reliable transmission protocol, which can ensure the integrity and reliability of data during transmission and avoid the problem of data loss or duplication.

Sequentiality: TCP Client data transmission is received in the order in which it is sent, ensuring the sequentiality of data transmission.

Flow control: The TCP protocol has a flow control mechanism that can avoid the problem of data transmission rate mismatch between the sender and the receiver.

Congestion control: The TCP protocol has a congestion control mechanism that can automatically slow down the sending rate when the network is congested, ensuring the stability and reliability of network communication.

Security: TCP protocol is an encrypted protocol that can ensure the security of data transmission and avoid the problem of data being stolen or tampered with.

Wide application: TCP protocol is a universal network protocol that can be applied on a variety of operating systems and platforms and has good compatibility and portability.

2.4 Application scenarios

The application scenarios of TCP Client are very wide. The following are some main scenarios:

Network communication: TCP Client is widely used in various network communications, including but not limited to remote login, file transfer, email, etc.

Database connection: TCP Client is often used to establish a connection with the database server to realize data transmission and interaction.

Cloud services: Many cloud services, such as Amazon's AWS and Google's GCP, use TCP Client for data interaction and remote management.

Real-time trading system: In the real-time trading system, TCP Client can provide stable and reliable data transmission to ensure the smooth progress of transactions.

Game development: In multiplayer online games, TCP Client can help achieve real-time game state synchronization and data interaction.

Remote control: Through TCP Client, users can remotely connect to other computers and control them.

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.

Compared with the software protocol stack, WIZnet's hardware protocol stack Ethernet chip has the following advantages:

Hardware TCP/IP protocol stack: WIZnet's hardware protocol stack chip provides a hardware-implemented TCP/IP protocol stack. This hardware-implemented protocol stack has better performance and stability than software-implemented protocol stacks.

No additional embedded system software stack and memory resources required: Since all Ethernet transmit and receive operations are handled by the independent Ethernet controller, no additional embedded system software stack and memory resources are required.

Resistant to network environment changes and DDoS attacks: Compared with software TCP/IP protocol stacks that are susceptible to network environment changes and DDoS attacks, hardware protocol stack chips can provide more stable Ethernet performance.

Suitable for low-specification embedded systems: Even in low-specification embedded systems, hardware protocol stack chips using WIZnet can show more efficient Internet application operating performance than high-specification systems using software TCP/IP protocol stacks.

4 TCP_Client 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_Client.py file directly.

Step one: You can see that in the w5x00_init() function, the SPI and serial port are initialized. 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 connect to the remote server. When connected to the server, you can test the data sending and receiving.


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)

destip = '192.168.1.18'
destport = 8000
conn_info = (destip, destport)

''' 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 client example.\r\n')
   
def w5x00_init():
   
   ''' 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)
       
   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 client_loop():
   global conn_flag
   s = socket()
   while(True):
       if(conn_flag== False):
           try:
               s.connect(conn_info) # Destination IP Address
               conn_flag=True
               print("Loopback client Connect!")
               uart.write('Loopback client connect!\r\n')
           except:
               uart.write('connect error\r\n')
               conn_flag=False
       if(conn_flag):
           try:
               data = s.recv(2048)
               data = data.decode('utf-8')
       
               if data != 'NULL' :
                   uart.write('recv from {0}:[{1}]: {2}\r\n'.format(conn_info[0],conn_info[1],data))
                   s.send(data)
           except:
               uart.write('disconnect')
               conn_flag=False
           
def main():
   w5x00_init()
   client_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 and select the server to enable monitoring and wait for the client to connect. After the client connects, you can get a reply by sending a message. 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