Hi there, I'm having a simple project that makes 3 LED blink randomly but only using millis()
My object is: 1 in 3 LEDs turns on for 1000ms, then 200ms later, it randomly changes to another LED.
But the problem is in my code, somehow it got like this: All 3 LEDs are on, then 1 in 3 of them turns off for 200ms, 1000ms later it randomly change to another one and repeat the progress.
Please help me!
Here's my code:
const int LEDpin1 = 2; // led 1 ứng với chân số 8
const int LEDpin2 = 3; // led 2 ứng với chân số 9
const int LEDpin3 = 4; // led 3 ứng với chân số 4
int LEDState1 =LOW;// initial state of LED
int LEDState2 =LOW;// initial state of LED
int LEDState3 =LOW;// initial state of LED
long count1 = 200;// OFF time for LED
long count2 = 1000;// ON time for LED
long rememberTime=0;// this is used by the code
byte randNumber;
void setup() {
Serial.begin(9600);
pinMode(LEDpin1, OUTPUT);
pinMode(LEDpin2, OUTPUT);
pinMode(LEDpin3, OUTPUT);
}
void loop() {
randomly();
}
void randomly(){
randNumber = random(3);
switch (randNumber) {
case 0:
if( LEDState1 == LOW ){
if( (millis() - rememberTime) >= count1){
LEDState1 = HIGH;// change the state of LED
rememberTime=millis();// remember Current millis() time
}
}
else{
if( (millis()- rememberTime) >= count2){
LEDState1 =LOW;// change the state of LED
rememberTime=millis();// remember Current millis() time
}
}
digitalWrite(LEDpin1,LEDState1);// turn the LED ON or OFF
break;
/////
case 1:
if( LEDState2 ==LOW ){
if( (millis()- rememberTime) >= count1){
LEDState2 = HIGH;// change the state of LED
rememberTime=millis();// remember Current millis() time
}
}
else{
if( (millis()- rememberTime) >= count2){
LEDState2 =LOW;// change the state of LED
rememberTime=millis();// remember Current millis() time
}
}
digitalWrite(LEDpin2,LEDState2);// turn the LED ON or OFF
break;
/////
case 2:
if( LEDState3 ==LOW ){
if( (millis()- rememberTime) >= count1){
LEDState3 = HIGH;// change the state of LED
rememberTime=millis();// remember Current millis() time
}
}
else{
if( (millis()- rememberTime) >= count2){
LEDState3 =LOW;// change the state of LED
rememberTime=millis();// remember Current millis() time
}
}
digitalWrite(LEDpin3,LEDState3);// turn the LED ON or OFF
break;
/////
}
}