Millisecond precise timing

Hello.

I am trying to build a precise strobe lamp with customizable frequencies. I am running into a little problem though.

In my sketch, two LEDs are flashing at the same time while two other LEDs are flashing in the exact Pause, splitting the frequency in two so the flashing of the LEDs is "in higher resolution" aka. visible to the human eye.

I give the flash-timestamps as output on my monitor and see a drift in the timing. In my program, the currentMillis are incrementing by around 3 milliseconds, giving the whole blinking program a gradual shift. So over time, they dont blink every 100 milliseconds but like every 101 to 107 or 112, kinda random but overall shifting more and more over time.

I understand that the program needs some time to run through every row of code, interpreting it and then doing what it's supposed to do. What I dont understand is why? As far as I know, it has a 16MHz quartz which gives me a possible 16 Million bits/second resolution. With a baud rate of 500000 it's still shifting. I think with a baud rate that high (500000 bits/second), it should give me precise milliseconds since its only 1000 tics per second.

Either I get something wrong with the whole math itself since I might be leave out some critical info I dont know or there is some tolerance in the ATMEGA which just doesnt work that precise by default.

If I want to build myself a programmable timer, what are my alternatives? I heard about the NE555 but am not really sure how to set it up.

Thanks for reading :slight_smile:

Cheers

no.

show

Also, no.

/*#include <LiquidCrystal.h>

// LCD Pins: {RS, E, D4, D5, D6, D7};
LiquidCrystal lcd{10, 4, 8, 7, 6, 2};*/

// constants won't change. Used here to set a pin number:
const int ledPin =  3;// the Pin number of the LED
const int led2Pin = 5;// the Pin number of LED 2 
const int led3Pin = 9;
const int led4Pin = 11;

// Flankenerkennungsvariablen

bool Aufsteigend1 = 0;
bool Fallend1 = 0;
bool Aufsteigend2 = 0;
bool Fallend2 = 0;
bool Aufsteigend3 = 0;
bool Fallend3 = 0;
bool Aufsteigend4 = 0;
bool Fallend4 = 0;
bool Aufsteigend[] = {NULL, Aufsteigend1, Aufsteigend2, Aufsteigend3, Aufsteigend4};
bool Fallend[] = {NULL, Fallend1, Fallend2, Fallend3, Fallend4};
//bool LED = 0;

// Flash() Variablen

bool halt1 = 0;
bool halt2 = 0;
bool halt3 = 0;
bool halt4 = 0;
bool halt[] = {NULL, halt1, halt2, halt3, halt4};

double flash = 0;
bool LED1 = 0;
bool LED2 = 0;
bool LED3 = 0;
bool LED4 = 0;
bool LED[] = {NULL, LED1, LED2, LED3, LED4};

// Variables will change:
bool ledState = LOW;             // ledState used to set the LED
bool ledState2 = LOW;            // ledState2 für die zweite LED
bool ledState3 = LOW;
bool ledState4 = LOW;

bool ledStates[] = {ledState, ledState2, ledState3, ledState4};

// constants won't change:
double x;                     // Die Frequenz die geblinkt werden soll

//Const für Blink1
long previousMillis;        // will store last time LED was updated

//Const für Blink2
long previousMillis2;

//Const für Blink3
long previousMillis3;
long previousMillis4;
long previousMillis5;

//Const Testprogramm
  int Stopp1;
  int Stopp2;
  int Stopp3;
  int Stopp4;
  int Stopp5;
  int Stopper;
  int Stopp[] = {Stopp1, Stopp2, Stopp3, Stopp4, Stopp5};
  int Stopperer;

  int Abschnitt;
  
// Frequenzabhängige Switch Case
int auswahl; //Je nach Frequenz wird hier die passende Blinkfunktion ausgewählt, damit keine LED durchgehend an ist
bool initial = 0;

// PROGRAMMSTART

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  Serial.begin(500000);
 
}


void loop() {

 x = 10;

 BlinkAuswahl();
 
}

void Blink1(){
  
   long currentMillis = millis();
   double Hertz = (1 / x) * 500;    // Hertz Intervall wird berechnet
   double interval = Hertz;           // interval at which to blink (milliseconds) in Hz

   while(initial != 1){
    previousMillis = currentMillis;
    initial = 1;
   }
   
if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
      previousMillis = currentMillis;

      //Flankenerkennung innerhalb der if-Schleife, die hier als Clock Signal dient
      Flanke(1);
      }

      //Theoretisch jetzt ein Timer, in dem die ON/OFF Zeit für die LED rein soll
      Flash(1,1);
      
      ledState = LED[1];
  
  Serial.println("");
  Serial.print("CurrentTime: ");
  Serial.println(currentMillis);
  Serial.print("previousMillis: ");
  Serial.println(previousMillis);
  
    // set the LED with the ledState of the variable:
     digitalWrite(ledPin, ledState);
     digitalWrite(led2Pin, ledState);
     digitalWrite(led3Pin, ledState);
     digitalWrite(led4Pin, ledState);
   
   //Serial.println(previousMillis);
}

