0% found this document useful (0 votes)
22 views3 pages

Spi Interface ES

Embedded Systems VTU 5th sem

Uploaded by

Han Jisung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views3 pages

Spi Interface ES

Embedded Systems VTU 5th sem

Uploaded by

Han Jisung
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <reg51.

h>

sbit SPI_SCK = P1^0 ; // SPI Clock


sbit SPI_MOSI= P1^1; // Master Out Slave In
sbit SPI_MISO= P1^2; // Master In Slave Out
sbit SPI_SS= P1^3 ; // Slave Select

void SPI_Init(void);
void SPI_Start(void);
void SPI_Stop(void);
void SPI_SendByte(unsigned char dat);
unsigned char SPI_ReceiveByte(void);
void SPI_Transfer(unsigned char dat);

void main(void)
{
unsigned char receivedData;

SPI_Init(); // Initialize SPI

while (1)
{
SPI_Start(); // Start SPI communication
SPI_Transfer(0xA5); // Send data byte
receivedData = SPI_ReceiveByte(); // Receive response

SPI_Stop(); // Stop SPI communication

// Here you can process the received data if needed


// For example, you might want to toggle an LED based on receivedData
// P2 = receivedData; // Output received data to P2 for observation
}
}

void SPI_Init(void) {
// Configure pins as output
SPI_SCK = 0; // Set clock low
SPI_MOSI = 0; // Set MOSI low
SPI_SS = 1; // Set SS high (deselect slave)
}

void SPI_Start(void) {
SPI_SS = 0; // Select the slave (active low)
}

void SPI_Stop(void) {
SPI_SS = 1; // Deselect the slave
}

void SPI_SendByte(unsigned char dat)


{
int i;
unsigned char y;
for (i = 0; i < 8; i++) {
SPI_MOSI = (dat & 0x80) ? 1 : 0; // Send MSB first
SPI_SCK = 1; // Clock high
SPI_SCK = 0; // Clock low
dat <<= 1; // Shift left to prepare next bits
if(SPI_MOSI == 1)
y = y|0x01;
else
y = y|0x00;
P3 = y;
y <<= 1;

}
}

unsigned char SPI_ReceiveByte(void)


{
unsigned char dat = 0, x;
int i;
x=P3;
for (i = 0; i < 8; i++)

{
SPI_MISO = ( x & 0x80) ? 1: 0 ;

SPI_SCK = 1; // Clock high


dat <<= 1; // Prepare to receive the next bi
x<<=1;
if (SPI_MISO) {
dat |= 0x01; // Read bit from MISO
}
SPI_SCK = 0; // Clock low
}
return dat; // Return received byte
}

void SPI_Transfer(unsigned char dat) {


SPI_SendByte(dat); // Send data byte
}

You might also like