Hello,
I am using 1 Arduino 2009 as a SPI Master, and another Arduino 2009 as a SPI Slave.
when the SPI Slave received the value, it is printed out to the Serial Monitor by using Serial.println.
Both is working fine, but if the value is larger than 127, it is received but FFFFFF is added before the value.
here is the Spi library, which is based on Spi library found in
http://www.arduino.cc/playground/Code/Spi
but I changed the type from byte to uint8_t
#ifndef Spi_h
#define Spi_h
#include "WProgram.h"
#include <inttypes.h>
#define SCK_PIN 13
#define MISO_PIN 12
#define MOSI_PIN 11
#define SS_PIN 10
class SPI
{
public:
SPI(void);
void mode(uint8_t);
void SPI_SlaveInit(void);
uint8_t SPI_SlaveReceive(void);
uint8_t transfer(uint8_t);
uint8_t transfer(uint8_t, uint8_t);
};
extern SPI Spi;
#endif
Here is the cpp file
#include "WProgram.h"
#include "Spi.h"
//---------- constructor ----------------------------------------------------
SPI::SPI()
{
}
//------------------ mode ---------------------------------------------------
void SPI::mode(byte config)
{ byte tmp;
// initialize the SPI pins
pinMode(SCK_PIN, OUTPUT);
pinMode(MOSI_PIN, OUTPUT);
pinMode(MISO_PIN, INPUT);
pinMode(SS_PIN, OUTPUT);
// enable SPI master with configuration byte specified
SPCR = 0;
SPCR = (config & 0x7F) | (1<<SPE) | (1<<MSTR);
tmp = SPSR;
tmp = SPDR;
}
void SPI::SPI_SlaveInit(void)
{
/* Set MISO output, all others input */
//DDR_SPI = ( 1 <<DD_MISO);
pinMode(SCK_PIN, INPUT);
pinMode(MOSI_PIN, INPUT);
pinMode(MISO_PIN, OUTPUT);
pinMode(SS_PIN, INPUT);
/* Enable SPI */
// SPCR = ( 1 <<SPE)|(0<<MSTR);
SPCR = B01000000;//SPIE=0,SPE=1,DORD=0,MSTR=0,CPOL=0,CPOL=0,SPR=00
}
uint8_t SPI::SPI_SlaveReceive(void)
{
/*Wait for reception complete */
while(!(SPSR & (1<<SPIF)))
;
/* Return Data Register */
return SPDR;
}
//------------------ transfer -----------------------------------------------
uint8_t SPI::transfer(uint8_t value)
{
SPDR = value;
while (!(SPSR & (1<<SPIF))) ;
return SPDR;
}
uint8_t SPI::transfer(uint8_t value, uint8_t period)
{
SPDR = value;
if (period > 0) delayMicroseconds(period);
while (!(SPSR & (1<<SPIF))) ;
return SPDR;
}
//---------- preinstantiate SPI object --------------------------------------
SPI Spi = SPI();
Here's the PDE file for SPI slave
/* SPI slave */
#include "Spi.h"
void setup()
{
Serial.begin(9600);
Spi.SPI_SlaveInit();
}
void loop()
{
char RX_Data;
RX_Data = Spi.SPI_SlaveReceive();
// Serial.println(RX_Data);
Serial.println(RX_Data, HEX);
Serial.println("rx");
}
Here's the PDE for SPI Master
/* SPI Master */
#include "Spi.h"
void setup()
{
Spi.mode(B01010000);//MSB first,Master,CPOL=0,CPHA=0,SPR=00
}
int i;
void loop()
{
for(i=0;i<255;i++)
{
digitalWrite(SS_PIN, LOW);
Spi.transfer(i);
digitalWrite(SS_PIN, HIGH);
delay(100);
}
// digitalWrite(SS_PIN, LOW);
// Spi.transfer(0xF0);
// digitalWrite(SS_PIN, HIGH);
// delay(100);
}
Can someone help to tell me why?
Cheers
Joseph