void Blink2(){

  double x_zwei = x / 2;             // Die Frequenz für den Timer nach dem ersten Split, damit kein durchflimmern vorliegt
  double Hertz2 = (1 / x_zwei) * 500;    // Hertz Intervall wird berechnet für Blink2
  double interval2 = Hertz2;
  long currentMillis = millis();  

  while(initial != 1){
  previousMillis = currentMillis;
  previousMillis2 = currentMillis + Hertz2;
  initial = 1;
  }

  Serial.print("Interval: ");
  Serial.println(interval2);
  Serial.print("currentMillis: ");
  Serial.println(currentMillis);
  Serial.print("previousMillis: ");
  Serial.println(previousMillis);
  Serial.print("previousMillis2: ");
  Serial.println(previousMillis2);
  Serial.println("");
   
   if (currentMillis - previousMillis >= interval2) {
    // save the last time you blinked the LED
      previousMillis = currentMillis;

    Flanke(1);
   }

    Flash(1,2);

    ledState = LED[1];

    // set the LED with the ledState of the variable:
     digitalWrite(ledPin, ledState);
     digitalWrite(led3Pin, ledState);

     if (currentMillis - previousMillis2 >= interval2) {
    // save the last time you blinked the LED
      previousMillis2 = currentMillis;

      Flanke(2);
     }

     Flash(2,2);

     ledState2 = LED[2];

    // set the LED with the ledState of the variable:
     digitalWrite(led2Pin, ledState2);
     digitalWrite(led4Pin, ledState2);
     
}

void Blink3(){

  double x_drei = x / 4;                   // Die Frequenz für den ersten Timer im dritten Split
  double Hertz3 = (1 / x_drei) * 500;     // Hertz Intervall wird berechnet -> Das Intervall wird von der Insgesamtzahl auf 4 LEDs verteilt, da x_drei die Frequenz viertelt für Blink3
  double interval3 = Hertz3;
  long currentMillis = millis();
  
  while(initial != 1){
   previousMillis = currentMillis;
   previousMillis3 = currentMillis + (Hertz3 *2/ 4);      //Zweiter Timer für die zweite LED, die in den Pausen der ersten LED blinkt
   previousMillis4 = currentMillis + (Hertz3 *2/ 2);      //Zweiter Timer für die zweite LED, die in den Pausen der ersten LED blinkt
   previousMillis5 = currentMillis + (Hertz3 * 3 *2/ 4);  //Zweiter Timer für die zweite LED, die in den Pausen der ersten LED blinkt
   initial = 1;
  }

  Serial.println("");
  Serial.print("Intervall: ");
  Serial.println(interval3);
  Serial.print("CurrentTime: ");
  Serial.println(currentMillis);
  Serial.print("previousMillis: ");
  Serial.println(previousMillis);
  Serial.print("PreviousMillis3: ");
  Serial.println(previousMillis3);
  Serial.print("PreviousMillis4: ");
  Serial.println(previousMillis4);
  Serial.print("PreviousMillis5: ");
  Serial.println(previousMillis5);

if (currentMillis - previousMillis >= interval3) {
    // save the last time you blinked the LED
      previousMillis = currentMillis;
      Flanke(1);
   }

    Flash(1,3);
    ledState = LED[1];

    // set the LED with the ledState of the variable:
     digitalWrite(ledPin, ledState);

if (currentMillis - previousMillis3 >= interval3) {
    // save the last time you blinked the LED
      previousMillis3 = currentMillis;
      Flanke(2);
    }

    Flash(2,3);
    ledState2 = LED[2];
    
    // set the LED with the ledState of the variable:
     digitalWrite(led2Pin, ledState2);
   
 if (currentMillis - previousMillis4 >= interval3) {
    // save the last time you blinked the LED
      previousMillis4 = currentMillis;
      Flanke(3);
    }

    Flash(3,3);
    ledState3 = LED[3];
    // set the LED with the ledState of the variable:
     digitalWrite(led3Pin, ledState3);
 
 if (currentMillis - previousMillis5 >= interval3) {
    // save the last time you blinked the LED
      previousMillis5 = currentMillis;
      Flanke(4);
    }

    Flash(4,3);
    ledState4 = LED[4];
    // set the LED with the ledState of the variable:
     digitalWrite(led4Pin, ledState4);
     
}

void Flanke(int Speicher){
  if(Aufsteigend[Speicher] == 0){
    Aufsteigend[Speicher] = 1;
    Fallend[Speicher] = 0;
  }
  else{
   Aufsteigend[Speicher] = 0;
   Fallend[Speicher] = 1;
  }
}

