Skip to content

Instantly share code, notes, and snippets.

@radi-cho
Created November 20, 2023 16:42
Show Gist options
  • Save radi-cho/44d37323d878d61bc7330370086dc7dc to your computer and use it in GitHub Desktop.
Save radi-cho/44d37323d878d61bc7330370086dc7dc to your computer and use it in GitHub Desktop.
const int buttonPin = 4;
const int ss = 10;
const int mosi = 11;
const int miso = 12;
const int sclk = 13;
int lastState = LOW;
int ledState = LOW;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT);
pinMode(ss, OUTPUT);
pinMode(mosi, OUTPUT);
pinMode(miso, INPUT);
pinMode(sclk, OUTPUT);
digitalWrite(ss, HIGH);
}
void sendMessage(String message) {
digitalWrite(ss, LOW); // SELECT
delay(10);
for (int i = 0; i < message.length(); i++) {
digitalWrite(mosi, message.charAt(i) == '1' ? HIGH : LOW);
delay(10);
digitalWrite(sclk, HIGH); // CLOCK HIGH (slave reads)
delay(10);
digitalWrite(sclk, LOW); // CLOCK LOW
delay(10);
}
digitalWrite(ss, HIGH); // STOPS LISTENING
}
void loop()
{
int currentState = digitalRead(buttonPin);
if(currentState != lastState && currentState == HIGH){
if (ledState == LOW){
Serial.print("Send 10 to turn on");
sendMessage("1000");
} else {
Serial.print("Send 01 to turn on");
sendMessage("0001");
}
ledState = !ledState;
}
lastState = currentState;
}
///
const int ss = 10;
const int mosi = 11;
const int miso = 12;
const int sclk = 13;
const int LEDPin = 7;
int LEDState = LOW;
int last = LOW;
int lastSS = HIGH;
String message = "";
void setup()
{
Serial.begin(9600);
pinMode(LEDPin, OUTPUT);
pinMode(mosi, INPUT);
pinMode(miso, OUTPUT);
pinMode(sclk, INPUT);
pinMode(ss, INPUT);
}
void loop()
{
int clockState = digitalRead(sclk);
int ssState = digitalRead(ss);
if (ssState == HIGH) {
if (ssState != lastSS) {
if (message == "1000") {
digitalWrite(LEDPin, HIGH);
} else if (message == "0001") {
digitalWrite(LEDPin, LOW);
}
message = "";
}
} else {
if(clockState != last && clockState == HIGH){
Serial.print(digitalRead(mosi));
if(digitalRead(mosi) == HIGH) {
message += "1";
} else {
message += "0";
}
digitalWrite(miso, HIGH);
}
last = clockState;
}
lastSS = ssState;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment