1. Introduction
1. Why use Ethernet for communication?
Ethernet refers to a local area network that complies with the IEEE 802.3 standard. It is a type of internet technology, and since it occupies the highest proportion in networking technology, many people directly equate Ethernet with the internet. However, IEEE also has other local area network standards, such as IEEE 802.11, which is a wireless local area network, commonly known as Wi-Fi. IEEE 802.15 is a personal area network, which includes Bluetooth technology, and the 802.15.4 standard is for ZigBee technology.
Industrial Ethernet is a type of industrial network developed based on Ethernet technology and TCP/IP technology. In industry, due to the low training costs for Ethernet users, mature product technology, low prices, stable supply, and easy information integration, its application range is quite broad, making it important to use on STM32.
The protocol used by Ethernet is the TCP/IP communication protocol.
2. What is TCP/IP?
TCP/IP is a large protocol family, a collection of many network protocols, including ARP, IP, ICMP, UDP, TCP, DNS, DHCP, HTTP, FTP, MQTT, etc. Different protocols in the TCP/IP protocol stack perform different functions, and the implementation of certain protocols depends on others. Based on this dependency, the protocol stack can be layered. Lower-layer protocols provide services to adjacent upper-layer protocols and form the basis for the implementation of upper-layer protocols.
3. What is the TCP/IP layered model?
The TCP/IP model is divided into four layers: application layer, transport layer, network layer, and network interface layer. Layering allows different lower-layer network cards to independently implement their functions, such as the physical layer providing binary transmission and encoding to provide a standard interface for the network layer, without needing to care about the internal implementation.
Transmission process: For example, if you send a QQ message to your friend A saying, “Are you coming out to play this weekend?” When you press “send” or the enter key, how does the computer transmit this information?
You send the message:
(1) Application layer: It detects that the data being transmitted contains a text message, marks it, adds the application layer header, and sends it to the transport layer.
(2) Transport layer: Since the other party also needs to receive the message via QQ, it uses a “port” (there are many programs on the computer, and different programs are identified by different ports), marks the port, adds the TCP header, and sends it to the network layer.
(3) Network layer: Since the network consists of countless subnets, to send the information to the other party’s computer, it needs to use the IP address to send the data to the corresponding subnet to find the corresponding IP address (the IP address includes the network number and host number; if the network numbers are the same, it is determined to be in the same subnet). It marks it, adds the IP header, forms an IP packet, and sends it to the link layer.
(4) Data link layer: Each computer connected to the network has a network card interface, and each network card has a unique address called the “MAC address.” Data transmission between computers is uniquely identified and transmitted using the MAC address (the MAC address consists of 48 bits of binary, which uniquely identifies it during network card production). Therefore, when we need to send data, we not only need to find the computer host but also know the MAC address. Suppose the ARP protocol helps us find the target host’s MAC address, but sometimes the information being sent is too large to be sent at once; the link layer will split it into groups and send them out one by one.
(5) Physical layer: It receives the data from the data link layer and transmits it based on binary levels.
Friend A receives the message:
(1) Physical layer: The 0101…. level signal is received, and the physical layer passes the data to the link layer.
(2) Link layer: If the MAC address matches, it checks the data for issues; if there are no issues, it removes the Ethernet header and hands the remaining data to the IP layer.
(3) IP layer: It detects that there is data, removes the IP header, and hands it to the transport layer.
(4) Transport layer: It finds that the destination is the QQ port, removes the TCP header, and hands it to the application layer.
(5) Application layer: The QQ interface displays “Are you coming out to play this weekend?”
4. What is LwIP? How is it related to TCP/IP?
(1) Definition of LwIP:
Lightweight IP, as the name suggests, is a lightweight TCP/IP protocol developed by Adam Dunkels from the Swedish Institute of Computer Science (SICS). It is a small open-source TCP/IP protocol stack.
(2) Purpose of LwIP design: To implement a relatively complete TCP/IP protocol stack with minimal resource consumption. It can be used for pan-tilt access, wireless gateways, remote modules, industrial controllers, routers, cameras, etc.
(3) Differences between LwIP and TCP/IP:
[1] LwIP does not implement all functions of TCP/IP.
[2] It greatly reduces RAM usage.
[3] LwIP can run on an operating system or operate independently without an operating system.
[4] LwIP does not adopt a clear layered structure; it assumes that some data and structures between layers are visible to other layers. In simple terms, the transport layer knows how the IP layer encapsulates and transmits data, and the IP layer knows how the link layer encapsulates data, etc. This allows for shared memory areas, greatly avoiding data copying and minimizing usage.
(4) Features of LwIP:
[1] Low resource overhead, highly customizable; all unnecessary functions can be removed through configuration options. LwIP runs smoothly with about 40KB of code ROM and tens of KB of RAM.
[2] A relatively complete set of supported protocols.
[3] Implements some common applications, such as DHCP client, DNS client, HTTP server, etc.
[4] Provides three programming interfaces: RAW/Callback API (suitable for few tasks, small data interaction, and low data processing time overhead), NETCONN API (sequential API, suitable for multitasking, large data volumes, and large applications), and Socket API (a simple wrapper around the NETCONN API, easier but less efficient and incomplete in functionality).
[5] Highly portable. Its source code is entirely implemented in C.
[6] Open-source and free, allowing users to use it without bearing any commercial risks.
[7] Long development history.
5. What is the LwIP protocol stack?
The protocol stack is the specific implementation of the protocol, simply put, it is a library function implemented in code, allowing developers to call it. Therefore, we download the latest version from the LwIP website, integrate the code files into our project, and use the interface functions provided by LwIP to implement TCP communication in our program.
6. What do the “three-way handshake” and “four-way handshake” of TCP mean?
TCP is a connection-oriented transport protocol. Simply put, UDP is like your mom shouting from downstairs for you to come help; everyone can hear it, and you might not hear it clearly. TCP is like your mom calling you on the phone; the information is transmitted one-on-one and is stable.
The “three-way handshake” is a method to confirm the connection: Simply put, it uses three sends to let both parties confirm that their sending and receiving are normal. First, A: I want to communicate with B. Second, B: Okay, I can communicate with you (when A receives this message, A has confirmed the reliability of the connection, but B cannot confirm whether A can hear its reply). Third, A: I can hear your reply; we can start now. (At this point, both parties have confirmed the reliability of the connection). If the handshake attempts fail after 5 tries, the connection is dropped.
The “four-way handshake” is a method to confirm the disconnection: Simply put, it uses four sends to let both parties confirm the disconnection. First, A: I need to go do something else; I won’t talk to you anymore. Second, B: I still have half of what I want to say; let me finish before you go. Third, B: Okay, I finished; you can go. Fourth, A: Okay, I’m leaving (after A sends this, it will wait for 2 milliseconds; if it receives B’s release message, it indicates that B has received the release signal, and the connection is disconnected). If B does not receive the fourth wave of disconnection, it will repeat sending the third release signal. After A sends, it will wait for 2 milliseconds; if it still receives B’s third wave of disconnection signal, it indicates that B did not receive the fourth wave of disconnection, and A will repeat the fourth wave of disconnection again.
2. Overview of STM32F4 Ethernet MAC
The Ethernet MAC exists in the data link layer of the TCP/IP stack. The STM32F4 has a built-in 10/100Mbit/s Ethernet MAC core.
This Ethernet MAC core has the following features:
Supports external PHY interface for 10M/100Mbit/s data transmission rates.
Communicates with external fast Ethernet PHY via MII interface compliant with IEEE802.3.
Supports full-duplex and half-duplex operation.
Inserts header and frame start data (SFD) in the sending path and removes them in the receiving path.
Can control CRC and pad generation on a per-frame basis.
Programmable frame length, supporting jumbo frames up to 16kB…
From the figure, we can see:
Data starts from the chip, transmitted via Ethernet DMA, received and sent through FIFO registers, processed by MAC, and then sent to external PHY via clock line MDC and data line MDIO.
The size of the Ethernet receive and transmit FIFO data registers is 2KB (the transmitted data cannot exceed 1500 bytes), and the STM32F4 Ethernet is managed through RMII and MII interfaces with external PHY.
The F4 MAC interface has three interfaces: SMI, MII, RMII.
1. Station Management Interface: SMI
This interface allows access to PHY registers in the program. The SMI interface has two lines: data line MDIO and clock line MDC, supporting access to up to 32 PHYs.
MDC: Periodic clock, provides reference timing for data transmission at a maximum frequency of 2.5MHz. In idle state, the SMI management interface drives the MDC clock signal low.
MDIO: Data input/output bit stream used to synchronize status information to/from the PHY device via the MDC clock signal.
Management frame format: (STM32F4XX Chinese Reference Manual P825)
PADDR: PHY address
RADDR: Register address
Data bits: 16-bit data bits (PHY registers are all 16 bits)
2. Media Independent Interface: MII
The Media Independent Interface (MII) defines the connection between the Ethernet core and PHY device at data transmission rates of 10Mbit/s and 100Mbit/s.
TX_CLK and RX_CLK are continuous clocks for sending and receiving. When the rate is 10Mbit/s, it is 2.5MHZ; when the rate is 100Mbit/s, it is 25MHZ.
To generate TX_CLK and RX_CLK clocks, a 25MHZ clock must be provided to the external PHY. Typically, we use a 25M crystal oscillator, or we can use the MCO pin of STM32F4xx to output a 25MHZ clock.
3. Reduced Media Independent Interface: RMII
The Reduced Media Independent Interface (RMII) specification reduces the number of pins between the microcontroller Ethernet peripheral and the external PHY at 10/100 Mbit/s. According to the IEEE 802.3u standard, MII includes 16 pins for data and control signals. The RMII specification reduces the number of pins to 9.
The reference clock for both MAC and PHY must be 50 MHz!
3. PHY Layer Chip LAN8720
RJ45 <-> PHY Chip <-> Ethernet MAC
It is a low-power 10/100M Ethernet PHY layer chip that communicates with the Ethernet MAC layer using the RMII interface, built-in full-duplex module, supporting 10Mbps and 100Mbps. It can automatically adjust to the best connection method with the destination host. It supports auto-flip functionality, allowing the connection to be changed to straight-through or crossover without changing the cable.
1. Schematic Diagram
(1) STM32 Pins:
(2) EARTHNET:
(3) RJ45:
(4) PCF8574
IO expansion chip
2. LAN8720 Description
(1) PHY Address
As mentioned above, the MAC can connect to 32 PHY chips via the SML interface. How to distinguish these 32 PHYs? It is through the PHY address.
Since pin 10 in the schematic diagram is floating, it defaults to address 0x00.
(2) RMII Mode Settings
LAN8720 can be set to two connection modes in RMII mode:
REF_CLK input mode (nINT) and REF_CLK output mode.
The configuration mode determines the function of the nINT / REFCLKO pin. The nINTSEL configuration is locked on the rising edge of POR and nRST. By default, the nINTSEL is configured to nINT mode through an internal pull-up resistor.
REF_CLK comes from external sources and must be driven on the XTAL1 / CLKIN pin.
i. REF_CLK Input Mode
In REF_CLK input mode, the XTAL1/CLKIN pin drives a 50 MHz REF_CLK. When using this mode, an external 50 MHz source must be provided for REF_CLK. As shown, the clock drives both MAC and PHY simultaneously.
ii. REF_CLK Output Mode
To reduce BOM costs, this device has the capability to generate RMII REF_CLK signals from a low-cost 25 MHz crystal. Compared to the typically required 50 MHz third harmonic crystal, this type of crystal is cheaper. The MAC must be able to work with the external clock to utilize this feature.
Obtaining REF_CLK from a 25 MHZ crystal:
In some system architectures, a 25 MHz clock source can be used. This device can generate REF_CLK for the MAC; in this specific example, only a 25 MHz clock can be used (the clock cannot be 50 MHz). Similar to the 25 MHz crystal mode, the nINT function is disabled.
Obtaining REF_CLK from an external 25 MHZ source:
3. PHY Registers
LAN8720 has 32 registers, each with 16 bits.
These 32 registers are divided into two categories:
Standard registers: Registers 0-15 are defined according to IEEE standards (especially BCR and BSR registers are set according to user-implemented functions).
Free-defined registers: Registers 16-31 are freely defined by the chip manufacturer (generally do not need modification).
In the example code from the original point atom
PHY_SR=0X1F refers to the 31st register (as shown in the register above).
PHY_SPEED_STATUS=0X0004 indicates that the PHY speed is 100Mbit/s (configured according to the register above).
PHY_DUPLEX_STATUS=0X0010 indicates half-duplex transmission mode (configured according to the register above).
4. Ethernet DMA Descriptor
Students who have studied STM32-DMA should know that DMA can achieve data exchange between memory and peripherals without CPU involvement. Similarly, the role of Ethernet DMA in STM32 interconnect microcontrollers is the same; it facilitates data exchange between memory and Ethernet peripherals without CPU involvement. Simply put, we place the data to be sent in a memory area, inform the Ethernet DMA that we have placed the data, and it will retrieve it and send it to the network; when network data arrives, the Ethernet DMA automatically copies the data to a memory area and interrupts the CPU to inform it that data has arrived, prompting the CPU to retrieve it.
Sending: Without CPU involvement, the data in the buffer pointed to by the descriptor is transmitted to the TX FIFO.
Receiving: Without CPU involvement, the data from the RX FIFO is transmitted to the buffer pointed to by the descriptor.
Descriptors are divided into:
Regular descriptors: Manage buffers.
Enhanced descriptors: Enable timestamps and IPV4 on the basis of regular descriptors (content not discussed).
Descriptors are not actual physical structures but are implemented in the program through software; they are essentially structures.
Structure code for regular descriptors:
TX DMA descriptor member variables:
TDES0[31] set to 0: The CPU can copy data into the descriptor; after copying is complete, it sets this position to 1, indicating to DMA that it can send it out.
TDES0[20] set to 1: The second address in the descriptor is the address of the next descriptor [ST Ethernet driver library sets TDES0[20] to 1].
TDES0[28:16]: If TDES0[20] is set to 1, this field is invalid.
TDES0[31:0]: Depending on the value of TDES0[20], if it is 1, it points to the address of the next descriptor.
RX DMA descriptor member variables:
RDES0[31] set to 0: The MAC transfers data from the RX FIFO to the RX descriptor; after copying is complete, it sets this position to 0, indicating to the CPU that it can receive data.
RDES0[14] set to 1: The second address in the descriptor is the address of the next descriptor [ST Ethernet driver library sets RDES0[14] to 1].
RDES0[28:16]: If RDES0[14] is set to 1, this field is invalid.
RDES0[31:0]: Depending on the value of RDES0[14], if it is 1, it points to the address of the next descriptor.
STM32 ETH-DMA descriptors (only regular descriptors are used, enhanced descriptors are not used):
ETH for sending and receiving application memory:
Sending: Network layer issues pbuf->copy to TXFIFO->MAC->PHY (optical signal);
Receiving: External->PHY->MAC->RXFIFO->Network layer
Among them, ETH_TX_BUF_SIZE = ETH_MAX_PACKET_SIZE descriptor maximum length is 1524.
The Ethernet driver library provided in STM32 uses linked structures:
Descriptor notes:
1. An Ethernet data packet can span one or more DMA descriptors.
2. A DMA descriptor can only be used for one Ethernet data packet.
3. The last descriptor in the DMA descriptor list points to the first, forming a chain structure.
4. Key Code Analysis of Original Point Atom
The overall process is as follows:
1. LwIP Initialization
-
// LwIP initialization (used when starting LwIP)
-
// Return value: 0, success
-
// 1, memory error
-
// 2, LAN8720 initialization failed
-
// 3, network card addition failed.
-
u8 lwip_comm_init(void)
-
{
-
u8 retry=0;
-
struct netif *Netif_Init_Flag; // Return value when calling netif_add() function, used to determine if network initialization is successful
-
struct ip_addr ipaddr; // IP address
-
struct ip_addr netmask; // Subnet mask
-
struct ip_addr gw; // Default gateway
-
if(ETH_Mem_Malloc())return 1; // Memory allocation failed
-
if(lwip_comm_mem_malloc())return 2; // Memory allocation failed
-
lwip_comm_default_ip_set(&lwipdev); // Set default IP and other settings
-
while(LAN8720_Init()) // Initialize LAN8720, if it fails, retry 5 times
-
{
-
retry++;
-
if(retry>5) {retry=0;return 3;} // LAN8720 initialization failed
-
}
-
lwip_init(); // Initialize LwIP kernel
-
#if LWIP_DHCP // Use dynamic IP
-
ipaddr.addr = 0;
-
netmask.addr = 0;
-
gw.addr = 0;
-
#else // Use static IP
-
IP4_ADDR(&ipaddr,lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]);
-
IP4_ADDR(&netmask,lwipdev.netmask[0],lwipdev.netmask[1] ,lwipdev.netmask[2],lwipdev.netmask[3]);
-
IP4_ADDR(&gw,lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]);
-
printf(“The MAC address of the network card is:…………….%d.%d.%d.%d.%d.%d\r\n”,lwipdev.mac[0],lwipdev.mac[1],lwipdev.mac[2],lwipdev.mac[3],lwipdev.mac[4],lwipdev.mac[5]);
-
printf(“Static IP address……………………%d.%d.%d.%d\r\n”,lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]);
-
printf(“Subnet mask……………………..%d.%d.%d.%d\r\n”,lwipdev.netmask[0],lwipdev.netmask[1],lwipdev.netmask[2],lwipdev.netmask[3]);
-
printf(“Default gateway……………………..%d.%d.%d.%d\r\n”,lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]);
-
#endif
-
Netif_Init_Flag=netif_add(&lwip_netif,&ipaddr,&netmask,&gw,NULL,ðernetif_init,ðernet_input);// Add a network interface to the network card list
-
#if LWIP_DHCP // If using DHCP
-
lwipdev.dhcpstatus=0; // DHCP marked as 0
-
dhcp_start(&lwip_netif); // Start DHCP service
-
#endif
-
if(Netif_Init_Flag==NULL)return 4;// Network card addition failed
-
else// After successfully adding the network interface, set netif as the default value and open the netif network interface
-
{
-
netif_set_default(&lwip_netif); // Set netif as the default network interface
-
netif_set_up(&lwip_netif); // Open netif network interface
-
}
-
return 0;// Operation OK.
-
}
(1) ETH_Mem_Malloc():
Allocates memory for descriptors and buffers. In addition to this algorithm-based memory allocation function, the official example from ST uses simple arrays to implement memory allocation.
(2) Determine whether to enable DHCP (dynamic IP)
If not enabled, use static IP: request remote IP address, network card MAC address, local IP address, subnet mask, default gateway.
(3) Ethernet Environment Configuration
Configure the Ethernet environment and initialize the RMII IO (by calling the HAL_ETH_Init function, which will call the HAL_ETH_MspInit function to initialize the corresponding interface IO and reset the PHY chip pins); reset the PHY chip (very important, without resetting, Ethernet communication cannot succeed).
(4) Initialize LwIP Kernel
This is a function included in the LwIP kernel source code, initializing a series of functions such as sys_init(), mem_init(), pbuf_init(), netif_init().
2. Add Virtual Network Card
LwIP is software; how does it manage real Ethernet hardware? For example, there are various network interfaces, such as Wi-Fi and Ethernet interfaces. How to manage these actual network interfaces? LwIP abstracts a virtual network card to manage these various hardware network interfaces.
(1) ethernetif_init:
Network card initialization, setting virtual network card parameters. This function has already implemented the overall framework for us in the ethernetif.c file. It will call the low_level_init function, which initializes the sending and receiving descriptors and enables ETH interrupts.
(2) err_t low_level_init:
Initializes sending and receiving descriptors and enables ETH interrupts.
(3) ethernetif_input:
Ethernet packet input; here LwIP has already implemented the framework for us. The virtual network card is activated: data is received through low_level_input, and then processed using the input field (a function) in the netif structure.
3. Virtual Network Card Control Block
4. Sending Process
5. Receiving Process
There are two ways to receive data packets: one is polling to receive data packets, and the other is interrupt-based receiving of data packets.
Statement: We respect originality and value sharing; the text and images are copyrighted by the original author. The purpose of reprinting is to share more information and does not represent the position of this account. If your rights are infringed, please contact us in a timely manner, and we will delete it as soon as possible. Thank you!
Original link:
https://blog.csdn.net/m0_73409202/article/details/142433531