---
title: "4. W5100S/W5500+RP2040 Raspberry Pi Pico＜TCP Server Data Loopback Test＞"
url: "https://maker.wiznet.io/ronpang/projects/4-w5100s-w5500-rp2040-raspberry-pi-picotcp-server-data-loopback-test/"
markdown_url: "https://maker.wiznet.io/ronpang/projects/4-w5100s-w5500-rp2040-raspberry-pi-picotcp-server-data-loopback-test/md"
type: "UCC: User Created Content"
author: "WIZnet HK"
author_url: "https://blog.csdn.net/WIZnet2012/article/details/134043893?spm=1001.2014.3001.5502"
editor: "WIZnet"
editor_url: "https://maker.wiznet.io/"
original_author: "WIZnet HK"
original_url: "https://blog.csdn.net/WIZnet2012/article/details/134043893?spm=1001.2014.3001.5502"
published: "2023-11-13"
language: "en"
hardware: ["WIZnet W5100S-EVB-Pico", "WIZnet W5500-EVB-Pico"]
likes: 0
views: 376
comments: 0
source: "WIZnet Makers (https://maker.wiznet.io/)"
---

# 4. W5100S/W5500+RP2040 Raspberry Pi Pico＜TCP Server Data Loopback Test＞

> 4. W5100S/W5500+RP2040 Raspberry Pi Pico＜TCP Server Data Loopback Test＞

