In this project, I will show you how to control multiple LEDs, and use a switch button to change displaying pattern. I will also show you how to include header file to make code tidier.
Everytime button is pressed, it switches the lighting patterns. The patterns are:
0. all off
1. all on
2. one at a time and keep changing.
/* Oscar's project switch lighting patern of 5 LEDs */ int patern = 0; // 0 all off // 1 all on // 2 one on at a time int onLED = 1; // which LED is on? 1-5 int buttonState = 0; int iPin = 0; // input pin int oPin1 = 1; // output pins int oPin2 = 2; int oPin3 = 3; int oPin4 = 4; int oPin5 = 5; void setup() { // declare pin 9 to be an output: pinMode(oPin1, OUTPUT); pinMode(oPin2, OUTPUT); pinMode(oPin3, OUTPUT); pinMode(oPin4, OUTPUT); pinMode(oPin5, OUTPUT); pinMode(iPin, INPUT); } void loop() { buttonState = digitalRead(input); if (buttonState == 1){ if (patern >= 2) patern = 0; else patern++; onLED = 1; // reset onLED buttonState = 0; } if (patern == 0) { digitalWrite(oPin1, LOW); digitalWrite(oPin2, LOW); digitalWrite(oPin3, LOW); digitalWrite(oPin4, LOW); digitalWrite(oPin5, LOW); } else if (patern == 1) { digitalWrite(oPin1, HIGH); digitalWrite(oPin2, HIGH); digitalWrite(oPin3, HIGH); digitalWrite(oPin4, HIGH); digitalWrite(oPin5, HIGH); } else { switch (onLED) { case 1: digitalWrite(oPin1, HIGH); digitalWrite(oPin2, LOW); digitalWrite(oPin3, LOW); digitalWrite(oPin4, LOW); digitalWrite(oPin5, LOW); break; case 2: digitalWrite(oPin1, LOW); digitalWrite(oPin2, HIGH); digitalWrite(oPin3, LOW); digitalWrite(oPin4, LOW); digitalWrite(oPin5, LOW); break; case 3: digitalWrite(oPin1, LOW); digitalWrite(oPin2, LOW); digitalWrite(oPin3, HIGH); digitalWrite(oPin4, LOW); digitalWrite(oPin5, LOW); break; case 4: digitalWrite(oPin1, LOW); digitalWrite(oPin2, LOW); digitalWrite(oPin3, LOW); digitalWrite(oPin4, HIGH); digitalWrite(oPin5, LOW); break; case 5: digitalWrite(oPin1, LOW); digitalWrite(oPin2, LOW); digitalWrite(oPin3, LOW); digitalWrite(oPin4, LOW); digitalWrite(oPin5, HIGH); break; default: digitalWrite(oPin1, LOW); digitalWrite(oPin2, LOW); digitalWrite(oPin3, LOW); digitalWrite(oPin4, LOW); digitalWrite(oPin5, LOW); } if (onLED >= 5) onLED = 1; else onLED++; } delay(30); } |