This solution of not using delay() has a big advantage over the previous approaches to toggle an LED: we can perform additional tasks inside our loop, as it is no longer blocking on the delay() function. This is how we achieve the desired blink. In other words, we repeatedly take the number of seconds passed since the program started running, and set the value of the LED based on that: ON if the number if currently odd, OFF if it is currently even. This calculation returns 0 for even numbers and 1 for odd numbers: Finally, we take the number of seconds and calculate the remainder of dividing it by two, using the modulus ( %) operator. We then divide this value by 1000, so we get the number of seconds passed so far. We take advantage of Arduino's millis() function, which returns the number of milliseconds since the program has started running. The one-liner code to toggle the LED is shown below: 5 ways to blink an LED in Arduino - Using millis() By using a clever trick, we no longer need to call delay() in our code to blink the LED using Arduino. This is my favorite one, which was first presented to me by my friend Avi Ostfeld. So basically the code above could be read as: We use the ! (not) operator to invert that value, and thus toggle the state of the LED. Here's the trick: digitalRead() returns the current output value of the pin: 1 if the pin is high and the LED is on, 0 otherwise. We can easily cut the loop() code in the LED blink program down to two lines by toggling the value of the pin: 5 ways to blink an LED in Arduino - Using Inversion You can try it yourself on the free online Arduino blink code simulator playground.Ĭan we achieve the same with less code? The Two-Liner
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |