Serial Communication and Connected Embedded SystemsIntroductionEmbedded systems rarely operate in isolation. A microcontroller may acquire sensor data, exchange commands with another controller, communicate with a human-machine interface, or transmit measurements to a cloud service. Serial communication provides the electrical, logical, and procedural foundation for these interactions. Unlike parallel communication, in which several bits travel simultaneously over multiple conductors, serial communication sends bits sequentially over one or more signal paths. It reduces wiring, connector size, cost, and electromagnetic exposure, although it introduces requirements for timing, framing, synchronization, addressing, arbitration, and error handling. This chapter examines UART, SPI, I²C, CAN, USB, and industrial communication fundamentals. It also explains how local buses connect to gateways and IoT networks. Protocol choice is treated as an engineering decision involving data rate, distance, topology, determinism, noise immunity, power, interoperability, software complexity, and safety. Learning ObjectivesAfter studying this chapter, a student should be able to: - Explain framing, baud rate, synchronization, addressing, arbitration, and error detection.
- Configure and analyze UART, SPI, I²C, CAN, and USB links.
- Compare protocols using electrical, architectural, and application criteria.
- Design robust message formats and fault-handling procedures.
- Select a communication protocol for an embedded application.
- Explain the role of gateways, network layers, and security in connected embedded systems.
1. Communication Models and Essential TerminologyA serial interface can be described at several layers. The physical layer defines voltages, timing, connectors, and transmission media. The link layer defines frames, addressing, arbitration, and error detection. Higher layers define message meaning, device discovery, configuration, and application data. Important terms include: - Simplex: communication in one direction only.
- Half-duplex: both directions are possible, but not simultaneously.
- Full-duplex: both directions can operate simultaneously.
- Synchronous communication: transmitter and receiver share an explicit or recovered clock.
- Asynchronous communication: timing is inferred from agreed baud rate and frame transitions.
- Baud rate: number of symbols transmitted per second. With binary signaling and one bit per symbol, it equals bit/s.
- Frame: a structured unit containing synchronization, data, and usually control information.
- Latency: time between a request and the corresponding response.
- Throughput: useful data delivered per unit time.
- Jitter: variation in event timing.
- Node: a device attached to a communication network.
- Transceiver: circuitry that converts logic-level signals to and from a physical medium.
For a frame containing D useful data bits and F total transmitted bits, the ideal payload efficiency is: η = D ÷ F Here η is dimensionless. This expression assumes that all transmitted bits are counted and that protocol overhead is not useful payload. If a link sends R bit/s, the ideal payload throughput is: Tpayload = R × η where T_payload is in bit/s. Real throughput is lower when inter-frame gaps, acknowledgements, retransmissions, processing delays, or flow control are included. 2. Framing and SynchronizationA receiver must determine where a message begins and ends. Common techniques are fixed-length frames, length fields, delimiters, start and stop symbols, and timeouts. A robust frame may contain a preamble, address, control field, payload length, payload, and frame-check sequence. A delimiter-based protocol must escape delimiter bytes appearing in payload data. In byte stuffing, a special escape byte is inserted before reserved values. In bit stuffing, a transmitter inserts a zero after a prescribed run of ones; the receiver removes it. These techniques prevent payload data from being mistaken for control information. Asynchronous links use a known timing tolerance rather than a shared clock. A UART character commonly consists of one start bit, 5–9 data bits, an optional parity bit, and one or more stop bits. The falling edge of the start bit lets the receiver begin sampling. Sampling near the center of each bit reduces sensitivity to edge uncertainty. For a UART frame with one start bit, n data bits, p parity bits, and s stop bits, the number of transmitted bits per character is: Nframe = 1 + n + p + s If the baud rate is B symbols/s, the character rate is approximately: fcharacter = B ÷ Nframe These equations assume one symbol per bit and neglect pauses between characters. For 8-N-1 UART, N_frame = 1 + 8 + 0 + 1 = 10. At 9,600 bit/s, the maximum continuous character rate is 960 characters/s, and an 8-bit payload rate is 7,680 bit/s before software or flow-control losses. Clock mismatch accumulates across a frame. If the transmitter and receiver clocks differ too greatly, the receiver samples progressively farther from the bit centers. The allowable error depends on the UART implementation, oversampling method, frame length, signal quality, and clock accuracy; therefore a design should follow the microcontroller and transceiver data sheets rather than rely on a universal percentage. 3. UART: Simple Asynchronous Point-to-Point CommunicationUART means Universal Asynchronous Receiver/Transmitter. A UART peripheral converts parallel bytes in a processor into serial frames and converts received frames back into bytes. Basic UART signals are TX, RX, and signal ground. TX of one device connects to RX of the other. Optional RTS and CTS signals provide hardware flow control. UART is normally point-to-point, although multidrop variants exist when an additional transceiver and protocol define bus ownership. Logic-level UART is not the same as RS-232. RS-232 uses bipolar voltage levels and an inverted signal convention, whereas microcontroller UART pins commonly use CMOS or TTL-compatible levels. Directly connecting an RS-232 port to a microcontroller pin can damage the pin or produce incorrect logic. A UART receiver can report framing, parity, overrun, and break errors. An overrun occurs when a new byte arrives before software or DMA has removed the previous byte from the receive register. Correct interrupt design, buffering, and flow control are therefore essential. UART design procedure: - Select baud rate, data length, parity, and stop-bit settings.
- Confirm that both endpoints use identical settings.
- Verify voltage levels and ground reference.
- Calculate worst-case data rate and buffer requirements.
- Define message boundaries, checksums, timeouts, and recovery behavior.
- Test normal, disconnected, noisy, and overloaded conditions.
UART is inexpensive and easy to debug, but it lacks inherent bus arbitration, addressing, and robust error recovery. It is well suited to console ports, GPS receivers, cellular modems, and short board-level links. 4. SPI: High-Speed Synchronous Peripheral CommunicationSerial Peripheral Interface (SPI) is a synchronous bus usually organized with a controller, a serial clock SCLK, controller-out/peripheral-in MOSI, controller-in/peripheral-out MISO, and one chip-select signal per peripheral. Older documentation often calls these lines MOSI, MISO, SCK, and SS/CS. The controller generates the clock and selects a peripheral by asserting its chip-select, commonly active low. Data shifts on one clock edge and is sampled on the other. SPI mode is specified by clock polarity (CPOL) and clock phase (CPHA), producing four modes. Both devices must use the same mode and observe setup, hold, maximum-frequency, and chip-select timing requirements. SPI is full-duplex: while one bit is transmitted on MOSI, one bit can be received on MISO. A peripheral may return meaningful data only after dummy bytes are transmitted. SPI has no universal addressing, acknowledgement, or error-detection field. The application must define register addresses, command formats, CRCs, and timeout behavior if needed. Advantages include high speed, simple hardware, and predictable transfers. Limitations include more wires, a separate chip-select for many peripherals, lack of standardized interoperability, and reduced suitability for long cables. Signal integrity becomes important as clock frequency and interconnect length increase. Series resistors, controlled edge rates, short traces, and careful grounding can reduce ringing and crosstalk. 5. I²C: Addressed Two-Wire BusI²C is a synchronous, multidrop two-wire bus using SDA for data and SCL for clock. Both lines are open-drain or open-collector and require pull-up resistors. Devices pull a line low but do not actively drive it high. This wired-AND behavior supports arbitration and allows a device to stretch the clock by holding SCL low, subject to the bus specification and controller capabilities. An I²C transaction begins with a START condition, followed by an address and read/write bit. Each transmitted byte is followed by an acknowledge bit. A STOP condition ends the transaction. A receiver acknowledges a byte by pulling SDA low during the acknowledge clock; a NACK may indicate that a device is not present, data is complete, or the receiver cannot accept more data. The bus capacitance and pull-up resistance determine how quickly a line rises. A simplified first-order relationship is: tr ≈ 0.8473 × RP × CB where t_r is the approximate 30%–70% rise time in seconds, R_P is pull-up resistance in ohms, and C_B is total bus capacitance in farads. The relationship assumes a lumped capacitance and a sufficiently ideal open-drain driver. Lower resistance improves rise time but increases low-state current; higher resistance reduces current but may violate rise-time limits. The selected value must satisfy both electrical limits and the I²C specification. I²C provides addressing and acknowledgement, making it convenient for sensors, EEPROMs, real-time clocks, and power-management devices. It is slower and more capacitance-sensitive than SPI. Address conflicts, unexpected clock stretching, and a device holding SDA low require recovery procedures, such as toggling SCL under controlled conditions and resetting the affected peripheral. 6. CAN: Fault-Tolerant Multi-Node Control NetworksController Area Network (CAN) is designed for reliable multi-node communication, especially in vehicles and industrial systems. Nodes broadcast frames identified by message identifiers rather than sending to a particular node address. Every node observes the bus and decides whether to accept a frame. CAN uses a differential physical layer, commonly through a twisted pair with a transceiver. The bus has dominant and recessive states. A dominant bit overrides a recessive bit. During arbitration, a node transmitting recessive but reading dominant has lost and stops transmitting. Consequently, the frame with the numerically lowest identifier wins when identifier priority is arranged appropriately. Arbitration is nondestructive because the winning frame continues without being corrupted by collisions. Classical CAN data frames contain a start-of-frame bit, arbitration field, control information, data field, CRC, acknowledgement, and end-of-frame. CAN FD permits larger payloads and different data-phase rates, subject to transceiver and network support. Bit stuffing prevents excessive runs of identical bits and assists synchronization. CAN incorporates bit monitoring, bit stuffing checks, CRC, frame-form checks, acknowledgement, and fault confinement. Nodes maintain error states and may eventually enter a bus-off state to protect the network. CAN does not guarantee that every application message is delivered within a fixed time merely because it has priority. Worst-case response depends on bit rate, frame lengths, competing priorities, retransmissions, and system load. Safety-critical designs require schedulability analysis, sensible identifier assignment, supervision, and fail-safe behavior. 7. USB: Host-Centered Standardized ConnectivityUniversal Serial Bus (USB) is a standardized communication system designed for interoperability and plug-and-play connection. USB uses a host-centered architecture: the host schedules bus transactions, while devices respond through endpoints. A device generally cannot transmit whenever it wishes; it requests service through defined mechanisms. USB devices identify themselves through descriptors that describe device class, configuration, interfaces, endpoints, and capabilities. Common transfer types include control transfers for enumeration and configuration, bulk transfers for reliable high-volume data, interrupt transfers for bounded-latency polling-oriented data, and isochronous transfers for time-sensitive streams where occasional loss may be preferable to retransmission. USB complexity is higher than that of UART, SPI, or I²C. It involves standardized connectors and electrical requirements, protocol stacks, enumeration, descriptors, power negotiation in newer generations, and host software. USB is appropriate when connection to computers, standardized peripherals, or broad interoperability is required. It is less attractive for a tiny two-chip board-level link. 8. Industrial Communication FundamentalsIndustrial systems prioritize predictable operation, long distance, noise immunity, maintainability, and fault diagnosis. RS-485 is a physical layer commonly used for multidrop differential links. It does not itself define message meaning; protocols such as Modbus RTU can operate over it. Differential signaling rejects common-mode noise when cabling, termination, grounding, and transceiver limits are respected. A typical RS-485 network uses a linear bus, not a star, with termination at the two physical ends. Short stubs reduce reflections. Biasing establishes a defined idle state when no driver is active. Shielding and grounding must be designed with attention to ground-potential differences and safety isolation. Modbus RTU commonly uses a master–slave or client–server transaction model, address fields, function codes, data fields, and a CRC. A silent interval separates frames. It is simple and widely supported, but performance and interoperability depend on consistent baud settings, timing, register maps, byte order, exception handling, and documentation. Other industrial technologies include Ethernet-based systems, EtherCAT, PROFINET, CANopen, and DeviceNet. These are not interchangeable merely because they use similar cables or connectors. The physical layer, data-link behavior, configuration tools, real-time guarantees, and application profiles must all be considered. 9. Error Detection, Reliability, and RecoveryNoise, interference, connector faults, software defects, and overload can corrupt communication. Error detection adds redundancy so that a receiver can identify many errors. A parity bit detects all odd numbers of bit errors in a protected word, but it cannot detect every even-numbered error. A checksum adds words or bytes according to a defined arithmetic rule. A cyclic redundancy check (CRC) treats a bit sequence as a polynomial and divides it by a generator polynomial; the transmitted remainder enables detection of many burst and random errors. Detection is not correction. A reliable protocol must specify what happens after an error: discard the frame, acknowledge negatively, request retransmission, retry a bounded number of times, reset the link, log the fault, or enter a safe state. Timeouts must be finite and based on the maximum expected transaction duration plus engineering margin. A robust message often includes: | Field | Purpose |
|---|
| Preamble or start marker | Synchronization and frame recognition | | Version/type | Interpretation and evolution | | Address or identifier | Destination, source, or message priority | | Length | Payload boundary and validation | | Sequence number | Duplicate detection and ordering | | Payload | Application data | | CRC or checksum | Error detection |
Sequence numbers are especially useful when retransmission can create duplicates. Idempotent commands—commands that can safely be repeated—simplify recovery. Safety-related systems should not treat a valid CRC as proof that a command is safe; range checks, authentication, freshness, and independent supervision may also be necessary. 10. Comparing Protocols and Selecting One| Protocol | Synchronization | Topology | Addressing/arbitration | Typical strength | Typical limitation |
|---|
| UART | Asynchronous | Point-to-point | Usually none | Simple console or modem link | No inherent arbitration | | SPI | Clocked | Controller with peripherals | Chip-select | High speed, low overhead | More wires and little standardization | | I²C | Clocked | Multidrop two-wire | Addressing and arbitration | Many low-speed peripherals | Pull-up rise time and capacitance | | CAN | Clocked/recovered | Differential bus | Identifier arbitration | Robust distributed control | Limited payload and configuration complexity | | USB | Host scheduled | Host–device tree | Enumeration/endpoints | Interoperability with computers | Large protocol stack | | RS-485/Modbus | Usually asynchronous | Differential bus | Protocol dependent | Long industrial links | Physical layer alone is incomplete |
A rational selection process begins with requirements rather than familiarity. Determine the number of nodes, cable length, data volume, maximum latency, environmental noise, power constraints, required interoperability, safety classification, physical topology, and software resources. Then identify whether the application needs deterministic priority, hot plugging, galvanic isolation, standardized drivers, or low pin count. For example, a temperature sensor on the same PCB may use I²C; a high-speed display controller may use SPI; a vehicle actuator network may use CAN; and a computer-connected instrument may use USB. A protocol can be technically capable yet unsuitable because its connectors, electromagnetic behavior, or diagnostic ecosystem do not match the application. 11. Connected Embedded Systems and IoTA connected embedded system commonly contains four layers: sensing and actuation, local control, gateway networking, and application services. A microcontroller may read sensors through I²C, control an actuator over CAN, and forward selected measurements through UART to a Wi-Fi or cellular modem. The modem then uses IP networking and an application protocol such as MQTT or HTTPS. A gateway performs protocol translation, buffering, time synchronization, authentication, data filtering, and sometimes local analytics. Edge processing can reduce bandwidth and preserve operation during cloud outages. Data should be represented with units, timestamps, quality flags, calibration status, and device identity. Sending an unlabelled integer without scale or byte-order documentation is an interoperability defect. IoT security must be designed from the beginning. Relevant controls include unique device identity, secure boot, signed firmware updates, encrypted transport, key protection, least privilege, input validation, replay protection, logging, vulnerability response, and decommissioning procedures. Physical access may allow probing of buses or replacement of firmware, so security assumptions must be explicit. AI can be useful at the edge for anomaly detection, predictive maintenance, or adaptive sampling, but it does not replace deterministic communication design. A machine-learning model may flag unusual vibration, while the communication system must still guarantee timestamp integrity, bounded latency where required, safe fallback, and auditable behavior. 12. Illustrative Case: Remote Pump Monitoring and ControlBackgroundConsider an illustrative industrial pump station containing pressure, temperature, and vibration sensors; a motor drive; and a remote supervisory system. The controller is installed near electrically noisy motor equipment and must continue safe local operation if the network connection fails. ProblemThe design team initially proposes UART for every connection. This would require separate point-to-point links, provide no inherent multi-node arbitration, and offer weak fault containment. The remote link also needs longer cable distance and noise immunity. AnalysisLocal digital sensors require modest bandwidth and simple wiring, so I²C is suitable if the board layout keeps capacitance within limits. The motor drive and safety-related status devices benefit from CAN because differential signaling, priority arbitration, and error confinement support distributed control. A gateway can expose diagnostics through USB during commissioning and transmit selected data over Ethernet or cellular service. UART remains useful between the controller and a modem if the modem specifies that interface. Approach and SolutionThe controller uses I²C for board-level sensors, CAN for the field bus, and a gateway for external connectivity. Each application message is assigned a documented identifier, scaling factor, unit, update period, and timeout. A pressure value is range-checked before it can influence control. If a sensor fails to update within its timeout, the controller marks the value invalid and applies a predefined safe strategy. The pump continues under local closed-loop control when cloud connectivity is unavailable; remote commands are accepted only after authentication, freshness checking, and local permissibility checks. The CAN bus is terminated correctly, cables are routed away from high-current switching conductors, and error counters are monitored. Gateway data are buffered with timestamps and transmitted when the connection returns. Firmware updates are signed and tested first on a noncritical unit. OutcomeThe resulting architecture separates real-time local control from non-deterministic remote services. It improves maintainability because each link is selected for its actual function, rather than forcing one protocol across the entire system. Learning Points- Protocol selection is an architectural decision, not merely a peripheral configuration.
- Local safety must not depend on continuous cloud availability.
- Units, scaling, timeouts, and fault states are part of interoperability.
- Physical installation and termination can be as important as software.
- Security and update mechanisms must be included before deployment.
13. Best Practices and LimitationsUse data sheets and applicable standards as the final authority for voltage, timing, cable length, termination, and electrical limits. Separate logic-level and physical-layer specifications. Define reset behavior, bus recovery, timeout values, and versioning. Use DMA and ring buffers where sustained serial traffic could overrun a processor. Instrument systems with counters for CRC errors, framing errors, retries, dropped messages, and bus-off events. Test at temperature and voltage extremes, during startup and shutdown, under maximum traffic, with disconnected nodes, and in the presence of electromagnetic interference. A logic analyzer verifies digital timing, but it does not replace oscilloscope measurements of signal integrity or compliance testing. No protocol solves every problem. SPI has no universal interoperability model; I²C can fail when a device holds the bus; UART depends on endpoint agreement; CAN requires careful priority and load analysis; USB adds stack complexity; and industrial networks require disciplined installation. These limitations should be documented as design assumptions. Chapter SummarySerial communication transfers information sequentially and requires agreement about physical signaling, timing, framing, and message interpretation. UART provides simple asynchronous point-to-point communication. SPI provides fast synchronous transfers with separate chip-select lines. I²C offers an addressed two-wire multidrop bus using open-drain signaling and acknowledgements. CAN supports robust distributed control through differential signaling, nondestructive identifier arbitration, and extensive error handling. USB supplies standardized host-centered interoperability through enumeration and endpoints. RS-485 and industrial protocols support longer, noisier links, but a physical layer alone does not define application semantics. Reliable systems require explicit frame boundaries, error detection, timeouts, recovery, buffering, validation, and diagnostics. Protocol choice must reflect topology, distance, bandwidth, latency, noise, interoperability, safety, power, and maintenance requirements. In connected embedded systems, gateways combine local buses with IP and IoT services. Secure identity, authenticated updates, encryption, fail-safe local control, and well-defined data models are essential for dependable deployment. Key TermsUART: Asynchronous serial peripheral that converts parallel data to serial frames. SPI: Synchronous peripheral bus using clock, data, and chip-select signals. I²C: Two-wire addressed bus using open-drain signaling and acknowledgements. CAN: Differential multi-node control network with identifier-based arbitration. USB: Host-centered standardized bus supporting enumeration and multiple transfer types. Baud rate: Number of transmitted symbols per second. Frame: Structured transmission unit containing control and data fields. Parity: Redundant bit used to detect selected bit errors. CRC: Polynomial-based error-detection code. Arbitration: Process by which competing transmitters determine bus ownership. Dominant bit: CAN bus state that overrides a recessive state. Clock stretching: I²C technique in which a device holds SCL low. Transceiver: Circuit that interfaces logic signals to a physical communication medium. Termination: End-of-line impedance used to reduce signal reflections. Throughput: Useful information delivered per unit time. Latency: Time between an initiating event and the corresponding response. Gateway: Device that translates or aggregates between networks or protocols. Enumeration: USB process in which a host identifies and configures a device. Timeout: Maximum permitted waiting interval before declaring abnormal behavior. Review QuestionsShort Answer Questions- Distinguish synchronous and asynchronous serial communication.
- Why must an RS-232 interface not be connected directly to a typical CMOS UART pin?
- What is the purpose of an I²C pull-up resistor?
- Explain nondestructive arbitration in CAN.
- State two functions commonly performed by an IoT gateway.
Long Answer Questions- Explain UART framing, including baud rate, start bit, data bits, parity, stop bits, and common receiver errors.
- Compare SPI and I²C in terms of wiring, speed, addressing, acknowledgement, topology, and typical applications.
- Describe CAN frame arbitration, differential signaling, error detection, and fault confinement.
- Explain USB host-centered operation, enumeration, descriptors, endpoints, and transfer types.
- Develop a protocol-selection framework for an industrial embedded system and justify the criteria used.
Analytical / Application Questions- A controller sends 8-N-1 UART frames at 19,200 bit/s. Calculate the maximum continuous payload rate in bytes per second, assuming no gaps or flow-control pauses. Explain the effect of adding an even parity bit.
- An I²C bus has a 4.7 kΩ pull-up and an estimated capacitance of 200 pF. Use the rise-time relationship in this chapter to estimate the rise time and discuss whether changing the pull-up resistance affects current and signal speed.
- Design a communication architecture for a battery-powered pump containing local sensors, an actuator drive, a service laptop connection, and a remote monitoring link. Justify each protocol and specify at least three fault or security controls.
Multiple Choice Questions with AnswersQuestion 1A UART frame uses one start bit, eight data bits, no parity bit, and one stop bit. What is its total length? A. 8 bits B. 9 bits C. 10 bits D. 11 bits Correct Answer: C. 10 bits Question 2Which SPI signal is normally generated by the controller to determine when data shifts or is sampled? A. SCLK B. MISO C. CS only D. RX Correct Answer: A. SCLK Question 3Why do I²C lines require pull-up resistors? A. To generate a negative supply voltage B. Because devices actively drive only the low state C. To provide a separate clock oscillator D. To encode parity bits Correct Answer: B. Because devices actively drive only the low state Question 4In CAN arbitration, which transmitter loses arbitration? A. The node transmitting dominant and reading dominant B. The node transmitting recessive and reading dominant C. The node transmitting recessive and reading recessive D. The node with the shortest cable Correct Answer: B. The node transmitting recessive and reading dominant Question 5What is the principal role of a USB host during normal bus operation? A. To schedule and control bus transactions B. To provide CAN identifier arbitration C. To supply I²C pull-up current D. To generate UART parity Correct Answer: A. To schedule and control bus transactions Question 6Which item detects errors but does not by itself specify retransmission or recovery? A. CRC B. Chip-select C. Baud rate D. Pull-up resistor Correct Answer: A. CRC Question 7For 8-N-1 UART at 9,600 bit/s, the ideal maximum payload rate is approximately: A. 960 bytes/s B. 1,200 bytes/s C. 7,680 bytes/s D. 9,600 bytes/s Correct Answer: A. 960 bytes/s Question 8Which topology is generally appropriate for a properly installed RS-485 bus? A. A linear bus with termination at its two ends B. An unterminated star with unlimited stubs C. A single-ended point-to-point link only D. A ring requiring USB enumeration Correct Answer: A. A linear bus with termination at its two ends Question 9Which property most directly supports CAN’s priority-based nondestructive arbitration? A. Open-drain I²C acknowledgement B. Dominant and recessive bus states C. USB device descriptors D. UART stop bits Correct Answer: B. Dominant and recessive bus states Question 10Which gateway practice best supports operation during temporary cloud failure? A. Disable all local control B. Discard all sensor data immediately C. Buffer data and retain local control functions D. Accept unauthenticated remote commands Correct Answer: C. Buffer data and retain local control functions
|