Hi all, I have a problem in which I try to count time with std::chrono’s duration class. I am trying to poll a button every 10 millisec. The problem is as if chrono.now() would only count every second!! That makes my polling very slow of course, but I don’t see what I am doing wrong?
In the following code, if (time_since_poll >= ms_between_polls)
only returns true when time_since_poll == 1000, I dont understand why!! std::chrono seems to count in seconds?? I then check at the values stored in last_poll and now and they can be for example 1746000000000 and 1747000000000
Can anyone help with this? Thanks!
#include <mbed.h>
#include <tact.h>
#define TACT_POLL_FREQ_HZ 100
#define NB_BUTTONS 2
#define BUTTON_ACTIVE_STATE 1
DigitalOut myLed(LED1);
DigitalIn buttons[2] = {DigitalIn(BUTTON1),
DigitalIn(PD_0) };
int buttonRead(int pin)
{
if (pin >= NB_BUTTONS) return !BUTTON_ACTIVE_STATE;
int rc = buttons[pin].read();
return rc;
}
// We declare tact objects pins as array offsets, not pins per sey
tact myTact = tact(0, buttonRead, TACT_POLL_FREQ_HZ, BUTTON_ACTIVE_STATE);
int main() {
myLed = 1;
float ms_between_polls = 10; // 1 sec / 100 Hz poll freq
std::chrono::_V2::system_clock::time_point last_poll =
std::chrono::high_resolution_clock::now();
while(1) {
std::chrono::_V2::system_clock::time_point now =
std::chrono::high_resolution_clock::now();
// This is my problem: I only get increments of 1000 milliseconds!
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_poll);
float time_since_poll = duration.count();
if (time_since_poll >= ms_between_polls)
{
myTact.poll([]{ myLed.write(0); },
[]{ myLed.write(1); },
[]{ });
last_poll = now;
}
}
}