SparkFun Forums 

Where electronics enthusiasts find answers.

Your source for all things Atmel.
By sabale.ashish
#67507
I am trying to send data from one ATMEGA16 to another ATMEGA16 using SPI. Can you provide me the code for master as well as slave? i'm using SPI.h header function from Codevision AVR IDE.
1) So does function unsigned char spi(unsigned char) takes care of /ss(slave select) signal or do i have to manually activate it?
2) When do i need to initialize spi n also data to SPDR in slave? Do that data in SPDR get overwritten as wen I was writtng data SPI might get actived n data get shifted.
Plz help i am stuck with my project due to this difficulty.
my code as follows

MASTER :
Code: Select all
#include <mega16.h>   
#include <spi.h>
#include <delay.h>  

#define SPIF SPSR.7;
void spi_tx(void);
#define ss PORTB.4
// Declare your global variables here
void init_spi(void);

void main(void)
{
unsigned char temp;
PORTA=0x00;
DDRA=0xFF;

PORTB=0x00;
DDRB=0xB0;

PORTC=0x00;
DDRC=0xFF;

PORTD=0x00;
DDRD=0xFF;

TCCR0=0x00;
TCNT0=0x00;
OCR0=0x00;

TCCR1A=0x00;
TCCR1B=0x00;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;

ASSR=0x00;
TCCR2=0x00;
TCNT2=0x00;
OCR2=0x00;

MCUCR=0x00;
MCUCSR=0x00;

TIMSK=0x00;

ACSR=0x80;
SFIOR=0x00;
ss = 1;
init_spi();
spi_tx();

ss = 0 ;
temp=spi('h') ;
ss = 1;
delay_ms(250);
temp=spi('b');
PORTA = temp;
while(1);
             
} 


void init_spi()
{
 SPCR = 0x52;
 SPSR = 0x00;
 return;
}
 

void spi_tx()
{
 
SPDR = 'h';
delay_ms(500);
ss = 0;
/* Wait for transmission complete */
while(!(SPSR & (1 << SPSR.7)));

ss = 1;
PORTC = SPDR;
 return;
}       


SLAVE :
Code: Select all

#include <mega16.h>
#include<spi.h>
#include<delay.h>

void init_spi(void);

#define SPIF SPSR.7
void main(void)
{

PORTA=0x00;
DDRA=0xFF;


PORTB=0x00;
DDRB=0x40;

/
PORTC=0x00;
DDRC=0xFF;

/
PORTD=0x00;
DDRD=0xFF;


SFIOR=0x00;              
SPDR = 'b';               // Data to be sent to Master
while (1)
      { 
        
        init_spi();
        PORTC = SPDR;      // debug
        if(SPIF == 1)
           {
                init_spi();         // reinitialization after 1 transfer
           }
         
        delay_ms(500);
       PORTC = SPDR;      // debug
         

      };
}



void init_spi()
{
 
SPCR = 0x42;
SPSR = 0x00;          // SPI slave initialization
}
[/quote]


PLZ help me with Slave code . it's a total block for project.
By monstrum
#97123
Why do you set the SPI configuration registers for every transfer in the slave?

Also, you must poll the bit in the SPI status register and make sure new data has been received before you try to read it. Just reading the SPDR will not stall the program until new data is available.