<* LED와 Switch를 이용한 SPI 통신 *>
• Master에서 Swich를 누르면, Slave에서 LED가 동작한다.
• Slave에서 Swich를 누르면, Master의 LED가 동작한다.
---- < SPI 통신 LED와 Switch : Master 소스 코드 > --------
#include<SPI.h>
#define LED_Pin 8
#define Button_Pin 2
int ButtonValue;
int ButtonStat;
void setup() {
Serial.begin(9600); //Starts Serial Communication at Baud Rate 9600
pinMode(Button_Pin,INPUT); //Sets pin 2 as input
pinMode(LED_Pin,OUTPUT); //Sets pin 7 as Output
SPI.begin(); //Begins the SPI commnuication
SPI.setClockDivider(SPI_CLOCK_DIV8); //Sets clock for SPI communication at 8 (16/8=2Mhz)
digitalWrite(SS,HIGH);
digitalWrite(SS, LOW); //Starts communication with Slave connected to master
Master_Send = ButtonStat;
Master_Receive=SPI.transfer(Master_Send); //Send the mastersend value to slave also receives value from slave
if(Master_Receive == 1) //Logic for setting the LED output depending upon value received from slave
{
digitalWrite(LED_Pin,HIGH); //Sets pin 7 HIGH
Serial.println("Master LED ON");
}
else
{
digitalWrite(LED_Pin,LOW); //Sets pin 7 LOW
Serial.println("Master LED OFF");
}
delay(1000);
}
---- < SPI 통신 LED와 Switch : Slave 소스 코드 > --------
#include<SPI.h>
#define LED_Pin 8
#define Button_Pin 2
volatile boolean received;
volatile byte Slave_Received,Slave_Send;
int ButtonValue;
int Button_Stat;
void setup() {
Serial.begin(9600);
pinMode(Button_Pin,INPUT); // Setting pin 2 as INPUT
pinMode(LED_Pin,OUTPUT); // Setting pin 7 as OUTPUT
pinMode(MISO,OUTPUT); //Sets MISO as
SPCR |= _BV(SPE); //Turn on SPI in Slave Mode
received = false;
SPI.attachInterrupt();
}
ISR (SPI_STC_vect) { //Inerrrput routine function
Slave_Received = SPDR; // Value received from master if store in variable slavereceived
received = true; //Sets received as True
}
void loop() {
if(received) { //Logic to SET LED ON OR OFF depending upon the value recerived from master
if (Slave_Received==1) {
digitalWrite(LED_Pin,HIGH); //Sets pin 7 as HIGH LED ON
Serial.println("Slave LED ON");
}else {
digitalWrite(LED_Pin,LOW); //Sets pin 7 as LOW LED OFF
Serial.println("Slave LED OFF");
}
ButtonValue = digitalRead(Button_Pin); // Reads the status of the pin 2
if (ButtonValue == HIGH) { //Logic to set the value of x to send to master
Button_Stat=1;
} else {
Button_Stat=0;
}
Slave_Send=Button_Stat;
SPDR = Slave_Send; //Sends the x value to master via SPDR
delay(1000);
}