I am trying to control 4 LED's, each with a momentry contact switch, so that when you first press the switch the LED starts flashing, until the button is pressed again.
At the moment I have only tried to make the LED flash 10 times when the button is pressed, but even this does not work correctly. LED 1 flashes occasionally and stays on most of the time, LED 2 also flashes if I press the button, but it does not appear to do so to any pattern that I have programmed and seems to only flash when LED 1 is off. the remaining LED's refuse to flash when the button is pressed.
As I am not used to c programming I am not sure where I am going wrong.
Also how do I program press once for ON, press again for OFF?
I learn best by looking at examples, so please contribute ideas that I can use in this project.
Here is the code:
int switch1Pin = 4; // Button 1 is connected to pin 4
int switch2Pin = 5; // Button 2 is connected to pin 5
int switch3Pin = 6; // Button 3 is connected to pin 6
int switch4Pin = 7; // Button 4 is connected to pin 7
int led1Pin = 12;
int led2Pin = 11;
int led3Pin = 10;
int led4Pin = 9;
int switch1State = 0;
int switch2State = 0;
int switch3State = 0;
int switch4State = 0;
int switch5State = 0;
int timer = 100; // The higher the number, the slower the timing.
void setup() {
pinMode(switch1Pin, INPUT); // Button 1
pinMode(switch2Pin, INPUT); // Button 2
pinMode(switch3Pin, INPUT); // Button 3
pinMode(switch4Pin, INPUT); // Button 4
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
pinMode(led3Pin, OUTPUT);
pinMode(led4Pin, OUTPUT);
}
void loop() {
switch1State = digitalRead(switch1Pin); // read input values
switch2State = digitalRead(switch2Pin);
switch3State = digitalRead(switch3Pin);
switch4State = digitalRead(switch4Pin);
if (switch1State == HIGH) // when the first button is pressed
VID1();
else if (switch2State == HIGH) // when the next button is pressed
VID2();
else if (switch3State == HIGH) // the next button
VID3();
else if (switch4State == HIGH) // the next button
VID4();
}
void VID1(){
for (int i=0; i <10; i++){
digitalWrite(led1Pin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(led1Pin, LOW);
}
}
void VID2(){
for (int i=0; i <10; i++){
digitalWrite(led2Pin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(led2Pin, LOW);
}
}
void VID3(){
for (int i=0; i <10; i++){
digitalWrite(led3Pin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(led3Pin, LOW);
}
}
void VID4(){
for (int i=0; i <10; i++){
digitalWrite(led4Pin, HIGH);
delay(timer);
// turn the pin off:
digitalWrite(led4Pin, LOW);
}
}
Many thanks!