Files
esp32-dev/components/protocol-quick-ref.md
2026-08-05 17:25:09 +08:00

15 KiB
Raw Permalink Blame History

Protocol Quick Reference

类别:reference | 主题:通信协议快速参考 | 信源: 多平台汇总

Table of Contents


I2C (Inter-Integrated Circuit)

Overview

  • Two-wire synchronous serial bus
  • Multi-device: multiple slaves on same bus
  • Addressable: 7-bit (128) or 10-bit (1024) addresses
  • Open-drain: requires external pull-up resistors
  • Half-duplex: bidirectional on single data line

Signal Lines

  • SDADirection=Bidirectional, Type=Open-drain, Description=Serial data
  • SCLDirection=Master→Slave, Type=Open-drain, Description=Serial clock

Speed Modes

  • StandardSpeed=100 kHz, Notes=Universal compatibility
  • FastSpeed=400 kHz, Notes=Most common for sensors
  • Fast PlusSpeed=1 MHz, Notes=Requires stronger pull-ups
  • High SpeedSpeed=3.4 MHz, Notes=Rarely used in hobby projects

Pull-up Requirements

REQUIRED on both SDA and SCL lines.

  • Standard/FastRecommended Value=4.7kΩ, Notes=Most common choice
  • Fast PlusRecommended Value=2.2kΩ, Notes=Stronger pull needed
  • High Speed / Long wiresRecommended Value=1kΩ, Notes=Compensates for capacitance

Calculation Formula:

R = (VCC - VOL) / IOL
R = (3.3V - 0.4V) / 3mA = 967Ω minimum

Consequences of Wrong Value:

  • Too high (>10kΩ): Slow rise times, communication errors, fails at higher speeds
  • Too low (<1kΩ): Excessive current draw, devices cannot pull line LOW, bus contention

Common I2C Addresses (Collision Detection)

  • 0x20-0x27Device(s)=MCP23017 GPIO expander, PCF8574
  • 0x27, 0x3FDevice(s)=PCF8574 LCD backpack
  • 0x29Device(s)=VL53L0X ToF distance sensor
  • 0x39Device(s)=APDS9960 gesture/color sensor
  • 0x3C, 0x3DDevice(s)=SSD1306 OLED display
  • 0x40Device(s)=INA219 current sensor, PCA9685 PWM
  • 0x48-0x4BDevice(s)=ADS1115/ADS1015 ADC
  • 0x50-0x57Device(s)=AT24C EEPROM
  • 0x5ADevice(s)=MLX90614 IR thermometer
  • 0x60Device(s)=Si5351 clock generator
  • 0x68Device(s)=DS3231 RTC, MPU6050 IMU
  • 0x76, 0x77Device(s)=BME280/BMP280 sensor

Note: Many devices have address pins (A0, A1, A2) to resolve conflicts.

Platform Notes

Raspberry Pi:

  • I2C1 (GPIO2/3) is the primary user-accessible bus
  • I2C0 (GPIO0/1) is reserved for HAT EEPROM detection — do not use
  • Enable with dtparam=i2c_arm=on in config.txt
  • Pi 4/5 have additional I2C buses via dtoverlay

ESP32:

  • Any GPIO pair works via GPIO matrix — no fixed pins
  • Convention: GPIO21 (SDA), GPIO22 (SCL)
  • Do NOT use input-only pins (GPIO34-39) — they cannot drive SDA

SPI (Serial Peripheral Interface)

Overview

  • Four-wire synchronous serial bus
  • Full-duplex: simultaneous send and receive
  • One chip select (CS) per slave device
  • No addressing: CS line selects device
  • Push-pull drivers: no pull-ups required on data/clock

Signal Lines

  • MOSIDirection=Master→Slave, Description=Master Out, Slave In
  • MISODirection=Slave→Master, Description=Master In, Slave Out
  • SCLKDirection=Master→Slave, Description=Serial clock
  • CS/SSDirection=Master→Slave, Description=Chip Select (active LOW)

Speed

  • Typical: 1-40 MHz (device dependent)
  • Check slave device datasheet for maximum
  • Longer wires = lower reliable speed

Clock Modes

  • 0CPOL=0, CPHA=0, Clock Idle=LOW, Data Sampled On=Rising edge
  • 1CPOL=0, CPHA=1, Clock Idle=LOW, Data Sampled On=Falling edge
  • 2CPOL=1, CPHA=0, Clock Idle=HIGH, Data Sampled On=Falling edge
  • 3CPOL=1, CPHA=1, Clock Idle=HIGH, Data Sampled On=Rising edge

Note: Mode 0 is most common. Check device datasheet.

Pull-up Requirements

  • MOSI, MISO, SCLK: Generally NOT required (push-pull drivers)
  • CS lines: 10kΩ pull-up recommended to prevent floating during boot/reset

Platform Notes

Raspberry Pi:

  • SPI0 (GPIO7-11) is primary bus — CE0 (GPIO8), CE1 (GPIO7)
  • SPI1 (GPIO16-21) available but conflicts with PCM/I2S audio
  • Enable with dtparam=spi=on in config.txt

ESP32:

  • VSPI (SPI3): GPIO23 (MOSI), GPIO19 (MISO), GPIO18 (SCLK), GPIO5 (CS) — recommended
  • HSPI (SPI2): GPIO13 (MOSI), GPIO12 (MISO), GPIO14 (SCLK), GPIO15 (CS)
  • WARNING: HSPI pins overlap strapping pins! GPIO12 can brick the module if HIGH at boot.
  • Any GPIO can be used via GPIO matrix (except input-only pins for outputs)

UART (Universal Asynchronous Receiver/Transmitter)

Overview

  • Two-wire asynchronous serial communication
  • Point-to-point: one transmitter, one receiver per pair
  • No clock line: baud rate must match on both ends
  • Simple: widely supported, easy to debug

