What is MOSI, MISO, SCLK, SS in SPI in Embedded C
MOSI is the line where data is sent from the master to the slave, MISO is where data is sent from the slave to the master, SCLK is the clock signal that synchronizes data transfer, and SS (Slave Select) is used by the master to activate a specific slave device. These signals are essential for SPI to work correctly in embedded C programs.How It Works
SPI (Serial Peripheral Interface) is like a conversation between a master and one or more slaves using four main wires. Imagine the master as a teacher and the slaves as students. The MOSI line is the teacher speaking to the students, sending instructions or data. The MISO line is the students replying back to the teacher.
The SCLK is like a metronome or clock that keeps everyone in sync, telling when to listen or speak. Finally, the SS line is like raising a student's hand to answer; it tells which slave device should pay attention and respond. This setup allows fast and clear communication between devices in embedded systems.
Example
This example shows how to configure SPI pins and send one byte from master to slave in embedded C.
#include <stdint.h> #include <avr/io.h> // Example for AVR microcontroller void SPI_MasterInit(void) { // Set MOSI, SCLK and SS as output DDRB |= (1 << DDB3) | (1 << DDB5) | (1 << DDB2); // Set MISO as input DDRB &= ~(1 << DDB4); // Enable SPI, Master mode, set clock rate fck/16 SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR0); } void SPI_MasterTransmit(uint8_t 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 with MOSI, MISO, SCLK, and SS lines when you need fast, full-duplex communication between a microcontroller and peripherals like sensors, memory chips, or displays. It is ideal for short-distance communication on the same circuit board.
For example, SPI is used to read data from temperature sensors, write data to flash memory, or control LCD screens in embedded devices. The SS line helps manage multiple devices by selecting which one to talk to at a time.
Key Points
- MOSI: Master Out Slave In - data from master to slave.
- MISO: Master In Slave Out - data from slave to master.
- SCLK: Clock signal to sync data transfer.
- SS: Slave Select to choose which slave is active.
- SPI is fast and simple for short-distance device communication.