Non-Blocking Delays
Using delay() function
void loop()
{
int button_state = digitalRead(button_pin);
if(button_state == HIGH) {
digitalWrite(led_pin,HIGH);
} else {
digitalWrite(led_pin,LOW);
}
delay(1000);
}
Without delay() function. Using non-blocking delays
static int last_time = millis();
void loop()
{
int current_time = millis();
int button_state = digitalRead(button_pin);
// This is the "delay" block, runs until 1
// second elapsed since the previous time it ran.
// The code in this section is equivalent to the
// delay() code above.
if(current_time - last_time >= 1000){
if(button_state == HIGH){
digitalWrite(led1_pin, HIGH);
}else{
digitalWrite(led1_pin, LOW);
}
last_time = current_time;
}
if(button_state == HIGH){
digitalWrite(led2_pin, HIGH);
}else{
digitalWrite(led2_pin, LOW);
}
}
Comments
Leave a Comment