DAY53 UART Serial Communication

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):

  1. Start bit: 1-bit low level (marks the start of data).
  2. Data bits: 5--9 bits (typically 8 bits), transmitted LSB first.
  3. Parity bit (optional): 1 bit (odd/even/none) for basic error detection.
  4. 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 0xA6 has 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:

    c 复制代码
    SCON &= ~(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:

    c 复制代码
    PCON &= ~(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:

    c 复制代码
    TMOD &= ~(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

  1. UART wiring: TXD and RXD must be cross-connected, common ground is critical;
  2. Communication parameters: Baud rate, data bits, etc. (4 parameters) must be identical;
  3. Register configuration: SCON (8-bit UART + enable reception), PCON (double baud rate), Timer 1 (8-bit auto-reload);
  4. Data order: LSB first, parity bit only for simple error detection;
  5. Modbus protocol: Master-slave structure, function codes correspond to peripheral operations, checksum ensures data integrity.

Practical Suggestions

  1. Debug basic UART communication first: Achieve data exchange between 51 MCU and PC serial assistant;
  2. Implement Modbus protocol parsing: Process function codes and responses as per assignment requirements;
  3. Debugging tools: Use a logic analyzer to capture TXD/RXD waveforms and verify data frame correctness;
  4. 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.

相关推荐
上海云盾-小余1 小时前
精准抵御流量攻击:高防 IP + 游戏盾组合部署实战详解
网络·tcp/ip·游戏
czhaii1 小时前
基于Arm Cortex-M7内核GD32H7
单片机·嵌入式硬件
番茄灭世神1 小时前
MCU开发常见软件BUG总结(持续更新)
c语言·stm32·单片机·嵌入式·gd32
okiseethenwhat1 小时前
TCP拥塞控制算法原理详解
tcp/ip
wanghanjiett1 小时前
双轮平衡车建模及控制 2 PID控制原理与调参
嵌入式硬件·控制算法
江畔何人初1 小时前
TCP的三次握手与四次挥手
linux·服务器·网络·网络协议·tcp/ip
m0_738120721 小时前
网络安全编程——Python编写基于UDP的主机发现工具(解码IP header)
python·网络协议·tcp/ip·安全·web安全·udp
EVERSPIN1 小时前
SQPI PSRAM为单片机提供RAM扩展方案
单片机·嵌入式硬件·psram·sqpi psram
Ar-Sr-Na2 小时前
STM32现代化AI开发指南-VSCode环境配置(macOS)
c语言·人工智能·vscode·stm32·嵌入式硬件·硬件工程
进击的小头2 小时前
第6篇:嵌入式芯片算力核心来源:多级流水线架构与指令并行机制详解
单片机·嵌入式硬件·架构