Hi there,
I am trying to learn SPI method of communication. I hooked up two STK500 board according to AVR151 application note, page 10(see link below)exactly. Except that in my case, I use ATmega16 and not Atmega162. I could not figure out what is the problem. Please have a look at it.
http://www.atmel.com/dyn/resources/prod … oc2585.pdf
Master
#include <avr/io.h>
//#include <stdio.h>
#include<avr/delay.h>
#define DD_MOSI 0x20 //PINB5
#define DD_SCK 0x80 //PINB7
#define DDR_SPI DDRB //PORTB
#define sw0 0x01
#define sw1 0x02
#define sw2 0x04
#define sw3 0x08
#define sw4 0x10
#define sw5 0x20
#define sw6 0x40
#define sw7 0x80
void SPI_MasterInit(void)
{
/* Set MOSI and SCK output, all others input */
DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
/* Enable SPI, Master, set clock rate fck/16 */
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}
void SPI_MasterTransmit(char cData)
{
/* Start transmission */
SPDR = cData;
/* Wait for transmission complete */
while(!(SPSR & (1<<SPIF)));
}
//int main()
void main(void)
{
SPI_MasterInit();
DDRA = 0x00; //input
DDRD = 0xFF; //output
PORTD = 0xff; //turn off all LEDs
while(1)
{
if( ( (PINA &sw0) == 0x00)) //if switch 0 is pressed
{
PORTD = 0xfe;
SPI_MasterTransmit('0');
}
else if ( ( (PINA &sw1) == 0x00))
{
PORTD = 0xfd;
}
else if ( ( (PINA &sw2) == 0x00))
{
PORTD = 0xfb;
}
else if ( ( (PINA &sw3) == 0x00))
{
PORTD = 0xf7;
}
else if ( ( (PINA &sw4) == 0x00))
{
PORTD = 0xef;
}
else if ( ( (PINA &sw5) == 0x00))
{
PORTD = 0xdf;
}
else if ( ( (PINA &sw6) == 0x00))
{
PORTD = 0xbf;
}
else if ( ( (PINA &sw7) == 0x00))
{
PORTD = 0x7f;
}
}
}
Slave:
#include <avr/io.h>
//#include <stdio.h>
#include<avr/delay.h>
//#define DD_MISO 0x40 //PINB6
//#define DD_SCK 0x80 //PINB7
//#define DDR_SPI DDRB //PORTB
#define DD_MISO PINB6
//#define DD_SCK PINB7
#define DDR_SPI PORTB
void SPI_SlaveInit(void)
{
/* Set MISO output, all others input */
DDR_SPI = (1<<DD_MISO);
/* Enable SPI */
SPCR = (1<<SPE);
}
char SPI_SlaveReceive(void)
{
/* Wait for reception complete */
while(!(SPSR & (1<<SPIF)));
/* Return data register */
return SPDR;
}
int main()
{
SPI_SlaveInit();
char selection;
DDRD = 0xFF; //output
PORTD = 0xff; //turn off all LEDs
//SPI_SlaveReceive();
while(1)
{
selection = SPI_SlaveReceive();
if( selection == '0')
{
PORTD = 0xfe;
}
}
}