5 Replies Latest reply on Mar 16, 2018 5:38 PM by FerryT

    Linux timer interval

    michalt38

      Hello I want to run a timer with interval of 5 ms. I created a Linux timer and when a sigalrm_handler is called I'm checking elapsed time from a previous call. I'm getting times like: 4163, 4422, 4266, 4443, 4470 4503, 4288 microseconds when I want intervals to be about 5000 microseconds with a least possible error. Here is my code:

       

      #include <stdio.h>
      #include <signal.h>
      #include <sys/time.h>
      #include <unistd.h>
      
      
      static int time_count;
      static int counter;
      struct itimerval timer={0};
      
      
      void sigalrm_handler(int signum)
      {
        Serial.print("SIGALRM received, time: ");
        Serial.println(micros()-time_count);
        time_count=micros();
        counter++;
        if(counter > 20) {
          timer.it_interval.tv_usec = 0;
          timer.it_value.tv_sec = 0;
          setitimer(ITIMER_REAL, &timer, NULL);
        }
      }
      
      
      void setup() {
        // put your setup code here, to run once:
        Serial.begin(9600);
        /* Initial timeout value */
        timer.it_value.tv_sec = 1;
      
      
        /* We want a repetitive timer */
        timer.it_interval.tv_usec = 5000;
      
      
        /* Register Signal handler
         * And register for periodic timer with Kernel*/
        signal(SIGALRM, &sigalrm_handler);
        setitimer(ITIMER_REAL, &timer, NULL);
        time_count = micros();
      }