Sonsivri

Electronics => AVR, 8051 Family and ARM Area => Topic started by: micropcb on September 17, 2013, 07:30:41 07:30



Title: Need help on SPI code for Atmega16
Post by: micropcb on September 17, 2013, 07:30:41 07:30
Hi everyone,

I am trying to establish communication between two Atmega16s using SPI
One Atmega16 is configured as master and the other as slave.
The connections are as follows :

Master                  Slave
SCK          <--->       SCK
MOSI        <--->     MOSI
MISO        <--->     MISO
SS            <--->        SS

I am expecting to get the binary 1,2,3....etc on the master's portA (common anode LEDs) every one second.

But it does not work. I am using SS from the master to synchronize .
I shall be obliged if somebody can help me find the bug.
Codes attached.

Thanks in advance.


    


Title: Re: Need help on SPI code for Atmega16
Post by: robotai on September 17, 2013, 09:10:05 09:10
The SPIF would clear after read both SPSR and SPDR. So the slave code may need to read out SPDR in order to clear the SPIF flag.

Try this code out on slave to see if it works,
Code:
while(1)
{
  SPDR = ++i;
  while ( !(SPSR & (1<<SPIF)));
  PORTA = ~SPDR;
}


Title: Re: Need help on SPI code for Atmega16
Post by: micropcb on September 17, 2013, 09:24:13 09:24
I tried that robotai but no response.
Attached proteus simulation and AVR studio files


Title: Re: Need help on SPI code for Atmega16
Post by: robotai on September 17, 2013, 10:38:16 10:38
Well, it seems you have a mistyping on register flag. ((1<SPE))

correction on master.c
Code:
//SPCR = (1<SPE) | (1<<MSTR) | (1<<SPR0)|(1<<SPR1);
SPCR = (1<<SPE) | (1<<MSTR) | (1<<SPR0)|(1<<SPR1);

correction on slave.c
Code:
//SPCR = (1<SPE) | (1<<SPR0) |(1<<SPR1);
SPCR = (1<<SPE)| (1<<SPR0) |(1<<SPR1);


Title: Re: Need help on SPI code for Atmega16
Post by: metal on September 17, 2013, 12:26:11 12:26
http://www.rocketnumbernine.com/2009/04/26/using-spi-on-an-avr-1


Title: Re: Need help on SPI code for Atmega16
Post by: micropcb on September 17, 2013, 01:13:22 13:13
Well, it seems you have a mistyping on register flag. ((1<SPE))

correction on master.c
Code:
//SPCR = (1<SPE) | (1<<MSTR) | (1<<SPR0)|(1<<SPR1);
SPCR = (1<<SPE) | (1<<MSTR) | (1<<SPR0)|(1<<SPR1);

correction on slave.c
Code:
//SPCR = (1<SPE) | (1<<SPR0) |(1<<SPR1);
SPCR = (1<<SPE)| (1<<SPR0) |(1<<SPR1);

How silly of me not to have noticed that !!
Now it works like a charm!!


Title: Re: Need help on SPI code for Atmega16
Post by: micropcb on September 17, 2013, 02:36:54 14:36
Here are the files of the working project for the use of anybody who may be interested.

Cheers! :)