How to Use Loops in Arduino Programming - Ultimate Guide to the Arduino #13
HTML-код
- Опубликовано: 27 мар 2023
- Loops are used to control the flow of a program. A program enters or exits a loop depending on certain conditions defined in the code. Learn how to use several different types of loops in your Arduino programs with this in-depth tutorial!
This is tutorial #13 in the Ultimate Guide to the Arduino, a complete video course on the Arduino microcontroller with 45 lessons that are designed to teach anyone how to master the Arduino at any skill level. Visit our RUclips channel page to watch the entire series!
Get the 3-in-1 Arduino Smart Car and IOT Learning Kit from SunFounder here:
www.sunfounder.com/products/s...
Or get the kit from Amazon:
US Amazon: amzn.to/3W1Mahh
DE Amazon: amzn.to/3j0oETn
JP Amazon: amzn.to/3UYrHZG
UK Amazon: amzn.to/3uTJZAC
CA Amazon: amzn.to/3W2vExN
Get an Arduino Uno from SunFounder here:
www.sunfounder.com/products/a...
Visit the webpage for this video tutorial on Circuit Basics for wiring diagrams and example code:
www.circuitbasics.com/using-l...
And be sure to check out the Circuit Basics blog and social media for more articles and tutorials on the Raspberry Pi, Arduino and other DIY electronic projects!
www.circuitbasics.com
Facebook: / circuitbasic
Twitter: / circuitbasics
Instagram: / circuitbasics - Наука
so in the first example showcasing the while loop command, line10 declares "int buttonState = digitalRead(buttonPin)" to store the pin#7's high or low signal. Using while (buttonState == LOW) to trigger the LED to be ON and OFF codes using button here at 4:17, I found out that the "while" loop command only needs one condition check, after that It will repeatedly run codes. so the button became a onetime trigger.
so I changed the "while" to "if", The problem was solved, and now the button can control the LED to be ON and OFF.
guess the difference between "while" and "if" is, the "if" command checks the condition true or false every time, "while" only checks once.
Amazing ❤
Why is the while-loop stopping when you didn't read the button again inside the loop???
Yes, to get this to work:
void loop() {
int buttonState = digitalRead(buttonPin);
while (buttonState == LOW) {
digitalWrite(LEDPin, HIGH);
delay(200);
digitalWrite(LEDPin, LOW);
delay(200);
buttonState = digitalRead(buttonPin);
}
}