Trying to use std::chrono on Mbed with STM32

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 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
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 =
  while(1) {
    std::chrono::_V2::system_clock::time_point 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;

Maybe the integration to std::chrono is not good in mbedos. As a substitute for


can you use


instead as a sanity check? See docs

1 Like

I think it wasnt good as you mentioned. I solved it by using their deprecated timer class. I am done with this so I can’t test Kernel::get_ms_count(); but if anyone is interested it may work too!

this is what I did in the meantime

Timer myTimer;
int main()
  while(1) {
    if ((*1000) >= 10) { // ervery 10 millisec
      // do something