UART Serial Communication (51 Microcontroller + Modbus Protocol)
1. Core Concepts and Features of UART
UART (Universal Asynchronous Receiver Transmitter)
A universal asynchronous transceiver, serving as the hardware interface module for asynchronous communication between MCUs and external devices. Key features:
- Asynchronous communication: No clock line, relies on baud rate synchronization.
- Full-duplex communication: Uses independent TXD (transmit) and RXD (receive) lines for simultaneous bidirectional transmission.
- Serial communication: Data is transmitted bit by bit, offering low hardware costs and strong anti-interference.
- Protocol-based communication: Fixed data frame format and communication rules require parameter alignment between parties for successful interaction.
2. Wiring Standards and Hardware Basics
1. Core Pin Definitions
| Pin | Function | Notes |
|---|---|---|
| VCC | Power positive (typically 5V/3.3V) | Must match the power supply of the connected device. |
| GND | Ground | Must share a common ground; otherwise, signal interference may cause communication failure. |
| TXD | Data transmit line | Outputs level signals. |
| RXD | Data receive line | Inputs level signals. |
2. Key Wiring Principles
- Cross-connect TXD and RXD: TXD of Device A → RXD of Device B, RXD of Device A → TXD of Device B.
- Example: When connecting a 51 microcontroller (TXD=P3.1, RXD=P3.0) to a PC USB-to-serial module, connect P3.1 to the module's RXD and P3.0 to the module's TXD.
- Avoid direct same-end connections (e.g., TXD of A to TXD of B), as this prevents data transmission.
3. Communication Modes (Simplex/Half-Duplex/Full-Duplex)
| Mode | Data Lines | Transmission Characteristics | Typical Applications |
|---|---|---|---|
| Simplex | 1 line | Unidirectional transmission; fixed sender/receiver roles. | Radios, IR remotes. |
| Half-Duplex | 1 line | Bidirectional transmission, but only one direction at a time. | Walkie-talkies, I2C communication. |
| Full-Duplex (UART) | 2 lines | Simultaneous bidirectional transmission with independent send/receive paths. | 51 microcontroller-PC communication, Modbus master-slave interaction. |
4. Core Rules of UART Data Transmission
1. Data Transmission Order
UART follows the LSB (Least Significant Bit) first principle. For example, the 8-bit data 0xA6 (binary 10100110):
- Bit order: bit7 (1), bit6 (0), bit5 (1), bit4 (0), bit3 (0), bit2 (1), bit1 (1), bit0 (0).
- Transmission order: bit0 → bit1 → bit2 → bit3 → bit4 → bit5 → bit6 → bit7 (LSB first, MSB last).
2. Serial vs. Parallel Transmission Comparison
| Type | Key Differences | Advantages | Disadvantages |
|---|---|---|---|
| Serial (UART) | 1 data line, bit-by-bit transmission. | Low hardware cost, strong anti-interference, long-distance support. | Slower speed. |
| Parallel | Multiple data lines, simultaneous multi-bit transmission. | High speed. | High cost, weak anti-interference, short-distance only. |
5. UART Data Frame Structure and Timing
A UART data frame consists of 4 parts (without parity):
- Start bit: 1-bit low level (marks the start of data).
- Data bits: 5--9 bits (typically 8 bits), transmitted LSB first.
- Parity bit (optional): 1 bit (odd/even/none) for basic error detection.
- Stop bit: 1--2 bits of high level (marks the end of data; typically 1 bit).
Example timing: Start bit (1 bit) → Data bits (8 bits) → Stop bit (1 bit), totaling 10 bits per frame.
6. Parity Mechanisms (Odd/Even/None)
Parity checks detect bit errors but cannot correct them:
1. Odd Parity
- Parity bit set to 1, ensuring the total number of 1s in "data + parity" is odd.
- Example: Data
0xA6(10100110) has four 1s; parity bit = 1, total 1s = 5 (odd).
2. Even Parity
- Parity bit set to 0, ensuring the total number of 1s in "data + parity" is even.
- Example: Data
0xA6has four 1s; parity bit = 0, total 1s = 4 (even).
3. No Parity
- No parity bit; relies on stable communication conditions.
- Pros: Higher efficiency. Cons: No error detection; suitable for short-distance, low-interference scenarios.
Note: Odd/even parity cannot detect even-numbered bit errors (e.g., bit0 and bit1 flipping simultaneously).
7. Core Serial Communication Parameters (Must Match!)
Both parties must agree on these four parameters; otherwise, data parsing fails. Example format: 9600 8 N 1
| Parameter | Meaning | Common Configurations |
|---|---|---|
| Baud rate | Bits per second (bit/s). | 2400, 4800, 9600, 115200 (9600 most common). |
| Data bits | Number of valid data bits per transmission. | 8 bits (standard). |
| Parity | Error detection bit. | N (none), E (even), O (odd). |
| Stop bits | End-of-frame marker. | 1 bit (standard). |
8. Synchronous vs. Asynchronous Communication
| Type | Key Feature | Typical Applications |
|---|---|---|
| Synchronous | Requires a clock line (e.g., SCLK); synchronized timing. | SPI, I2C. |
| Asynchronous (UART) | No clock line; synchronized via baud rate + start bit. | Serial communication, Modbus. |
9. 51 Microcontroller UART Register Configuration (Key!)
The 51 microcontroller configures UART mode, baud rate, and interrupts via SCON, PCON, and TMOD registers. Essential configurations:
1. SCON Register (Serial Control Register)
- Address: 0x98H (bit-addressable).
- Key bits (critical bits only):
| Bit | Name | Function | Value |
|---|---|---|---|
| B7 | SM0 | UART mode selection. | 0 (with SM1 for 8-bit UART). |
| B6 | SM1 | UART mode selection. | 1 (8-bit UART, variable baud rate). |
| B4 | REN | Receive enable. | 1 (enable reception). |
| B1 | TI | Transmit complete flag. | Set by hardware; cleared by software. |
| B0 | RI | Receive complete flag. | Set by hardware; cleared by software. |
-
Configuration:
cSCON &= ~(3 << 6); // Clear SM0, SM1. SCON |= (1 << 6); // SM1=1, 8-bit UART mode. SCON |= (1 << 4); // REN=1, enable reception.
2. PCON Register (Power Control Register)
-
Address: 0x87H (not bit-addressable).
-
Key bits:
- SMOD (B7): Baud rate doubling. SMOD=1 doubles baud rate; SMOD=0 does not.
- SMOD0 (B6): Frame error detection. SMOD0=0 enables SM0/SM1 mode selection.
-
Configuration:
cPCON &= ~(1 << 6); // SMOD0=0, enable SM0/SM1 mode. PCON |= (1 << 7); // SMOD=1, double baud rate.
3. Baud Rate Generation (Timer 1)
The 51 microcontroller generates UART baud rates using Timer 1, typically in 8-bit auto-reload mode . Formula:
\\text{Timer initial value} = 2\^8 - \\frac{2\^{\\text{SMOD}} \\times f_{osc}}{32 \\times \\text{Baud rate} \\times 12}
-
Parameters:
- ( f_{osc} ): Crystal frequency (commonly 11.0592MHz for 51 MCUs).
- SMOD: Baud rate doubling bit in PCON (0 or 1).
-
Example calculation (11.0592MHz, 9600 baud, SMOD=1):
\\text{Initial value} = 256 - \\frac{2\^1 \\times 11059200}{32 \\times 9600 \\times 12} = 256 - 6 = 250
Thus, TH1=0xFA, TL1=0xFA (auto-reload mode: TH1=TL1=initial value).
4. Timer 1 Configuration (Baud Rate Generation)
-
Mode: 8-bit auto-reload (configured via TMOD).
-
Configuration:
cTMOD &= ~(0x0F << 4); // Clear Timer 1 mode bits. TMOD |= (1 << 5); // Timer 1 = 8-bit auto-reload. TH1 = 0xFA; // 9600 baud initial value. TL1 = 0xFA; TCON |= (1 << 6); // Start Timer 1.
5. Interrupt Configuration (Enable UART Interrupt)
c
IE |= (1 << 7); // EA=1, enable global interrupts.
IE |= (1 << 4); // ES=1, enable UART interrupt.
10. 16-bit Timer vs. 8-bit Auto-Reload Timer
| Timer Mode | Key Difference | Applications |
|---|---|---|
| 16-bit Timer | Counter range: 0--65535; manual reload after overflow. | Precise timing (e.g., 1ms interrupts). |
| 8-bit Auto-Reload | Counter range: 0--255; auto-reloads THx value after overflow. | UART baud rate generation (no manual reload). |
11. Master-Slave Communication Model (Core of Modbus)
1. Master
- Controls communication; initiates commands (e.g., toggling slave LEDs).
- Examples: PCs, PLCs, central controllers.
2. Slave
- Responds passively; cannot initiate communication; executes commands and replies.
- Examples: 51 microcontrollers, sensor modules, actuators.
12. Practical Modbus Protocol (Assignment Implementation)
1. Assignment Requirements
The host sends commands according to the Modbus protocol, and the slave (51 MCU) parses the function codes to control corresponding peripherals and returns responses:
- Function code 01: LED control;
- Function code 02: Digital tube control;
- Function code 03: Buzzer control.
2. Modbus Protocol Data Frame Format (Simplified Version)
| Field | Meaning | Example (Control LED On) |
|---|---|---|
| Slave Address | Target slave number (0~255) | 0x01 (51 MCU address) |
| Function Code | Operation type | 0x01 (LED control) |
| Data Segment | Specific control parameters | 0x01 (LED1 on) |
| Checksum | Data integrity check | 0x03 (Sum of first 3 bytes) |
3. Slave Processing Flow (51 MCU Code Logic)
c
// UART interrupt receiving data
void uart_isr(void) interrupt 4 {
if (RI) { // Reception complete
recv_buf[recv_len++] = SBUF; // Store in receive buffer
RI = 0; // Clear receive flag manually
if (recv_len == 4) { // Complete frame received (address + function code + data + checksum)
if (recv_buf[0] == 0x01) { // Match slave address
if (recv_buf[3] == (recv_buf[0]+recv_buf[1]+recv_buf[2])) { // Checksum correct
switch(recv_buf[1]) {
case 0x01: led_control(recv_buf[2]); break; // LED control
case 0x02: seg_control(recv_buf[2]); break; // Digital tube control
case 0x03: beep_control(recv_buf[2]); break; // Buzzer control
}
uart_send_ack(); // Return response frame
}
}
recv_len = 0; // Clear buffer
}
}
if (TI) TI = 0; // Clear transmit flag
}
13. Key Knowledge Review and Practical Suggestions
Core Points
- UART wiring: TXD and RXD must be cross-connected, common ground is critical;
- Communication parameters: Baud rate, data bits, etc. (4 parameters) must be identical;
- Register configuration: SCON (8-bit UART + enable reception), PCON (double baud rate), Timer 1 (8-bit auto-reload);
- Data order: LSB first, parity bit only for simple error detection;
- Modbus protocol: Master-slave structure, function codes correspond to peripheral operations, checksum ensures data integrity.
Practical Suggestions
- Debug basic UART communication first: Achieve data exchange between 51 MCU and PC serial assistant;
- Implement Modbus protocol parsing: Process function codes and responses as per assignment requirements;
- Debugging tools: Use a logic analyzer to capture TXD/RXD waveforms and verify data frame correctness;
- Common issues: If communication fails, check wiring → parameters → register configuration → checksum in order.
Summary
UART serial communication is fundamental in embedded development, with the core principles being "protocol consistency + hardware correctness + accurate register configuration." Mastering the theoretical knowledge and practical approaches in this article will enable you to easily complete the assignment of controlling peripherals via the Modbus protocol while laying a foundation for future industrial communication, sensor data transmission, and other scenarios. It is recommended to practice coding and debugging extensively, validate understanding through actual waveforms and data, and avoid rote memorization.