SPI programming

Go To Last Post
7 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hello, I have found some "Hello World" code for SPI. Unfortunately I don't understand it completely.

#include 
#define MOSI 5
#define SCK 7

int main(void)
{
DDRB = (1<<MOSI) | (1<<SCK); //Master Out Slave In
DDRA = 0XFF;//DDRA is output

//SPI Control Register
//SPE = SPI ENABLE
//MSTR = Master
//SPR0 = 1 to give SPI frequency of Fosc/16
//in my case 8000000Hz/16 = 500000Hz
SPCR = (1<<SPE) | (1<<MSTR) | (1<<SPR0); 
while(1)
{
       
SPDR = 'G'; //SPI data register contains letter G

//SPSR = SPI Status Register
//SPIF = SPI  Interrupt Flag
while(!(SPSR & (1<<SPIF)));
PORTA = SPDR; //Send letter G to PORTA
	
}
return 0;
}

I'm using an ATmega32 and a development board which has LEDs on PORTA. The LED number 1 of 8 just turns on and stays on. Are the LEDs suppose to show the binary representation of the letter g?

I don't understand is this a pointless program if we don't have any external devices that use SPI to communicate connected? Am I suppose to use female to female jumper wire and connect one pin to another or something?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Your right it is pointless, although it shows how to send a byte to the spi and poll for transmission completed. Loop mosi pin to miso pin with a jumper and verify that portA has the ascii code for the letter G (hex 47, or bin 01000111).

Always start small, get it working, then expand on code that works.

jc

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Oh, then it is useful to learn the concept if it does that. I put a jumper on MISO and MOSI and nothing happens.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

SS (PB4) is an input and if it is not held high then the SPI will change from Master mode to Slave mode.
(reference /SS Pin Functionality in the datasheet.

Enable the internal pullup on that pin, or externally tie it high, or set it as an output.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

It can be a loop test.
It tests if the connection with a slave device works.
I have changed comments to be more clear.

SPDR = 'G'; // send byte 'G' to SPI 
while(!(SPSR & (1<<SPIF))); 
PORTA = SPDR; // receive byte from SPI and save to PORTA    
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:
if we don't have any external devices that use SPI to communicate connected?

If you don't have an SPI device what is the point of experimenting with SPI?

Anyway that code looks atrocious, any decent SPI software is going to have an spi-tx-rx() function broken out separately so if you really want to experiment then I'd Google for some more professional looking code.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

In good old times, there used to be something called as Slave Select when the SPI is used in master mode.. this code doesnt even seem to care about that.. so better look for another code somewhere else...