SPI Master and Slave in Embedded C: Explanation and Example
SPI communication, the master device controls the clock and initiates data transfer, while the slave device responds to the master's commands. In Embedded C, the master and slave roles are programmed to manage data exchange over the SPI bus using specific registers and pins.How It Works
SPI (Serial Peripheral Interface) is like a conversation between two friends where one leads and the other follows. The master is the leader who sends a clock signal and decides when to talk, while the slave listens and responds accordingly. This clock signal helps both devices stay in sync during data exchange.
Imagine the master as a teacher calling on students (slaves) to answer questions. The teacher controls when the question is asked (clock) and which student should answer (chip select). The slave waits for the teacher's signal before sending or receiving data.
In Embedded C, the master and slave are set up by configuring hardware registers to define roles, clock speed, and data format. The master generates the clock and selects the slave, while the slave waits for the master's clock and chip select signals to communicate.
Example
This example shows a simple SPI master sending a byte to a slave in Embedded C. The master configures SPI settings, sends data, and waits for the transfer to complete.
#include <avr/io.h> void SPI_MasterInit(void) { DDRB = (1 << DDB5) | (1 << DDB3) | (1 << DDB2); // SCK, MOSI, SS as output SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR0); // Enable SPI, Master mode, clock rate fosc/16 } void SPI_MasterTransmit(char data) { SPDR = data; // Load data into SPI data register while (!(SPSR & (1 << SPIF))) ; // Wait until transmission complete } int main(void) { SPI_MasterInit(); while (1) { SPI_MasterTransmit(0x55); // Send 0x55 to slave for (volatile int i = 0; i < 10000; i++); // Simple delay } return 0; }
When to Use
Use SPI master and slave communication when you need fast, full-duplex data exchange between microcontrollers or between a microcontroller and peripherals like sensors, displays, or memory chips. SPI is ideal for short-distance communication on the same circuit board.
For example, a microcontroller (master) can control an LCD screen (slave) by sending commands and data quickly. Another case is reading sensor data from a slave device that sends measurements back to the master.
Key Points
- The master controls the clock and initiates communication.
- The slave responds to the master's clock and commands.
- SPI uses separate lines for clock, data out, data in, and chip select.
- Embedded C programs configure hardware registers to set master or slave roles.
- SPI is fast and suitable for short-distance device communication.