Unit 7: Under Pressure

 

 

 

Code for Sketch: 


// Pin definitions
const int BLUE_PIN = 9;   // Blue LED (Was mistakenly Red)
const int GREEN_PIN = 10; // Green LED
const int RED_PIN = 11;   // Red LED (Was mistakenly Green)

const int BUTTON1_PIN = 2;
const int BUTTON2_PIN = 3;
const int BUTTON3_PIN = 4;

// State tracking
bool redState = false;
unsigned long button2PressTime = 0;
bool button2Held = false;

void setup() {
  Serial.begin(9600);

  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);

  pinMode(BUTTON1_PIN, INPUT_PULLUP);
  pinMode(BUTTON2_PIN, INPUT_PULLUP);
  pinMode(BUTTON3_PIN, INPUT_PULLUP);

  Serial.println("Setup complete. Press a button!");
}

void loop() {
  // Button 1 - Press to turn on Blue LED
  if (digitalRead(BUTTON1_PIN) == LOW) {
    Serial.println("Button 1 pressed - BLUE ON");
    digitalWrite(BLUE_PIN, HIGH);
  } else {
    digitalWrite(BLUE_PIN, LOW);
  }

  // Button 2 - Hold for 3 seconds to turn on Green LED
  if (digitalRead(BUTTON2_PIN) == LOW) {
    if (button2PressTime == 0) {
      button2PressTime = millis();
    } else if (millis() - button2PressTime >= 3000) {
      Serial.println("Button 2 held for 3s - GREEN ON");
      digitalWrite(GREEN_PIN, HIGH);
      button2Held = true;
    }
  } else {
    button2PressTime = 0;
    digitalWrite(GREEN_PIN, LOW);
    button2Held = false;
  }

  // Button 3 - Toggle Red LED on/off
  if (digitalRead(BUTTON3_PIN) == LOW) {
    delay(50); // Debounce
    while (digitalRead(BUTTON3_PIN) == LOW); // Wait for release
    redState = !redState;
    Serial.print("Button 3 toggled - RED ");
    Serial.println(redState ? "ON" : "OFF");
    digitalWrite(RED_PIN, redState ? HIGH : LOW);
  }

  delay(50);
}

  

}

 

Notes: