PIC Serial Communication: UART, SPI, and I2C Explained

In this tutorial, we will explore three foundational serial communication protocols frequently used with PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization.: UART, SPI, and I2CDeveloping a Temperature Monitor with PIC18 and I2C SensorsDeveloping a Temperature Monitor with PIC18 and I2C SensorsFollow step-by-step instructions to build an accurate temperature monitoring system using a PIC18 microcontroller and an I2C sensor for reliable readings.. Each protocol offers distinct advantages, and understanding their principles and configurations is crucial for anyone looking to develop efficient and robust applications on PIC devices.

Introduction to Serial Communication on PIC🔗

Serial communication allows microcontrollers to exchange data using fewer I/O lines compared to parallel communication. In practice, this leads to simpler wiring and more compact designs. PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization. generally include built-in hardware modules for UART, SPI, and I2CDeveloping a Temperature Monitor with PIC18 and I2C SensorsDeveloping a Temperature Monitor with PIC18 and I2C SensorsFollow step-by-step instructions to build an accurate temperature monitoring system using a PIC18 microcontroller and an I2C sensor for reliable readings., making it straightforward to implement these protocols:

UART Communication🔗

Overview

UART is one of the simplest and most widely used serial protocols. It is commonly used for debuggingDebugging and Troubleshooting Techniques with ICD and MPLAB XDebugging and Troubleshooting Techniques with ICD and MPLAB XMaster real-time PIC microcontroller debugging with MPLAB X and ICD tools. Discover breakpoint setup, variable inspection, and performance techniques., data logging, or interfacing with external systems like GPS modules and Bluetooth devices. UART is asynchronous, meaning it does not use a clock signal. Instead, both devices agree on a baud rate (bits per second) and use start/stop bits for synchronization.

Key PIC Registers for UART

On a typical PIC microcontrollerIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization., the main registers and bits related to UART operation include:

  • TXSTA (Transmit Status and Control Register): Controls transmission settings (e.g., baud rate source, 8-/9-bit mode).
  • RCSTA (Receive Status and Control Register): Controls reception and enables serial port.
  • SPBRGH:SPBRGL (Baud Rate Generator Registers): Determines the desired baud rate in conjunction with the system clock.
  • TXREG and RCREG: The transmit and receive data buffers, respectively.

A simplified formula for configuring the baud rate with the default 16-bit Baud Rate Generator is often given by:

Baud Rate=FOSC4×(SPBRGH:SPBRGL+1) \text{Baud Rate} = \frac{F_{OSC}}{4 \times (SPBRGH:SPBRGL + 1)}

Typical Connection and Usage

For UART communication, connect the PIC TX (Transmit) pin to the RX (Receive) pin of the external device, and PIC RX pin to the TX pin of the external device. You usually connect ground as well. Optionally, level shifters (e.g., MAX232) may be required if the external device uses RS-232 voltage levels.

Below is a brief outline of steps to configure and use UART on a PIC:

1. Configure TXSTA and RCSTA: Enable transmit, enable serial port, select 8-bit modeDriving LCD Displays and Keypads with PICDriving LCD Displays and Keypads with PICLearn to interface a HD44780 LCD with a PIC microcontroller and matrix keypad. This guide covers wiring, initialization, and sample code for smooth integration..

2. Set Baud Rate: Load SPBRGH:SPBRGL with the correct value for the desired baud rate.

3. Enable InterruptsImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. (Optional): If you prefer interrupt-based communication, enable TX or RX interruptsImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices..

4. Write to TXREG: To transmit data, simply write a byte to TXREG. Wait until the transmit buffer is empty if needed.

5. Read from RCREG: To receive data, read the RCREG register when the receive interruptImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. flag is set or immediately after checking if data is available.

SPI Communication🔗

Overview

SPI (Serial Peripheral Interface) is a synchronous (clock-based) serial protocol known for its speed. It uses four main signals:

1. MOSI (Master Out, Slave In)

2. MISO (Master In, Slave Out)

3. SCK (Serial Clock)

4. SS (Slave Select) - sometimes multiple lines or a GPIO pin acting as chip select

SPI organizes data transfers in a master/slave arrangement. The master provides the clock (SCK) to the slave devices, and each slave is activated one at a time via its SS line.

Key PIC Registers for SPI

On many PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization., SPI functionality is provided via the MSSP (Master Synchronous Serial Port) module. Configuration involves:

Master and Slave Configuration

When configuring a PIC as an SPI master:

1. Select Master Mode by setting the appropriate bits in SSPCON (e.g., SSPM<3:0>).

2. Set Clock SpeedLow-Power Strategies: Maximizing PIC Battery LifeLow-Power Strategies: Maximizing PIC Battery LifeDiscover proven low-power strategies for PIC microcontrollers that maximize battery life through smart oscillator use, sleep modes, and efficient coding. based on the system clock, choosing the prescalerBuilding Real-Time Projects with PIC Using Timer1 and Input CaptureBuilding Real-Time Projects with PIC Using Timer1 and Input CaptureDiscover how to leverage Timer1 and Input Capture on PIC microcontrollers for precise real-time applications, pulse measurements, and periodic interrupts..

3. Choose Clock Polarity and Phase (CPOL, CKE bits in SSPSTAT or SSPCON).

4. Pull SS Line Low when communicating with a slave device, then send/receive data by writing/reading SSPBUF.

When configuring as an SPI slave:

1. Select Slave Mode by setting SSPM<3:0> to the corresponding mode.

2. Enable SS Pin or manage it in software.

3. Wait for Data: Data will be loaded into SSPBUF once the master generates clock pulses.

Ensure that both sides (master and slave) match the same data format (clock polarity, clock phase, and bit order).

