//bit masking
// BM => Bit Mask
#define _BM(bit7, bit6, bit5, bit4, bit3, bit2, bit1, bit0) \
( \
((bit7 == 7) << (bit7 & 7)) | \
((bit6 == 6) << (bit6 & 6)) | \
((bit5 == 5) << (bit5 & 5)) | \
((bit4 == 4) << (bit4 & 4)) | \
((bit3 == 3) << (bit3 & 3)) | \
((bit2 == 2) << (bit2 & 2)) | \
((bit1 == 1) << (bit1 & 1)) | \
((bit0 == 0) << (bit0 & 0)) \
)
UCSR0A = _BM (RXC0, TXC0, ~UDRE0, ~FE0, ~DOR0, ~UPE0, ~U2X0, ~MPCM0);
#define pinIsSlave 2
#define pinNSS 10
//pin2 is High –> Slave
//pin2 is Low –> Master
#define DDR_SPI DDRB
#define DD_MOSI DDB3
#define DD_MISO DDB4
#define DD_SCK DDB5
#define DD_NSS DDB2
//==========
//pin Master Slave
//MOSI User INPUT
//MISO INPUT User
//SCK User INPUT
//NSS User INPUT
//__enable_interrupt();
void SPI_MasterInit(void);
char SPI_MasterTransmit(char cData);
void SPI_SlaveInit(void);
char SPI_SlaveReceive(void);
void setup() {
pinMode(pinIsSlave, INPUT_PULLUP);
Serial.begin(9600);
Serial.println(“Master/Slave SPI - USART Firmware V1.0”);
Serial.println(“pin2 is High –> Slave || pin2 is Low –> Master”);
//Program Start
if(digitalRead(pinIsSlave)){
//========================= SLAVE ===================
Serial.println(“\n\n====Slave Mode is Selected====”);
pinMode(pinNSS, INPUT);
SPI_SlaveInit();
while(1){
if(digitalRead(pinNSS) == LOW)
Serial.print(SPI_SlaveReceive());
}
}else{
//========================= MASTER ==================
Serial.println(“\n\n====Master Mode is Selected====”);
pinMode(pinNSS, OUTPUT);
SPI_MasterInit();
while(1){
digitalWrite(pinNSS, HIGH);
char a = SPI_MasterTransmit(‘h’);
digitalWrite(pinNSS, LOW);
Serial.print(a);
delay(2000);
}
}
}
void SPI_MasterInit(void){
// Set MOSI and SCK output, all others untouch
DDR_SPI |= (1 << DD_MOSI)|(1 << DD_SCK);
//Enable SPI, Master,
SPCR |= (1 << SPE)|(1 << MSTR);
//SPI0 Clock Rate Select to f_osc/16
SPCR |= (1 << SPR0);
}
char SPI_MasterTransmit(char cData){
//Start Transmission
SPDR = cData;
//wait until Commication complete
while(!(SPSR & (1 << SPIF)));
return SPDR;
//
// SPDR = cData;
// asm volatile(“nop”);
// while (!(SPSR & _BV(SPIF))) ; // wait
// return SPDR;
}
void SPI_SlaveInit(void){
//Set MISO output, all other untouch
DDR_SPI |= (1 << DD_MISO);
//Enable SPI
SPCR = (1 << SPE);
}
char SPI_SlaveReceive(void){
//wait until Commication complete
Serial.print(“I am fucking here”);
while(!(SPSR & (1 << SPIF)));
Serial.println(“Something is here”);
//Start Transmission
return SPDR;
}
void loop() {
// put your main code here, to run repeatedly:
}