[SOLVED] How is the millis() function made ?

I see 3 possibilities :

  1. it uses a timer witch overflows each millisecond , and fires an interrupt ;
    in the ISR , the millis variable is incremented
  2. it uses a timer witch overflows each millisecond , and fires an interrupt
    in the ISR , a flag is set , anywhere in the RAM ; then in the loop , in a place reserved to the arduino system , if this flag is set , the millis variable is incremented , and the flag in RAM is reset (this method looks maybe stupid , but it's the way we , as users , are told to handle interrupts ... )
  3. it uses a timer witch overflows each millisecond ; no interrupt ; in the part of the loop reserved to the arduino system , there is a polling of the overflow flag of the timer ; if the overflow flag is set , the millis variable is incremented , and the overflow flag of the timer is reset
    witch is the right one , who knows ?

ArduinoCore-avr/cores/arduino/wiring.c at master · arduino/ArduinoCore-avr · GitHub

What's described above is how it works on AVR-based boards. Other processors are different. For example:

On Teensy ARM-based boards it uses the ARM's systick timer.
On ESP32 boards, it uses the esp_timer_get_time() API.

To be clear, Teensy ARM boards use the systick timer's interrupt to update their internal millis() counter. But there's no fudging it for 1000 vs 1024. The micros() function uses the same internal millis() counter (x 1000) adjusted with the live value from systick.

1. A millisCounter is a 32-bit storage space (Fig-1) in SRAM area of the MCU formed by cascading 4 byte oriented memory locations.
milllisCounterX.png
Figure-1:

2. At the end of sketch uploading, the millisCounter holds 0x00000000 and then advanced by one for every 1 ms of elapsed time on interrupt basis in the background.

3. The millisCounter will arrive at maximum count (0xFFFFFFFF = 4294967295) at the elapse of 4294967295 ms (about 49 days). When another 'time tick' arrives, the millisCounter completes “Full Count” ;and will turn from all 1s to all 0s -- an event that is known as roll over.

4. The content of the millisCounter can be read "on the fly" (without disturbing the counting process) by executing the following code:

unsigned long int presentMillis = millis();

ok , thank you all ; noiasca gave mi a lot of thinks I have to read

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.