void Flash(int Speicher, int Blink){      // Speicher ist die Vraiable, in der bei mehreren Flash-Zugriffen auf verschiedene Speicherbereiche zugegriffen werden soll, Blink ist dazu da um die Einschaltzeit für die LEDs zu berechnen
  long currentMillis = millis();
  double x_zwei = x / 2; 
  double x_drei = x / 4;  
  double Frequenz1 = (1 / x) * 500; 
  double Frequenz2 = (1 / x_zwei) * 500;
  double Frequenz3 = (1 / x_drei) * 500;
  double Frequenz[] = {0, Frequenz1, Frequenz2, Frequenz3};
  double flashtime = Frequenz[Blink] / 10; //Zweite Variable wegen der Blink Funktion und entsprechender Frequenz zum blinken
  /*Serial.print("flashtime : ");
  Serial.println(flashtime);*/
  if(Aufsteigend[Speicher] == 1 && Fallend[Speicher] == 0){
        LED[Speicher] = 1;
        while(halt[Speicher] != 1){
          flash = currentMillis;
          halt[Speicher] = 1;
        }
        }
      
      if(currentMillis - flash >= flashtime){
        LED[Speicher] = 0;
      }

      if(Aufsteigend[Speicher] == 0 && Fallend[Speicher] == 1){
        halt[Speicher] = 0;
      }
}

//Vor jedem Programmwechsel bzw vor jedem Frequenzwechsel im Programm müssen alle Speicher und Werte zurückgesetzt werden.
void Reset(){
  
  // Initial muss für die nächsten Zeitabgriffe anderer Frequenzen zurückgesetzt werden.
  initial = 0;
  ledState = 0;
  ledState2 = 0;
  ledState3 = 0;
  ledState4 = 0;

  // Alle Flanken, halte-Variablen und LED States müssen zurückgesetzt werden. Sie werden im Programm in Form von Arrays gespeichert.
  for(int i = 0; i < 5; i++){  // Die Arrays haben alle 5 Einträge, da 4 Zustände und die 0 an erster Stelle
    Aufsteigend[i] = 0;
    Fallend[i] = 0;
    LED[i] = 0;
    halt[i] = 0;
    }

  // Die LEDs sollen bei x = 0 aus sein. Das geht nur, indem sie mit dem LED Wert überschrieben werden.
  digitalWrite(ledPin, LED[1]);
  digitalWrite(led2Pin, LED[2]);
  digitalWrite(led3Pin, LED[3]);
  digitalWrite(led4Pin, LED[4]);
  
}

void BlinkAuswahl(){
  if(x == 0)
  auswahl = 0;
  if(x>0 && x<10)
  auswahl = 1;
  if(x>=6&&x<14)
  auswahl = 2;
  if(x>=14)
  auswahl = 3;
  
  switch(auswahl){
    case 1:
      Blink1();
    break;
    case 2:
      Blink2();
    break;
    case 3:
      Blink3();
    break;
    case 0:
      Reset();
    break;
  }
}

The sketch alone should be enough to see the shift. If you want to set up my build, it's just 4 LEDs with a resistor going from 5V to GND with a NPN Transistor C and E inbetween. The PIN Output connects to the base.

Can you draw a schematic, I think the transistor is not used correctly.
Can you tell what the leds should do ? The hardware timers can generate opposite signals in hardware.
Can you show a photo of your project with the Arduino board ? To check if you have a resonator or a crystal.

How? As a new user I can only post embedded things.

The leds do blink, there is no problem in the physical realm. The code is the problem, its shifting in time, making my theoretical 10Hz into a software-sided 9.9Hz one, but giving me more error the higher my frequency.

Since I cannot post pictures as a new user, I posted the drawn schematic and snap of my setup on imgur.

What is the NULL element for?
(Multiple times)

It's so my Array starts at 1. That way I don't have to re-think starting positions in the blink() functions later. Basically makes it easier for me to fill in a 1 in the blink1(), for LED1 which ist my actual LED number 1..
I just dont want to confuse myself in the process

Doesn't having only one "initial" variable screw things up?

(It looks to me like you have too much code for what you want to do, but also not enough code for all the things you are doing )

It doesnt screw it up. Initialising stays with the frequency. It is only reused if the frequency changes. There is a reset before every frequency change though.

It's missing a current limiting resistor on the transistor base.

You are right, I even left them out in the setup. I added 1kOhm resistors to the base now.

So why does ledStates start from zero?

In not confusing yourself, you're confusing everyone else.

(You dont have enough pinModes)

The ledState Array isn't used in the program. I set it up with the other ones but decided to work with the ledStates differently.

I kinda found the explanation to why this happens. The millis() function is not accurate. The 16MHz crystal is divided "by 2 divider hardware to get an exact millisecond output - -the closest you can get is 1024us" as said here: https://www.best-microcontroller-projects.com/arduino-millis.html

So the time itself has a drift, which get's corrected by code but might still create some problems - which it does in my case.

Yes, but the short term difference between two millis() readings will be accurate.

Yes, millis() may not be 100% accurate but it is reasonably close.

You should get better timing using:

previousMillis = previousMillis + interval;

instead of 

previousMillis = currentMillis;

That will prevent cumulative errors due to varying code execution times.

Thanks Wilem. It terminates cumulative errors, makes the actual problem invisible though.

On one hand, the interval is kinda stable but the actual frequency still differs. Is there a way to give the timer a higher resolution? I've read about the timer 1 now, which has a 16 bit resolution instead of a 8 bit one.. I am not quite sure how to set it up though.