I am controlling an instrument using C++.
I am trying to create instrument dwell periods that are consistent so the resulting data reads are more consistent. I am attempting to define a sleep function that uses a while loop to hold up the program for a certain amount of time.
My issue is the dwell times are inconsistent.
#include <stdio.h>
#include <tchar.h>
#include <chrono>
#include <thread>
#include <ctime>
using namespace std;
#include <windows.h>
void Dwell(float seconds){
clock_t startClock = clock();
float secondsAhead = seconds * CLOCKS_PER_SEC;
// do nothing until the elapsed time has passed.
while(clock() < startClock+secondsAhead);
return;
}
//I then use chrono to time the dwell
int main()
{
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::milliseconds;
auto t1 =high_resolution_clock::now();
Dwell(1);
auto t2 =high_resolution_clock::now();
auto ms_int = duration_cast<milliseconds>(t2-t1);
duration<double, std::milli> ms_double = t2-t1;`
I keep getting less than the time I put into my function Dwell. I call Dwell expecting a wait time of 1 second, but I get varying results, all less than 1 second, e.g. 800 ms, 759 ms, 912 ms, etc. I am hoping to get accurate and consistent dwell times within 100 us of the requested dwell time.