I have eight LEDs, four red ones and four yellow ones. There is one button for both rows. When you push a button, a row of LEDs gets a pulse. That means they light up in a row in 0.1 second intervals. My question is now: Can I send a pulse while another one is still being processed? At the moment a function is called in which a for loop sets the state of the LEDs to HIGH and low, but I can not run it again, before it is finished.
void setup()
{
pinMode(0, OUTPUT);
pinMode(1, OUTPUT);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, INPUT);
pinMode(13, INPUT);
Serial.begin(9600);
}
boolean wait(unsigned int j, unsigned int time) <-- test if 0.1 seconds have passed
{
if (millis()>=time+j){
return true;
}
else return false;
}
void pulse(int start)
{
for(int j = start;j < start + 4;j++)
{
digitalWrite(j, HIGH);
unsigned int time = millis();
while(wait(100, time)==false){};
digitalWrite(j, LOW);
}
}
void loop()
{
if (digitalRead(12) == HIGH)
{
Serial.println("yellow");
pulse(2); <-- I have to wait for this function
}
if (digitalRead(11) == HIGH)
{
Serial.println("red");
pulse(6); <-- I have to wait for this function
}
}
This is how I would write the code for this project.
unsigned long yellowButtonPress = 0;
unsigned long yellowTimeElapsed = 0;
int yellowLED = 2
unsigned long redButtonPress = 0;
unsigned long redTimeElapsed = 0;
int redLED = 6
unsigned long MAX_Time = 400;
void setup(){
//Setup the INPUT and OUTPUT pins
for (int x=2; x<10; x++){
pinMode(x, OUTPUT);
}
pinMode(12, INPUT); //Yellow Button
pinMode(13, INPUT); //Red Button
}
void loop{
yellowTimeElapsed = millis() - yellowButtonPress;
redTimeElapsed = millis() - redButtonPress;
//Check if yellow button has been pressed
if(digitalRead(12) == HIGH && yellowTimeElapsed > MAX_Time){
yellowButtonPress = millis();
}
//Check if red button has been pressed
if(digitalRead(13) == HIGH && redTimeElapsed > MAX_Time){
redButtonPress = millis();
}
//Identify which yellow LED needs to be on at this time
if (yellowTimeElapsed > Max_Time){
yellowLED=0; //This will turn off all yellow LEDs
} else {
yellowLED = map(yellowTimeElapsed, 0, MAX_Time, 2,5);
}
//Identify which red LED needs to be on at this time
if (redTimeElapsed > Max_Time){
redLED=0; //This will turn off all red LEDs
} else {
redLED = map(redTimeElapsed, 0, MAX_Time, 6,9);
}
//Turn the yellow and/or red LEDs on and off
for (int i = 2; i<10; i++){
if (i == yellowLED || i == redLED){
digitalWrite(i,HIGH);
} else {
digitalWrite(i,LOW);
}
}
}