Arduino Einstieg (15) – Zeitmessung mit der millis()-Funktion
Here we see our first Blink program again.. We set the switching time with the delay function., But it has one major disadvantage. During this time. The program is stopped and no more program code is executed.. For example, if we want to build an interval blinker that should change the blinking frequency every 5 seconds, we wont get any further with that.. If we were to measure the 5 seconds with the delay function, the LED could no longer flash, because the program is standing.. We need a time measurement while the program is running and the millis function will help us.. It does nothing but count the milliseconds that have passed since the program started.. It can count to the power of 2 to the power of 32, and that takes almost 50 days.. Then it starts again at 0.. If we compare the values from two different points in time, we know how much time has passed between them.. What could our program look like? As mentioned, the interval should be 5 seconds and the LED should flash once every 800 milliseconds and, alternatively, every 100 milliseconds. Lets define a few values first.. If they are to be visible throughout the program, they must be defined as global variables at the very beginning. Our interval time 5000 milliseconds does not change and is therefore a constant.. The boolean variable LED tells us whether the LED should light up or not. The default is false.. The millis function returns times in unsigned long format.
. This is an unsigned 32 bit number, and so we define all our time values in that format.. This is the respective actual time the flashing time which we initially preset to 800 milliseconds and the flashing and interval start time which we give an initial value with the millis function. At the beginning of the loop. We determine the actual time again.. Now we ask whether the 5 second interval has already been reached. Is actual time minus interval start time greater than or equal to interval. If so, we need to change the flashing frequency. If its just 800 milliseconds, let it go to 100 milliseconds.. If not, then it is currently at 100 milliseconds and should now be changed to 800 milliseconds., And we need to restart our interval by setting the start time to the current actual time.. We do the same query with our flashing time.. We calculate whether the 800 or 100 milliseconds have already passed.. If so, the LED is toggled.. If true the LED is switched on, if false it is switched, off. And the query starts again from the beginning.. Hopefully it works too. Very beautiful.. So if you dont mind the program being interrupted, you can work with the delay function.. Otherwise, the millis function is the method of choice. Thats it for today.. I hope you liked it.