Serial Interfaces for Arduino - UART, I2C and SPI
In questa pagina 6
Data exchange between a microcontroller and an external peripheral can be done very simply with a serial transmission: transmission and reception (even simultaneous) one bit at a time, with a minimal physical medium (usually 3 or 4 wires). A parallel transmission requires buses with many more lines. One distinguishes asynchronous from synchronous transmission: the synchronous one allows higher speeds but needs a more complex physical medium; the asynchronous one is widely used in microcontrollers (UART modules), the synchronous one for the I2C and SPI buses. On the Arduino boards these interfaces are the serial port, the I2C bus and the SPI bus (Arduino PlatformArduino is a family of open single-board microcontroller boards built on Atmel AVR chips (UNO, Mega, Micro), extended with stackable shields and programmed through its own IDE.Arduino Platform →); the use of I2C and SPI is introduced in Lab 10 - Arduino Standalone and Serial ProtocolsLaboratory 10 builds a standalone ATMega328P on a breadboard (16 MHz crystal, bootloader via ArduinoISP, or 8 MHz internal clock) and introduces the synchronous serial protocols I2C and SPI used to connect Arduino boards and peripherals.Lab 10 - Arduino Standalone and Serial Protocols →, and the serial port towards the WiFi module in Lab 11 - WiFi and Internet with ArduinoLaboratory 11 connects an Arduino UNO to WiFi through an ESP8266-01 module (pinout, 3.3 V level shifting and supply, baud rate fix with AT commands), tests the WiFiEsp library examples and posts sensor data to the dweet.io cloud service with an HTTP GET request.Lab 11 - WiFi and Internet with Arduino →.
Asynchronous serial transmission
The clocks of transmitter (Tx) and receiver (Rx) are not synchronized: the receiver must extract synchronism from the data line itself. Convention: every datum is preceded by a start bit (transition from the idle line to the opposite state) and followed by one or more stop bits (same polarity as the idle line). Between one datum and the next the line may stay idle for a long time. It is a standard for low-speed point-to-point communication.
Typical parameters (set in the UART): start bit 1; data bits from 5 to 8; parity bit none or 1; stop bits 1, 1.5 or 2; speed 1200, 2400, 4800, 9600, 19200 bit/s (bps).
Parity. An optional additional bit transmitted after the datum to detect errors: set to 1 if the sum of the transmitted bits is even (or odd, by convention). The receiver recomputes it: if different, it signals an error (two errors on the same datum are much less probable than one).
Efficiency. For an 8-bit datum with start and stop, 10 bits are needed on the line: the channel is used at 80% (20% is overhead); with parity or more stop bits it gets worse.
Transmission time. The bit time is . At 19200 bps . One byte (10 bits) takes ; a 16-bit datum sent as two bytes (20 bits) takes .
Receiver sampling. To read correctly, the receiver samples each bit at the middle of the interval. From the start transition, the samples of the bits of an 8-bit datum fall after ; after the line must be at the stop level, otherwise there is a synchronization error. Since the two clocks are not synchronized, the maximum relative frequency mismatch follows from the fact that the maximum error allowed is accumulated in : The receiver usually samples the line at 16 times the transmission frequency: synchronization starts at the first "high" sample after a series of "low" ones; after 6 sampling periods it acquires 3 consecutive samples to confirm the start; then it reads groups of 3 samples 16 periods apart and decides the bit value by majority (reducing the error probability). The uncertainty in detecting the start (maximum delay ) brings the limit to
Transmitter clock frequency. The UART uses a clock at derived from the system clock with a prescaler: for the clock is ; with a 4 MHz system clock the prescaler (division factor) is (the effective baud rate is bps, error , well below 4.6%).
Synchronous serial transmission
It is based on the synchronization of transmitter and receiver clocks: the transmitter is the master and also sends its clock on a dedicated line; often there are additional frame sync lines (start of word). The lines carry data for 100% of the time (no start/stop bits). The (for example falling) clock edge tells the receiver when the datum is stable. Synchronous peripherals allow one to configure: clock polarity (which edge samples), data polarity, bit order (MSB first or LSB first), size (8 or 16 bits), duration and frequency of the frame signal, clock frequency (programmable divider with prescaler, predefined or external).
The I2C bus
The I2C standard (Inter-Integrated Circuit, mid-1980s) is today an industrial standard. It is a synchronous serial transmission that allows the connection of many devices to a single master with only two lines: SDA (data) and SCL (clock), both connected to the supply with pull-up resistors (devices pull the line low; at rest it is high). Many microcontrollers have an I2C peripheral.
Speed. Normal mode: from 0 to 100 kbit/s; fast mode: up to 400 kbit/s. If there are devices on the bus that do not support fast mode, the bus stays at 100 kbit/s.
Transfer. The master generates the clock for all units. Data are transferred 9 bits at a time: the first 8 bits (MSB first) are written by the unit that is transmitting, the ninth by the destination unit: if it recognizes the datum, it brings SDA low during the 9th bit time (ACK); otherwise the line stays high (NACK). The bit changes on the falling edge of the clock and stays stable until the next.
Message. Every message begins with a start condition generated by the master (SDA falls while SCL is high) and ends with a stop (SDA rises while SCL is high): the two conditions are distinguished from a normal bit because SDA changes during the high phase of the clock. The first byte is a 7-bit address that uniquely identifies the peripheral; the eighth bit is R/W: low = the master writes to the peripheral, high = the master reads from it. The addressed peripheral answers with ACK; the others stay inert. Data bytes follow (in complex peripherals first one or more control bytes). In reading, the master can stop the transmission of the peripheral simply by not giving the ACK.
Addresses. Peripherals allow the address to be defined by fixing the logic level of some pins: usually only the 3 lowest bits of the 7 are configurable (rarely more than 8 equal peripherals are needed). Each device therefore has a unique address on the bus.
Duration of a message. Each byte takes 9 bit times: for bytes (address included) the duration is plus start and stop. Example: a microcontroller sends a 12-bit DAC a buffer of 128 values; each 12-bit value occupies 2 bytes: data bytes plus 1 of address bytes. At 400 kbit/s: . For a temperature sensor (address + 2 data bytes = 3 bytes): . For a 12-bit DAC with : .
True/false typical points. I2C is synchronous (not asynchronous); it requires a master (a single master); the maximum speed is 400 kbit/s; the lines are not terminated with 120 (pull-ups are needed; 120 belongs to CAN and RS485); each device has a unique address; it does not allow full-duplex communication (a single data wire).
The SPI bus
One master (the microcontroller) and several slaves. Lines: SCK (clock), MOSI (master out, slave in), MISO (master in, slave out) and one select line (CS) for each slave. The master starts the communication by activating the CS line of the slave, then sends bits on MOSI while sampling MISO: it is full duplex communication. There are 4 modes, defined by CPOL (idle level of the clock) and CPHA (on which edge MOSI changes and MISO is sampled). The protocol is very terse (no address, no ACK). It is used for flash/SD memories, converters and high-speed sensors.
Physical-level standards
They define conductors, voltage levels and line driving. Main ones: RS232, RS422/RS485, 0-20 mA current loop.
- RS232 (1962, modified several times): conceived for the connection between a DTE (computer) and a modem, then used for every point-to-point link. The connector has 25 pins (or 9); for asynchronous communication 3 lines are enough (Tx, Rx, ground). Levels: and , with = logic level 1 and = logic level 0 (negative logic); many devices also work at . Microcontrollers work at 0-5 V (or 3.3 V): a driver such as the MAX232 is needed, which with a voltage doubler and an inverter generates from 5 V (1 F capacitors).
- RS422: differential transmission on a twisted pair (reduces inductive coupling) with terminations of 125 (120 ). Thanks to the higher noise immunity it supports high speeds (10 Mbit/s on less than 15 m). Capacitive couplings become irrelevant because the receiver is insensitive to the common mode.
- RS485: electrically similar to RS422 but allows several transmitters on the same line (with an enable command that puts the transmitters in high impedance). Widely used in industry for robustness to noise; often with shielded conductors.
- 0-20 mA current loop: logic 1 is the flow of a current (20 mA), 0 is absence of current. Maximum immunity to electromagnetic disturbance; optoisolated drivers galvanically separate Tx and Rx even for thousands of volts.
Many microcontrollers integrate a UART (asynchronous) and/or a synchronous peripheral, SPI, often I2C and CAN. Programming a USART is simple (bit rate, parity, length); programming a bus peripheral (I2C, CAN, Ethernet) is more complex because the protocol is also needed (libraries are used).
Common mistakes
- Forgetting the start and stop bits in the transmission time (8 data bits = 10 bits).
- Confusing the baud rate (= for two-level modulations) with the UART clock frequency (16 times larger).
- Believing RS232 uses 0/5 V logic levels: it uses in negative logic.
- Saying the UART needs the clock on the cable: it is exactly the opposite of synchronous transmission.
- Saying I2C is full duplex or asynchronous; forgetting that ACK is the ninth bit (9 bits per byte, not 8).
- Forgetting the address byte in the byte count of a message.
Versione ripasso
Key statements and formulas
- Asynchronous (UART): start bit 1, data 5-8 bits, parity optional, stop 1, 1.5 or 2; 8 data bits need 10 bits on the line (efficiency 80%). Bit time ( at 19200 bps).
- Receiver sampling: at from the start edge; maximum clock mismatch , with oversampling and majority of 3 samples . UART clock from a prescaler.
- Synchronous: master sends the clock (and frame sync); 100% of the time on data, no start/stop.
- I2C: synchronous, 2 wires SDA and SCL with pull-ups, one master, 7-bit address (plus R/W: low = write), 9 bits per byte (8 + ACK, SDA low), start = SDA falls with SCL high, stop = SDA rises with SCL high, 100 kbit/s normal and 400 kbit/s fast, half duplex, only the 3 lowest address bits configurable. Duration .
- SPI: 4 wires SCK, MOSI, MISO, CS (one per slave), full duplex, modes from CPOL (idle clock level) and CPHA (sampling edge), no address, no ACK.
- Physical levels: RS232 (negative logic, , MAX232 adapts 0-5 V); RS422 differential twisted pair, 120 , 10 Mbit/s under 15 m; RS485 as RS422 with several transmitters (high-impedance enable); 0-20 mA current loop with optoisolation.
Main steps of the examples
- At 19200 bps: byte ; two bytes .
- 4 MHz clock, 19200 bps: prescaler , effective bps (error ).
- I2C DAC: bytes, at 400 kbit/s ; sensor with 3 bytes: ; 12-bit DAC with : .
Typical mistakes
- Start and stop bits forgotten in the time (8 bits = 10).
- Baud rate confused with the UART clock ().
- RS232 taken as 0/5 V logic.
- I2C called full duplex or asynchronous; ACK is the ninth bit; address byte forgotten in the count.
More points to remember
- Parity: extra bit after the datum (set to 1 if the sum of the bits is even, or odd by convention); the receiver recomputes it and signals an error if it differs. More stop bits or parity lower the 80% efficiency.
- Receiver: 16 clock, start recognized at the first high sample after low ones, 3 consecutive samples after 6 periods to confirm, then groups of 3 samples spaced 16 periods, majority vote. After the line must be at the stop level, else synchronization error.
- Synchronous peripherals are configurable in clock polarity, data polarity, bit order (MSB or LSB first), size (8 or 16 bits), frame signal and clock divider.
- I2C: normal -, fast up to (all devices must support it, otherwise ); the bit changes on the falling clock edge and stays stable until the next; the master can stop a read by not sending ACK; the pull-ups, not 120 , terminate the lines.
- SPI: used for flash/SD memories, converters and fast sensors; the master activates CS, sends on MOSI while sampling MISO.
- RS232: 25 or 9 pin connector, 3 lines enough (Tx, Rx, ground); MAX232 with voltage doubler and inverter, capacitors, makes from 5 V. RS422/RS485: twisted pair, insensitive to common mode, RS485 often with shielded conductors. Current loop: 20 mA = 1, optoisolated drivers separate Tx and Rx for thousands of volts.
- Programming a USART is simple (bit rate, parity, length); I2C, CAN and Ethernet need the protocol, hence libraries.