SunFounder 3in1 Kit
• When the button is pressed, its value is HIGH. Here, when the button is pressed, the value of the
variable detectionState is changed, e.g., from 0 to 1 after an operation.
if (buttonState == HIGH) {
detectionState=(detectionState+1)%2;
Serial.print("The detection state is: ");
Serial.println(detectionState);
}
• When the variable detectionState is 1, let the motor rotate, otherwise stop.
if(detectionState==1){
digitalWrite(motorPinA,HIGH);
digitalWrite(motorPinB,LOW);
}else{
digitalWrite(motorPinA,LOW);
digitalWrite(motorPinB,LOW);
}
4.5.4 5.4 Interval
Sometimes you need to do two things at once. For example you might want to blink an LED while reading a button
press. In this case, you can’t use delay(), because Arduino pauses your program during the delay(). If the button
is pressed while Arduino is paused waiting for the delay() to pass, your program will miss the button press.
An analogy would be warming up a pizza in your microwave, and also waiting some important email. You put the pizza
in the microwave and set it for 10 minutes. The analogy to using delay() would be to sit in front of the microwave
watching the timer count down from 10 minutes until the timer reaches zero. If the important email arrives during this
time you will miss it.
What you would do in real life would be to turn on the pizza, and then check your email, and then maybe do something
else (that doesn’t take too long!) and every so often you will come back to the microwave to see if the timer has reached
zero, indicating that your pizza is done.
This sketch demonstrates how to tone an buzzer without using delay(). It turns the buzzer on and then makes note
of the time. Then, each time through loop(), it checks to see if the desired interval time has passed. If it has, it tone
the buzzer and makes note of the new time. In this way the buzzer tones continuously while the sketch execution never
lags on a single instruction.
Based on this condition, we can add the code of the button to control the LED, it will not be disturbed by the buzzer
playing music.
Required Components
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
Name ITEMS IN THIS KIT LINK
3 in 1 Starter Kit 380+
You can also buy them separately from the links below.
142 Chapter 4. Basic Projects