I2C Communication🔗

Overview

I2CDeveloping a Temperature Monitor with PIC18 and I2C SensorsDeveloping a Temperature Monitor with PIC18 and I2C SensorsFollow step-by-step instructions to build an accurate temperature monitoring system using a PIC18 microcontroller and an I2C sensor for reliable readings. (Inter-Integrated Circuit) is a two-wire, synchronous communication protocol widely used for connecting sensorsAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions., EEPROMs, and other low-speed peripherals. Because it uses only SCL (serial clock) and SDA (serial data) lines, it reduces pin count and wiring complexity. I2CDeveloping a Temperature Monitor with PIC18 and I2C SensorsDeveloping a Temperature Monitor with PIC18 and I2C SensorsFollow step-by-step instructions to build an accurate temperature monitoring system using a PIC18 microcontroller and an I2C sensor for reliable readings. supports multiple slave devices on the same bus, distinguished by unique addresses.

Key PIC Registers for I2C

As with SPI, I2CDeveloping a Temperature Monitor with PIC18 and I2C SensorsDeveloping a Temperature Monitor with PIC18 and I2C SensorsFollow step-by-step instructions to build an accurate temperature monitoring system using a PIC18 microcontroller and an I2C sensor for reliable readings. often utilizes the MSSP module on PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization. but in I2CDeveloping a Temperature Monitor with PIC18 and I2C SensorsDeveloping a Temperature Monitor with PIC18 and I2C SensorsFollow step-by-step instructions to build an accurate temperature monitoring system using a PIC18 microcontroller and an I2C sensor for reliable readings. mode. Relevant registers typically include:

Master Mode Setup

1. Select I2CDeveloping a Temperature Monitor with PIC18 and I2C SensorsDeveloping a Temperature Monitor with PIC18 and I2C SensorsFollow step-by-step instructions to build an accurate temperature monitoring system using a PIC18 microcontroller and an I2C sensor for reliable readings. Master Mode by configuring SSPCON.

2. Set the Clock FrequencyLow-Power Strategies: Maximizing PIC Battery LifeLow-Power Strategies: Maximizing PIC Battery LifeDiscover proven low-power strategies for PIC microcontrollers that maximize battery life through smart oscillator use, sleep modes, and efficient coding. using SSPADD:

SSPADD=FOSC4×I2CClock1 SSPADD = \frac{F_{OSC}}{4 \times I2C_{Clock}} - 1
  • (Exact formula may vary based on device specifics.)

3. Generate Start Condition when ready to communicate.

4. Send Device Address (with read/write bit) and check for ACK.

5. Write or Read Data from the bus, managing ACK and NACK bits accordingly.

6. Generate Stop Condition when finished.

Slave Mode Setup

1. Select I2CDeveloping a Temperature Monitor with PIC18 and I2C SensorsDeveloping a Temperature Monitor with PIC18 and I2C SensorsFollow step-by-step instructions to build an accurate temperature monitoring system using a PIC18 microcontroller and an I2C sensor for reliable readings. Slave Mode in SSPCON.

2. Load the Device Address into SSPADD.

3. Handle InterruptsImplementing Interrupt-Driven Systems for Real-Time ApplicationsImplementing Interrupt-Driven Systems for Real-Time ApplicationsLearn to configure and optimize PIC microcontroller interrupts for real-time performance. Enhance responsiveness and efficiency using best practices. or poll the MSSP registers to detect address matches and data transfers.

4. Read/Write from/to SSPBUF when data is available or requested.

Comparison of UART, SPI, and I2C🔗

Below is a simplified table highlighting key differences among the three protocols:

ProtocolSignal LinesSpeed RangeTopologyTypical Usage
UARTTX, RX, GND (possibly RTS/CTS)Low to Moderate (up to Mbps)Point-to-PointDebug interfaces, point-to-point device links.
SPIMOSI, MISO, SCK, SS (plus ground)High (several Mbps)Master/Slave (1 master, 1+ slaves)Fast data exchange, sensors, displays, SD cards.
I2CSDA, SCL (plus ground, pull-up resist.)Moderate (100kHz - 400kHz, up to 1MHz+ in some variants)Multi-Master/Multi-Slave (1+ devices on same bus)Sensor networks, EEPROM, low-pin-count peripherals.

Practical Tips🔗

Conclusion🔗

By leveraging the built-in UART, SPI, and I2C modules on PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization., you can greatly simplify communication with a vast array of external peripherals. Understanding the underlying principles and register configurations of each protocol empowers you to design flexible, reliable, and efficient embedded systems. Whether connecting sensorsAnalog-to-Digital Conversion: Connecting Sensors to PICAnalog-to-Digital Conversion: Connecting Sensors to PICExplore our step-by-step PIC microcontroller ADC tutorial, including sensor interfacing techniques and C code examples to achieve accurate conversions., displaying data, or transferring information to another microcontroller, these three communication protocols form the backbone of modern embedded applications.

Next Steps: Experiment with each protocol in turn. Begin by setting up UART with a USB-to-serial converter for a simple PC-to-PIC communication test. Then explore SPI and I2C in Master mode to connect popular modules like temperatureAutomated Greenhouse Controller with PIC and SensorsAutomated Greenhouse Controller with PIC and SensorsLearn to build an automated greenhouse controller using a PIC microcontroller with sensors to manage temperature, humidity, and irrigation. sensors or EEPROM chips. Observing signals on an oscilloscope or logic analyzer can be highly beneficial for debugging and deepening your understanding of how each serial protocol operates.

Author: Marcelo V. Souza - Engenheiro de Sistemas e Entusiasta em IoT e Desenvolvimento de Software, com foco em inovação tecnológica.

References🔗

Share article

Related Articles