3 Buttons 3 Leds MIW

3 Buttons 3 Leds Coded

Lesson Learned:

  • Controlled by Arduino Controller Off-line.
  • Use const to keep track of pin numbers for buttons and leds
  • It is SO easy to fry a board:
    • Always connect GROUND before you connect POWER
    • Always dis-connect POWER before you dis-connect GROUND
  • Color coded wires helps:
    • GROUND = Black, Grey
    • POWER = Red, Orange
    • Match wire colors to Button and LED colors

Sample Code:

// CONSTS
//
const int butPinBlue = 9;
const int butPinYellow = 7;
const int butPinGreen = 8;
//
const int ledPinBlue = 5;
const int ledPinYellow = 4;
const int ledPinGreen = 3;

// VARS
//
int butStateBlue = 0;
int butStateYellow = 0;
int butStateGreen = 0;

// CUSTOM TIMERS
long lastButPressedTime = 0;
long butPressedDelay = 100;


// the setup function runs once when you press reset or power the board

void setup() {
  Serial.begin(9600);
  delay(1500); 
  
  // initialise BUTTONS as INPUT
  pinMode(butPinGreen, INPUT);
  pinMode(butPinYellow, INPUT);
  pinMode(butPinBlue, INPUT);
  
  // initialize LED's as OUTPUT
  pinMode(ledPinGreen, OUTPUT);
  pinMode(ledPinYellow, OUTPUT);
  pinMode(ledPinBlue, OUTPUT);
}

// the loop function runs over and over again forever

void loop() {
  
  Serial.println("looping");
  
  // but Pressed Delay
  if ( (millis() - lastButPressedTime) > butPressedDelay) {
    
    butStateBlue = digitalRead(butPinBlue);
    butStateYellow = digitalRead(butPinYellow);
    butStateGreen = digitalRead(butPinGreen);
    
    if (butStateBlue == LOW) {
       // turn LED on:
      digitalWrite(ledPinBlue, HIGH);
    } else {
      // turn LED off:
     digitalWrite(ledPinBlue, LOW);
    }    
    if (butStateYellow == LOW) {
     // turn LED on:
      digitalWrite(ledPinYellow, HIGH);
    } else {
      // turn LED off:
      digitalWrite(ledPinYellow, LOW);
    }  
    if (butStateGreen == LOW) {
      // turn LED on:
      digitalWrite(ledPinGreen, HIGH);
    } else {
      // turn LED off:
      digitalWrite(ledPinGreen, LOW);
    }
    
    // reset to current time
    lastButPressedTime = millis(); 
  } 
  
} // END LOOP