Week 9 – Switches and LEDs

Concepts and methods

For this assignment, I wanted to simulate police lights so I used two LEDs (blue and red) and two push (button switches). Each switch turns on the respectively colored LED, and when both switches are pressed the LEDs blink continuously looking like police lights.

Schematic

Code

//Declare the button switches and the LEDs 
const int BUTTON1 = 2;
const int BUTTON2 = 5;
const int LED1 = 8;
const int LED2 = 12;
int BUTTONstate1 = 0;
int BUTTONstate2 = 0;

void setup()
{
//Declare the buttons as input and the LEDs as output
pinMode(BUTTON1, INPUT);
pinMode(BUTTON2, INPUT);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
}

void loop()
{
// Turn on the blue LED by pressing the blue switch
BUTTONstate1 = digitalRead(BUTTON1);
if (BUTTONstate1 == HIGH)
{
digitalWrite(LED1, HIGH);
}
else{
digitalWrite(LED1, LOW);
}
//Turn on the Red LED by pressing the red switch
BUTTONstate2 = digitalRead(BUTTON2);
if (BUTTONstate2 == HIGH)
{
digitalWrite(LED2, HIGH);
}
else
{
digitalWrite(LED2, LOW);
}
//Blink the two LEDs when the two switches are pressed
if (BUTTONstate1 == HIGH && BUTTONstate2 == HIGH){
digitalWrite (LED1, HIGH);   
digitalWrite (LED2, LOW);   
delay(750);  // Wait 750ms  
digitalWrite (LED1, LOW);  
digitalWrite (LED2, HIGH);  
delay(500);  // Wait 500ms 
}
}

Video

Future Improvements 

In the future, I would like to experiment with a greater number of LEDs. Additionally, I would like to implement analog switches such as the potentiometer next.

Leave a Reply