How do you interface the Raspberry Pi with external microcontrollers (e.g., via UART, I2C)?


Interfacing the Raspberry Pi with external microcontrollers (like Arduino, STM32, etc.) is a common and powerful technique to combine the strengths of both platforms.
Here's how you can do it using UART, I²C, and SPI—the most popular communication interfaces:
1. UART (Serial Communication)
Wiring
Raspberry Pi Pin | Microcontroller Pin |
TX (GPIO 14) | RX (receive) |
RX (GPIO 15) | TX (transmit) |
GND | GND |
Logic levels: Raspberry Pi is 3.3V — don’t connect directly to 5V devices without a level shifter!
Example (Python with PySerial)
Install:
bash
sudo apt install python3-serial
python
import serial
ser = serial.Serial('/dev/serial0', 9600)
ser.write(b'Hello MCU\n')
data = ser.readline()
print("Received:", data.decode())
ser.close()
2. I²C (Inter-Integrated Circuit)
Wiring
Raspberry Pi Pin | Microcontroller Pin |
SDA (GPIO 2) | SDA |
SCL (GPIO 3) | SCL |
GND | GND |
Enable I²C:
bash
sudo raspi-config → Interface Options → I2C → Enable
Example (Python with smbus
)
Install:
bash
sudo apt install python3-smbus i2c-tools
python
import smbus
bus = smbus.SMBus(1)
addr = 0x08 # Example slave address
bus.write_byte(addr, 0x42)
data = bus.read_byte(addr)
print("Received:", data)
Use
i2cdetect -y 1
to scan devices.
3. SPI (Serial Peripheral Interface)
Wiring
Raspberry Pi Pin | Microcontroller Pin |
MOSI (GPIO 10) | MOSI |
MISO (GPIO 9) | MISO |
SCLK (GPIO 11) | SCK |
CE0 (GPIO 8) | CS / NSS |
GND | GND |
Enable SPI:
bash
sudo raspi-config → Interface Options → SPI → Enable
Example (Python with spidev
)
Install:
bash
pip3 install spidev
python
import spidev
spi = spidev.SpiDev()
spi.open(0, 0) # Bus 0, CS0
spi.max_speed_hz = 1000000
spi.writebytes([0x01, 0x02])
response = spi.readbytes(2)
print("Received:", response)
spi.close()
Which Interface Should You Use?
Interface | Use When... | Speed | Complexity |
UART | Simple, point-to-point communication | Low (~115 kbps) | Very easy |
I²C | Many devices on one bus, slower speeds OK | Medium (100–400 kbps) | Easy |
SPI | High-speed, multi-device, synchronous | High (up to several Mbps) | Moderate |
Tips for Reliable Communication
Always match logic levels (use level shifters if needed).
Use pull-up resistors for I²C (typically 4.7kΩ).
Keep ground lines connected between devices.
Validate with tools:
i2cdetect
,minicom
,logic analyzers
.
Subscribe to my newsletter
Read articles from ampheo directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