Original author: WIZnet HK (source: https://blog.csdn.net/WIZnet2012/article/details/134043893?spm=1001.2014.3001.5502)

## Components

- **WIZnet W5100S-EVB-Pico** x 1 ([docs](https://docs.wiznet.io/Product/Chip/Ethernet/W5100S/w5100s-evb-pico))
- **WIZnet W5500-EVB-Pico** x 1 ([docs](https://docs.wiznet.io/Product/Chip/Ethernet/W5500/w5500-evb-pico))

## Documents and links

- [Code for this article](https://gitee.com/wiznet-hk/W5100_W5500_C_SDK) (code)
- [WIZnet Official Website](https://www.wiznet.io/)
- [WIZnet Official library Github](https://github.com/Wiznet/ioLibrary_Driver)
- [YouTube Video](https://youtu.be/Cc2L86AFcsY)

## Article

### 1 Introduction

In computer networks, TCP Server is an indispensable role. It is responsible for monitoring and responding to connection requests from clients, processing data exchange, and providing a reliable, stable and efficient network communication service.

This article will take TCP Server as the core and perform data loopback testing on the device in TCP Server mode.

W5100S/W5500 is an embedded Ethernet controller integrating a full hardware TCP/IP protocol stack. It is also an industrial-grade Ethernet control chip. Using the W5500 in Ethernet applications makes it easier for users to connect and communicate remotely between devices.

### 2. Introduction to the protocol

#### 2.1 Brief description

TCP (Transmission Control Protocol) is a connection-oriented, reliable, byte stream-based transmission protocol used to transmit data on computer networks. TCP Server refers to the server-side connection of TCP network services, which is used to receive client connection requests and establish connections to realize network data interaction.

The main function of TCP Server is to monitor client connection requests, establish and manage connections, and achieve reliable transmission of data. Through TCPServer, multiple clients can establish connections with the server at the same time to realize multi-point transmission of data.

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). ˆ

Therefore, TCP Server can help devices achieve multi-point data interaction and is one of the important ways for device network communication. TCP Server is widely used in industrial automation, Internet of Things, smart home and other applications.

#### 2.2 Advantages

**Support multiple clients to connect at the same time: **The TCP server can handle the connection requests of multiple clients at the same time, so that multiple clients can interact with the server at the same time.

**Does not block the server's main thread: **TCP servers usually use asynchronous programming when designing. The main thread will not be blocked and can continue to process other tasks or accept new connection requests.

**High reliability: **The TCP protocol ensures the correctness and reliability of data transmission through the confirmation mechanism and retransmission mechanism to avoid data loss or disorder.

**Full-duplex transmission:** The TCP protocol supports full-duplex transmission, which allows data to be sent and received at the same time, improving the efficiency of data transmission.

**Transmission in byte stream mode: **TCP protocol transmits byte sequences in units of bytes. This method is flexible and simple and can adapt to data transmission needs of different sizes.

**Emergency data transmission function: **TCP protocol supports emergency data transmission function, which allows the server to process emergency data with priority, improving the response speed and real-time performance of the system.

#### 2.3 Application

**Database connection: **TCPServer can monitor connection requests from the client, create a new thread for each request, process the client's request, and return a response.

**File transfer:** Use TCPServer to build a reliable file transfer service. After a connection is established between the client and the server, the input/output stream can be used to transfer files.

**Real-time communication:** TCPServer can be used to build real-time communication systems, such as chat applications or online games.

**Remote services: **Through TCPServer, remote services can be provided, such as remote database access, remote file access, etc.

**Online games: **Online games are one of the most common uses of TCPServer. The game client and server communicate through TCP connections, and the server processes the game logic and returns a response.

**E-commerce: **TCPServer can be used for e-commerce applications, such as processing user login, payment and shopping cart.

### 3. WIZnet Ethernet chip

| **Model** | **Embedded Core** | **Host I/F** | **TX/RX Buffer** | **HW Socket** | **Network Performance** |
| --- | --- | --- | --- | --- | --- |
| W5100S | TCP/IPv4， MAC & PHY | 8bit BUS, SPI | 16KB | 4 | Max.25Mbps |
| W6100 | TCP/IPv4/IPv6, MAC & PHY | 8bit BUS, Fast SPI | 32KB | 8 | Max.25Mbps |
| W5500 | TCP/IPv4, MAC & PHY | Fast SPI | 32KB | 8 | Max 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 data loopback test

#### 4.1 Program flow chart

![](https://maker.wiznet.io/upload/ckeditor5/56044877%5F1699874545%2Epng)

### **4.2 Test preparationSoftware:**

Visual Studio Code

WIZnet UartTool

SocketTester

**Hardware:**

W5100SIO module + PR2040 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) &lt;----> USB_TTL_RX

RP2040 GPIO1 (UART0 RX) &lt;----> USB_TTL_TX

When using the module to connect RP2040 for wiring

RP2040 GPIO016 &lt;----> W5100S MOSI

RP2040 GPIO017 &lt;----> W5100S CS

RP2040 GPIO018 &lt;----> W5100S SCK

RP2040 GPIO019 &lt;----> W5100S MOSI

RP2040 GPIO020 &lt;----> W5100S RST

Directly connect to the PC network port through a network cable (or: both the PC and the device are connected to the switch or router LAN port through a network cable)

#### 4.4 Related code

We directly open the tcp_server.c file (path: examples/tcp_server/tcp_server.c) to see the specific implementation:

You can see that the network information is configured in dhcp mode. Therefore, after the master control and W5100S are initialized, DHCP initialization will be performed, and then a timer initialization will be added for timing during the dhcp process for timeout processing; then enter dhcp configures the network information. If it succeeds, it will directly enter the loop to call the loopback test function. If it fails, it will use the static I network information we initialized to configure, and then enter the loop to call the loopback test function, as shown below:

```
/* Network information to be configured. */
wiz_NetInfo net_info = {
    .mac = {0x00, 0x08, 0xdc, 0x1e, 0xed, 0x2e}, // Configured MAC address
    .ip = {192, 168, 1, 10},                     // Configured IP address
    .sn = {255, 255, 255, 0},                    // Configured subnet mask
    .gw = {192, 168, 1, 1},                      // Configured gateway
    .dns = {8, 8, 8, 8},                         // Configured domain address
    .dhcp = NETINFO_DHCP};                       // Configured dhcp model,NETINFO_DHCP:use dhcp; NETINFO_STATIC: use static ip.
​
wiz_NetInfo get_info;
static uint8_t ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {
    0,
};                                   // Send and receive cache
static uint16_t local_port = 8000;   // Local port
static uint8_t dhcp_get_ip_flag = 0; // Define the DHCP acquisition flag
​
int main()
{
    struct repeating_timer timer; // Define the timer structure
​
    /* MCU init */
    stdio_init_all();     // Initialize the main control peripheral
    wizchip_initialize(); // Initialize the chip interface
​
    /*dhcp init*/
    DHCP_init(SOCKET_ID, ethernet_buf);                                   // DHCP initialization
    add_repeating_timer_ms(1000, repeating_timer_callback, NULL, &timer); // Add DHCP 1s Tick Timer handler
​
    printf("wiznet chip tcp server example.\r\n");
    network_init(&net_info);              // Configuring Network Information
    print_network_information(&get_info); // Read back the configuration information and print it
​
    while (true)
    {
        loopback_tcps(SOCKET_ID, ethernet_buf, local_port); // tcp server data loop test
    }
}
```

Jump into the loopback test to see its specific implementation: This function has these parameters, socket port number, data sending and receiving cache, target IP address, and target port; you can fill in the parameters as needed. The whole process polls the socket status through a Swatch state machine, performs corresponding processing according to the difference, and sequentially completes the operations of initialization, opening the port, connecting to the server, and sending back the data after receiving the data; the local port is initialized directly within the function. As follows:

```
/**
 * @brief   tcp server loopback test
 * @param   sn:    socket number
 * @param   buf:   Data sending and receiving cache
 * @param   port:  Listen port
 * @return  value for SOCK_ERRORs,return 1:no error 
*/
int32_t loopback_tcps(uint8_t sn, uint8_t* buf, uint16_t port)
{
   int32_t ret;
   uint16_t size = 0, sentsize=0;
​
#ifdef _LOOPBACK_DEBUG_
   uint8_t destip[4];
   uint16_t destport;
#endif
​
   switch(getSn_SR(sn))
   {
      case SOCK_ESTABLISHED :
         if(getSn_IR(sn) & Sn_IR_CON)
         {
#ifdef _LOOPBACK_DEBUG_
            getSn_DIPR(sn, destip);
            destport = getSn_DPORT(sn);
​
            printf("%d:Connected - %d.%d.%d.%d : %d\r\n",sn, destip[0], destip[1], destip[2], destip[3], destport);
#endif
            setSn_IR(sn,Sn_IR_CON);
         }
         if((size = getSn_RX_RSR(sn)) > 0) // Don't need to check SOCKERR_BUSY because it doesn't not occur.
         {
            if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
            ret = recv(sn, buf, size);
         buf[ret]=0x00;
         printf("recv: %s\n",buf); //print the receive data.
            if(ret <= 0) return ret;      // check SOCKERR_BUSY & SOCKERR_XXX. For showing the occurrence of SOCKERR_BUSY.
            size = (uint16_t) ret;
            sentsize = 0;
​
            while(size != sentsize)
            {
                ret = send(sn, buf+sentsize, size-sentsize);
                if(ret < 0)
                {
                    close(sn);
                    return ret;
                }
                sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
            }
         }
         break;
      case SOCK_CLOSE_WAIT :
#ifdef _LOOPBACK_DEBUG_
         //printf("%d:CloseWait\r\n",sn);
#endif
         if((ret = disconnect(sn)) != SOCK_OK) return ret;
#ifdef _LOOPBACK_DEBUG_
         printf("%d:Socket Closed\r\n", sn);
#endif
         break;
      case SOCK_INIT :
#ifdef _LOOPBACK_DEBUG_
         printf("%d:Listen, TCP server loopback, port [%d]\r\n", sn, port);
#endif
         if( (ret = listen(sn)) != SOCK_OK) return ret;
         break;
      case SOCK_CLOSED:
#ifdef _LOOPBACK_DEBUG_
         //printf("%d:TCP server loopback start\r\n",sn);
#endif
         if((ret = socket(sn, Sn_MR_TCP, port, 0x00)) != sn) return ret;
#ifdef _LOOPBACK_DEBUG_
         //printf("%d:Socket opened\r\n",sn);
#endif
         break;
      default:
         break;
   }
   return 1;
}
```

### **4.5 Test phenomena**

After the hardware connection is correct, compile the burning program (for details, please refer to Chapter 1), select the corresponding COM port, open WIZ UartTool, and fill in the parameters: baud rate 115200, 8 data bits, 1 stop bit, no correction Verification, no flow control, click open after filling in the parameters, observe the information printed on the serial port to obtain the device running status; open SocketTester, fill in the corresponding parameters in the left column, TCP client mode, fill in the information based on the information printed on the serial port Enter the IP and port. After completion, click Connect. After the connection is successful, send data to observe the phenomenon; you can see that the data is successfully sent and returned successfully, as shown in the figure below:

![](https://maker.wiznet.io/upload/ckeditor5/56044877%5F1699874659%2Epng)

## **5. Precautions**

Don't confuse server IP and client IP.

Do not suddenly disconnect the network cable during the interaction after connection, causing a false link.

If we want to use WIZnet's W5500 to implement the example in this chapter, we only need to modify two places:

Find the wizchip_conf.h header file under library/ioLibrary_Driver/Ethernet/ and modify the WIZCHIP macro definition to W5500.

Find the CMakeLists.txt file under the library and set COMPILE_SEL to ON. OFF is W5100S and ON is W5500.

---

Source: https://maker.wiznet.io/ronpang/projects/4-w5100s-w5500-rp2040-raspberry-pi-picotcp-server-data-loopback-test/