Signal Lines

  • TXDirection=Output, Description=Transmit data (connect to peer's RX)
  • RXDirection=Input, Description=Receive data (connect to peer's TX)
  • RTSDirection=Output, Description=Request to Send (optional flow control)
  • CTSDirection=Input, Description=Clear to Send (optional flow control)

Critical: TX connects to RX, RX connects to TX (crossover).

Common Baud Rates

  • 9600Use Case=Legacy devices, GPS modules
  • 19200Use Case=Some sensors
  • 38400Use Case=Bluetooth modules
  • 57600Use Case=Faster sensors
  • 115200Use Case=Most common default
  • 230400Use Case=High-speed peripherals
  • 460800Use Case=ESP32 flash programming
  • 921600Use Case=Fast data transfer

Frame Format

Standard: 8N1 (8 data bits, No parity, 1 stop bit)

Other formats exist (7E1, 8E1, etc.) but 8N1 covers 95%+ of use cases.

Voltage Levels

  • TTL 3.3VVoltage=0V / 3.3V, Common Devices=RPi, ESP32, modern MCUs
  • TTL 5VVoltage=0V / 5V, Common Devices=Arduino, many modules
  • RS-232Voltage=±12V, Common Devices=PC serial ports

CRITICAL: RS-232 levels (±12V) will DESTROY 3.3V GPIO instantly. Use MAX232 or similar transceiver.

Level Shifting

  • 5V TX → 3.3V RX: Use voltage divider (1kΩ + 2kΩ) or level shifter
  • 3.3V TX → 5V RX: Often works directly (check VIH threshold)
  • Always use bidirectional level shifter for RTS/CTS

Platform Notes

Raspberry Pi:

  • UART0 (GPIO14/15) is primary serial port
  • Conflicts with Bluetooth on Pi 3/4/Zero2W — use dtoverlay=disable-bt or dtoverlay=miniuart-bt
  • Pi 4/5 have additional UARTs via dtoverlay

ESP32:

  • UART0 (GPIO1/3) is USB serial debug — avoid for peripherals
  • UART1 and UART2 are freely available
  • Any GPIO can be assigned via GPIO matrix

PWM (Pulse Width Modulation)

Overview

  • Digital approximation of analog voltage
  • Square wave at fixed frequency
  • Duty cycle controls average voltage
  • Used for: LED dimming, motor speed, servo position, audio

Key Parameters

  • FrequencyDescription=Pulses per second, Typical Range=50 Hz - 100 kHz
  • Duty CycleDescription=HIGH time percentage, Typical Range=0-100%
  • ResolutionDescription=Steps of duty control, Typical Range=8-bit (256) to 16-bit (65536)

Average Voltage: Vavg = VCC × (Duty Cycle / 100)

Frequency by Application

  • LED dimmingFrequency=500-5000 Hz, Reason=>500Hz avoids visible flicker
  • Servo controlFrequency=50 Hz, Reason=Standard RC servo protocol (20ms period)
  • Motor controlFrequency=1-20 kHz, Reason=Higher = less audible whine
  • Audio generationFrequency=20-100 kHz, Reason=Above audible range
  • Switching PSUFrequency=50-500 kHz, Reason=Efficiency vs. noise tradeoff

Servo Control Specifics

  • Period: 20ms (50 Hz)
  • Pulse width: 1ms (0°) to 2ms (180°)
  • Neutral: 1.5ms (90°)
  • Duty cycle: 5% (1ms) to 10% (2ms) at 50Hz

Platform Notes

Raspberry Pi:

  • 2 hardware PWM channels only
  • PWM0: GPIO12 (preferred) or GPIO18 (conflicts with audio)
  • PWM1: GPIO13 (preferred) or GPIO19 (conflicts with audio)
  • Software PWM available on any pin but less precise (jitter)
  • Enable with dtoverlay=pwm or dtoverlay=pwm-2chan

ESP32:

  • LEDC peripheral: 16 channels of hardware PWM
  • Can output on any output-capable GPIO
  • Cannot use input-only pins (GPIO34-39)
  • Configurable resolution (1-16 bit) and frequency
  • Motor Control PWM (MCPWM) for advanced motor control

1-Wire

Overview

  • Single-wire bidirectional bus
  • Parasitic power option (power over data line)
  • Each device has unique 64-bit ROM ID
  • Multiple devices on same bus (addressed by ROM)
  • Open-drain: requires pull-up resistor

Signal Line

  • DQType=Bidirectional, Open-drain, Description=Data and (optionally) power

Pull-up Requirement

REQUIRED: 4.7kΩ to VCC (3.3V or 5V depending on devices)

  • Stronger pull-up (2.2kΩ-1kΩ) for long cables or many devices
  • Parasitic power mode may need stronger pull-up during temperature conversion

Common 1-Wire Devices

  • DS18B20Function=Temperature sensor, Notes=Most popular 1-Wire device
  • DS18S20Function=Temperature sensor, Notes=Older, 9-bit only
  • DS2401Function=Serial number, Notes=Silicon serial number
  • DS2413Function=GPIO, Notes=2-channel I/O
  • iButtonFunction=Various, Notes=Key fobs, access control

Platform Notes

Raspberry Pi:

  • Default pin: GPIO4
  • Enable with dtoverlay=w1-gpio
  • Change pin with dtoverlay=w1-gpio,gpiopin=N
  • Kernel driver handles protocol automatically

ESP32:

  • Any GPIO can be used via OneWire library
  • GPIO4 is common convention
  • Requires software library (no hardware peripheral)

CAN (Controller Area Network)

Overview

  • Differential two-wire bus (noise immune)
  • Multi-master: any node can initiate
  • Message-based: no addresses, messages have IDs
  • Priority: lower message ID = higher priority
  • Error detection: CRC, ACK, bit stuffing
  • Common in: automotive, industrial, robotics

Signal Lines

  • CAN_HDescription=CAN High (dominant = 3.5V)
  • CAN_LDescription=CAN Low (dominant = 1.5V)

Note: Requires transceiver chip (GPIO cannot drive CAN directly)

Common Transceivers

  • MCP2551Voltage=5V, Notes=Classic, widely available
  • SN65HVD230Voltage=3.3V, Notes=Good for ESP32/RPi
  • TJA1050Voltage=5V, Notes=Automotive grade

Speed and Termination

  • 125 kbpsMax Bus Length=500m, Use Case=Long distance
  • 250 kbpsMax Bus Length=250m, Use Case=General purpose
  • 500 kbpsMax Bus Length=100m, Use Case=Automotive
  • 1 MbpsMax Bus Length=40m, Use Case=High speed

Termination: 120Ω resistor at each end of bus (two total). Many transceiver modules have onboard termination jumper.

Platform Notes

Raspberry Pi:

  • No built-in CAN controller
  • Requires external MCP2515 (SPI-to-CAN) + transceiver
  • Enable with dtoverlay=mcp2515-can0,oscillator=8000000,interrupt=25
  • Uses SocketCAN interface

ESP32:

  • Built-in TWAI controller (CAN 2.0B compatible)
  • Only needs external transceiver (e.g., SN65HVD230)
  • Common pins: GPIO4 (TX), GPIO5 (RX) — but any GPIO works
  • ESP-IDF and Arduino libraries available

ADC (Analog-to-Digital Converter)

Overview

  • Converts continuous analog voltage to discrete digital value
  • Key parameters: resolution, reference voltage, sample rate
  • Input must not exceed reference voltage

Key Parameters

  • ResolutionDescription=Bits of precision (10-bit = 1024 steps, 12-bit = 4096)
  • ReferenceDescription=Full-scale input voltage (typically VCC or internal ref)
  • Sample RateDescription=Conversions per second (SPS)
  • Input RangeDescription=Allowable input voltage (0 to Vref typically)

Platform Comparison

  • Built-in ADCRaspberry Pi=No, ESP32=Yes (2 ADCs)
  • ResolutionRaspberry Pi=N/A, ESP32=12-bit (4096 levels)
  • ChannelsRaspberry Pi=N/A, ESP32=ADC1: 8ch, ADC2: 10ch
  • ReferenceRaspberry Pi=N/A, ESP32=0-3.3V (with attenuation)
  • Sample RateRaspberry Pi=N/A, ESP32=Up to 2 MSPS
  • WiFi ConflictRaspberry Pi=N/A, ESP32=ADC2 unusable with WiFi

ESP32 ADC Attenuation

  • 0 dBInput Range=0-1.1V, Notes=Highest accuracy
  • 2.5 dBInput Range=0-1.5V
  • 6 dBInput Range=0-2.2V
  • 11 dBInput Range=0-3.3V, Notes=Full range, lower accuracy

External ADC Options

  • ADS1115Interface=I2C, Resolution=16-bit, Channels=4, Notes=Programmable gain, slow (860 SPS)
  • ADS1015Interface=I2C, Resolution=12-bit, Channels=4, Notes=Faster than ADS1115 (3300 SPS)
  • MCP3008Interface=SPI, Resolution=10-bit, Channels=8, Notes=Simple, cheap, fast
  • MCP3208Interface=SPI, Resolution=12-bit, Channels=8, Notes=Higher resolution MCP3008
  • ADS7828Interface=I2C, Resolution=12-bit, Channels=8, Notes=8-channel I2C option

Input Protection

  • Never exceed reference voltage — will damage ADC or give invalid readings
  • Use voltage divider for higher voltages
  • Add clamp diodes (Schottky to VCC and GND) for unknown inputs
  • Add RC filter (100Ω + 100nF) to reduce noise

Platform Notes

Raspberry Pi:

  • No built-in ADC — external ADC required for any analog input
  • MCP3008 (SPI) or ADS1115 (I2C) are most common choices
  • Many HATs include ADC chips

ESP32:

  • ADC1 (GPIO32-39): Always available, even with WiFi active
  • ADC2 (GPIO0-27 subset): Unusable when WiFi or Bluetooth active
  • Design rule: Use ADC1 pins for analog if project uses WiFi
  • Non-linear at extremes — calibration improves accuracy