SPI master-slave architecture helps devices talk to each other quickly using a simple wire connection. One device controls the conversation (master), and others listen and respond (slaves).
0
0
SPI master-slave architecture in Embedded C
Introduction
When connecting a microcontroller to sensors or memory chips.
When you want fast data transfer between two devices.
When you need to control multiple devices with one controller.
When you want simple wiring with clear control signals.
Syntax
Embedded C
/* SPI Master Initialization Example */ void SPI_MasterInit(void) { /* Set MOSI, SCK as Output, MISO as Input */ DDRB = (1 << DDB3) | (1 << DDB5); /* Enable SPI, Set as Master, Set clock rate fck/16 */ SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR0); } /* SPI Slave Initialization Example */ void SPI_SlaveInit(void) { /* Set MISO as Output */ DDRB = (1 << DDB4); /* Enable SPI */ SPCR = (1 << SPE); }
Master controls clock and data flow.
Slave waits for master's clock to send/receive data.
Examples
Master writes data and waits for it to send.
Embedded C
/* Master sends a byte */ void SPI_MasterTransmit(char data) { SPDR = data; /* Load data into SPI data register */ while(!(SPSR & (1 << SPIF))) ; /* Wait until transmission complete */ }
Slave waits for data from master and reads it.
Embedded C
/* Slave receives a byte */ char SPI_SlaveReceive(void) { while(!(SPSR & (1 << SPIF))) ; /* Wait for data reception */ return SPDR; /* Return received data */ }
Sample Program
This program sets up a device as SPI master and sends the letter 'A' repeatedly to a slave device.
Embedded C
#include <avr/io.h> void SPI_MasterInit(void) { DDRB = (1 << DDB3) | (1 << DDB5) | (1 << DDB2); /* MOSI, SCK, SS as output */ SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR0); /* Enable SPI, Master, clk/16 */ } void SPI_MasterTransmit(char data) { SPDR = data; while(!(SPSR & (1 << SPIF))) ; } int main(void) { SPI_MasterInit(); while(1) { SPI_MasterTransmit('A'); /* Send character 'A' */ for (volatile int i = 0; i < 10000; i++); /* Simple delay */ } return 0; }
OutputSuccess
Important Notes
Always set the slave select (SS) pin correctly to choose which slave to talk to.
SPI is full-duplex: master and slave send data at the same time.
Clock polarity and phase must match on master and slave for correct communication.
Summary
SPI master controls the clock and starts communication.
Slaves respond when selected by the master.
SPI is fast and uses few wires for device communication.