Hi everyone,
I am doing a project which involves using an Arduino Uno as a master device with SPI communication to AVR Atmega32 devices as slaves. I have experimented a lot with SPI and can get it working perfectly between two AVRs or two Arduinos, however, when I try to get them to communicate between an Arduino and AVR I run into problems. The first ten or so transmissions immediately after hitting "Reset" on the Arduino transmit fine (the resets are tied also), but after that I read mostly 0xFF and occasionally a random byte from the master side (read through Serial Monitor). If anyone has any idea why it is doing this PLEASE HELP!
Thank you so much!!!
The code is shown below:
Master Code:
//==================================================================
//Arduino Uno (Master)
//==================================================================
#include <SPI.h>
int SLAVESELECT=10;
int DD_MOSI=11;
int DD_MISO=12;
int DD_SCK=13;
byte buffer[6]={0x01,0x02,0x03,0x04,0x05,0x06};
void setup()
{
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV4);
Serial.begin(9600);
pinMode(SLAVESELECT,OUTPUT);
pinMode(DD_MOSI,OUTPUT);
pinMode(DD_MISO,INPUT);
pinMode(DD_SCK,OUTPUT);
digitalWrite(SLAVESELECT,HIGH);
}
void loop(void)
{
digitalWrite(SLAVESELECT,LOW); //enable Slave Select
for(int i=0;i<6;i++)
{
byte x = SPI.transfer(buffer[i]);
Serial.print("master:");
Serial.println(buffer[i], HEX);
Serial.println(x, HEX);
delay(200);
}
digitalWrite(SS,HIGH);
}
Slave Code
//=====================================================================
//ATmega32 (Slave)
//=====================================================================
#include <avr/io.h>
#define F_CPU 4000000UL
#include <util/delay.h>
#include <stdlib.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#define DD_SS PINB4 //0
#define DD_MOSI PINB5 //0
#define DD_MISO PINB6 //1
#define DD_SCK PINB7 //0
#define DDR_SPI DDRB //0100 0000
void SPI_SlaveInit(void)
{
DDRB = 0x40; // set MOSI as input pin, MISO output
PORTB = 0xB0; //1011 0000
SPCR=(1<<SPE); // Enable SPI
SPSR=0;
}
char SPI_SlaveReceive(void)
{
/* Wait for reception complete */
while(!(SPSR & (1<<SPIF)));
/* Return data register */
return SPDR;
}
int main(void){
SPI_SlaveInit();
while(1)
{
PORTD = SPI_SlaveReceive(); // move SPDR value to POTRD
_delay_ms(1000);
}
}