SPI interface beween 2 AVRs

Status
Not open for further replies.

mammadkhata

Newbie level 4
Joined
Dec 14, 2012
Messages
5
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,313
hello everyone. Recently I wrote a program for SPI communication between 2 ATmega8 with CodeVision AVR compiler.
this is code for master that is transmitter
Code:
#include <mega8.h>
#include <delay.h>

#define MISO 4
#define MOSI 3
#define SS 2
#define  SCK 5

void spi_masterinit()
{
DDRB|=(1<<MOSI)|(1<<SCK)|(1<<SS);
DDRB&=~(1<<MISO);
SPCR=0x73;
PORTB|=(1<<SS);
}

void spi_write(unsigned char data)
{
PORTB&=~(1<<SS);
SPDR=data;
while(!(SPSR&(1<<SPIF)));
PORTB|=(1<<SS);
}

void main(void)
{
spi_masterinit();
spi_write('o');
while (1){
}
}

and this is for slave that is receiver
Code:
#include <mega8.h>
#include <delay.h>
#include <stdio.h>
// Alphanumeric LCD Module functions
#include <alcd.h>
#define MISO 4
#define MOSI 3
#define SS 2
#define  SCK 5
int i;
char a[20];

void spi_slaveinit()
{
DDRB|=(1<<MISO)|(1<<SCK);
DDRB&=~(1<<MOSI)|(1<<SS);
SPCR=0x73;
//PORTB&=~(1<<SS);
}
unsigned char spi_read()
{
SPDR='X';
while(!(SPSR&(1<<SPIF)));
return(SPDR);
}

void main(void)
{
spi_slaveinit();
lcd_init(16);

i=spi_read();       
sprintf(a,"%d",i);
lcd_gotoxy(0,0);  
lcd_puts(a);

while (1){
}
}

It works good and I receive '111' code on LCD that is code of 'o' character.But when I write send and receive codes on while loop, I cant see anything on LCD or it shows just 255 on LCD.
how can I fix it? how can I send data continual like send a counter?
please help me. Thanks.
 

if you are sending data in loop, then you need to put the spi_read() function in loop too. Try these changes in slave code:

Code:
void main(void)
{

  spi_slaveinit();
  lcd_init(16);

  while (1){
    
    i=spi_read();       
    sprintf(a,"%d",i);
    lcd_gotoxy(0,0);  
    lcd_puts(a);
  
  }
}
 


I tried but nothing respond
master in loop & slave in loop
just master in loop
just slave in loop

just works on void loop, both of them
 

Try these changes in master and slave code:
Code:
//Master Code
void spi_write(unsigned char data)
{
  PORTB&=~(1<<SS);
  SPDR=data;
  while(!(SPSR&0x80));
  PORTB|=(1<<SS);
}


//Slave Code
unsigned char spi_read()
{
  SPDR='X';
  while(!(SPSR&0x80));
  return(SPDR);
}
 


problem still remains
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…