Migrate from https://cmakerhk.wordpress.com/2018/10/12/arduino-spi/
https://www.microchip.com/wwwproducts/en/ATmega328p
https://www.arduino.cc/en/Reference/SPI
The Arduino Lib is for SPI Master, if you would like to play with SLAVE >> 0) –> to enable SPI module
https://github.com/PaulStoffregen/SPI/blob/master/SPI.h
//master loopback
#include
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
SPI.begin();
}
void loop() {
// put your main code here, to run repeatedly:
}
void serialEvent(){
//statements
Serial.print(SPI.transfer(Serial.read()));
}
//unfinished
#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====");
SPI_SlaveInit();
}else{
//========================= MASTER ==================
Serial.println("\n\n====Master Mode is Selected====");
pinMode(pinNSS, OUTPUT);
SPI_MasterInit();
char a = SPI_MasterTransmit('i');
Serial.print(a);
}
}
void SPI_MasterInit(void){
// Set MOSI and SCK output, all others untouch
PORTB = 0xFF;
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
while(!(SPSR & (1 << SPIF)));
//Start Transmission
return SPDR;
}
void loop() {
// put your main code here, to run repeatedly:
}