Advertisement
belrey10

Day 5: The Trial of Lights and Buttons

Nov 3rd, 2024 (edited)
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const int buttonPin1 = 2;   // Button 1 is connected to pin 2
  2. const int buttonPin2 = 3;   // Button 2 is connected to pin 3
  3. const int ledPin1 = 8;      // LED 1 is connected to pin 8
  4. const int ledPin2 = 9;      // LED 2 is connected to pin 9
  5.  
  6. int buttonState1 = 0;       // Variable to hold the state of button 1
  7. int lastButtonState1 = 0;   // Previous state of button 1
  8. int buttonState2 = 0;       // Variable to hold the state of button 2
  9. int lastButtonState2 = 0;   // Previous state of button 2
  10. int ledState1 = LOW;        // Current state of LED 1 (initially off)
  11. int ledState2 = LOW;        // Current state of LED 2 (initially off)
  12.  
  13. void setup() {
  14.   pinMode(buttonPin1, INPUT);
  15.   pinMode(buttonPin2, INPUT);
  16.   pinMode(ledPin1, OUTPUT);
  17.   pinMode(ledPin2, OUTPUT);
  18. }
  19.  
  20. void loop() {
  21.   // Read the state of button 1
  22.   buttonState1 = digitalRead(buttonPin1);
  23.  
  24.   // Toggle LED 1 on/off when button 1 is pressed
  25.   if (buttonState1 != lastButtonState1) {
  26.     if (buttonState1 == HIGH) {
  27.       ledState1 = !ledState1;  // Toggle LED state
  28.       digitalWrite(ledPin1, ledState1);  // Set LED state
  29.     }
  30.     delay(50);  // Debounce delay
  31.   }
  32.   lastButtonState1 = buttonState1;  // Save the current state for next iteration
  33.  
  34.   // Read the state of button 2
  35.   buttonState2 = digitalRead(buttonPin2);
  36.  
  37.   // Toggle LED 2 on/off when button 2 is pressed
  38.   if (buttonState2 != lastButtonState2) {
  39.     if (buttonState2 == HIGH) {
  40.       ledState2 = !ledState2;  // Toggle LED state
  41.       digitalWrite(ledPin2, ledState2);  // Set LED state
  42.     }
  43.     delay(50);  // Debounce delay
  44.   }
  45.   lastButtonState2 = buttonState2;  // Save the current state for next iteration
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement