Software SPI communication (as master device)
Overview

A view of SPI in action, the data out is the 10101010 binary value
For SPI communication you need 4 pins
- Data Out (Yellow)
- Data In (Blue)
- Clock (pink)
- Chip select (green)
In this code segment I used Chip select as a low to high transition, and shifting of data on the rising edge of the clock. Most hardware devices uses a high to low transition for their chip select (also known as a negative chip select). Some devices clock data out on the rising edge and some on the falling edge, you will have to read the data sheet to find more information. This code was written to work with the MPLab C18 compiler from Microchip (declare your variables global, don’t ask me why its just the way it is). You would ideally use the same variable to swap the data out of and the new data into, unfortunately for my application this was not an option, so I had to use two variables.
Basic Flow of Code
The procedure for SPI works as follows.
- Set Chip Select
- Start Loop
- Set data on Data Out pin
- Set Clock
- Wait
- Sample data on Data In pin
- Unset Clock
- End Loop
- Unset Chip Select
C code
void SPI_master_char(void)
{
SW_SCK_PIN = 0;
SW_CS_PIN = 1;
Delay10TCYx(10);
b = 8;
for (b = 8; b >0 ; b–) {
Rlcf(Dout,1,1);
SW_DOUT_PIN = STATUSbits.C;
SW_SCK_PIN = 1;
Delay10TCYx(10);
STATUSbits.C = SW_DIN_PIN;
Rlcf(Din,1,1);
SW_SCK_PIN = 0;
Delay10TCYx(10);
}
SW_CS_PIN = 0;
}
Here is a copy of the complete code for the PIC18F1320: SPI_Master.c
Further Reading
On Wikipedia you can find a great page with information of the SPI protocol, the link is here.
0 Comments »
No comments yet.
RSS feed for comments on this post. TrackBack URI


