Skip to menu

Robotics with Object Pascal

Controls

(*) Nano Second Sleep only on Linux, not for MS Windows (*)
 
While I was making library for BNO-055 9-Axis IMU chip, I had to deal with microsecond sleep function.
While I was unsuccessful on getting microsecond sleep, I got nanosecond sleep instead.
Although it looks like working properly, yet I'm not 100% sure.
After I have done some testing, I have noticed that there is about 70 microseconds overhead each time the function is called.
As long as being aware of that 70 microseconds overhead, this function can be used.
 
 
nanosleep.png
program NanoSleep;
{ Program to demonstrate the NanoSleep function. }
{ It works only on LINUX }
uses BaseUnix;

Var
  Reqested, Remaining : TimeSpec;
  ResultVal : Longint;

begin
   // Here, enter time to sleep (seconds + nanoseconds)
   with Reqested do begin
      tv_sec  := 0;
      tv_nsec := 200000; // 200 microseconds = .2 milliseconds
   end;

   writeln('NanoSleep Starting!');
   Flush(Output);

   // Sleep
   ResultVal:=(fpNanoSleep(@Reqested,@Remaining));

   if ResultVal = 0 then
      writeln('Succeed!')
   else
      with Remaining do begin
         writeln('Remaining seconds     : ',tv_sec);
         writeln('Remaining nanoseconds : ',tv_nsec);
      end;
end.
 
 
 
 
Accuracy_Test.png

program NanoSleepAccuracyTest;
{ Program to demonstrate the NanoSleep function. }
{ It works only on LINUX }
uses BaseUnix, Unix, sysutils;

Var
  Reqested, Remaining : TimeSpec;
  ResultVal, microgap : Longint;
  tvprev, tvcur : timeval;  // for fpgettimeofday
begin
   // Here, enter time to sleep (seconds + nanoseconds)
   with Reqested do begin
      tv_sec  := 0;
      tv_nsec := 900000; // 100000 nanoseconds = .1 milliseconds
   end;

   writeln('Sleep Starts for ', inttostr(Reqested.tv_nsec div 1000));

   fpgettimeofday(@tvprev, nil);// get timestamp BEFORE sleep
   ResultVal:=(fpNanoSleep(@Reqested,@Remaining));  // Sleep
   fpgettimeofday(@tvcur, nil); // get timestamp AFTER sleep

   // Get the gap only for microseconds which is my interest point.
   microgap := tvcur.tv_usec - tvprev.tv_usec;
   writeln('Slept for : ', inttostr(microgap), ' microseconds');

   // if Error occured during fpNanoSleep
   if ResultVal <> 0 then begin
      writeln('Remaining seconds     : ', Remaining.tv_sec);
      writeln('Remaining nanoseconds : ', Remaining.tv_nsec);
      exit;
   end;
end.