SPI (Serial Peripheral Interface)
What is SPI ?
SPI (Serial Peripheral Interface) is a synchronous, full-duplex communication protocol used to transfer data between a master (e.g., microcontroller) and one or more slaves (e.g., sensors, memory chips).
SPI uses 4 main lines:
Line | Full Name | Direction | Purpose |
---|---|---|---|
MOSI | Master Out Slave In | Master → Slave | Master sends data to slave |
MISO | Master In Slave Out | Slave → Master | Slave sends data to master |
SCLK | Serial Clock | Master → Slave | Clock signal generated by master |
SS | Slave Select | Master → Slave | Selects which slave to talk to |
SPI Communication Characteristics :
- Synchronous – Clock signal is shared.
- Full Duplex – Transmit and receive at the same time.
- Master/Slave Architecture
- Faster than UART or I2C, but only supports short-distance, board-level communication.
Embedded C (for Arduino-like systems)
#include <SPI.h>
void setup() {
Serial.begin(9600);
SPI.begin(); // Initialize SPI
digitalWrite(SS, HIGH); // Deselect slave
}
void loop() {
digitalWrite(SS, LOW); // Select slave
byte response = SPI.transfer(0xA5); // Send 0xA5, receive data
digitalWrite(SS, HIGH); // Deselect slave
Serial.print("Received: ");
Serial.println(response, HEX);
delay(1000);
}
Python (with spidev on Raspberry Pi)
import spidev
import time
spi = spidev.SpiDev()
spi.open(0, 0) # Open bus 0, device 0
spi.max_speed_hz = 50000
while True:
response = spi.xfer([0xA5]) # Send one byte, receive one byte
print("Received:", response[0])
time.sleep(1)
Comments
Post a Comment