Need function to return elapsed microseconds

Share code examples or discuss embedded software, including device drivers, interrupt handlers, middleware and application code.

Moderators: Markus Girdland, Mattias Norlander

jjuni
Posts: 6
Joined: Wed Sep 27, 2017 3:29 pm

Need function to return elapsed microseconds

Postby jjuni » Wed Sep 27, 2017 6:41 pm

I need a function I can call repeatedly to get a value of elapsed microseconds so I can trigger various actions after various intervals have elapsed. Ideally, this would be functionally equivalent to the Arduino IDE's microseconds() function which returns the number of microseconds since system startup.

I am working with STM32F0 on Nucleo-64 board.

Can anyone help?

frank_ee
Posts: 55
Joined: Wed Apr 05, 2017 5:08 pm
Location: USA

Re: Need function to return elapsed microseconds

Postby frank_ee » Wed Oct 04, 2017 5:32 pm

Hello,

If your not using an RTOS which has these functions available, you can setup a timer with a frequency of 1MHz which has a counter resolution of 1us/bit. The function can read the timer channel counter value and return it. It will not be the exact value elapsed due to the function call overhead, but close. You have to take into consideration if the timer counter overflowed. I can post some example code if needed.

jjuni
Posts: 6
Joined: Wed Sep 27, 2017 3:29 pm

Re: Need function to return elapsed microseconds

Postby jjuni » Wed Oct 11, 2017 3:00 pm

Thank you frank_ee! I was able to get things working by having SysTick call a short routine that updates a global variable each time. I was able to get this to update every 2 microseconds, which is precise enough for my current application. Your approach is better, though, and more broadly applicable.

Thank you!

frank_ee
Posts: 55
Joined: Wed Apr 05, 2017 5:08 pm
Location: USA

Re: Need function to return elapsed microseconds

Postby frank_ee » Wed Oct 11, 2017 6:17 pm

Hello,

Glad you have it working. Did you check the delay using an oscilloscope by toggling an output port?

jjuni
Posts: 6
Joined: Wed Sep 27, 2017 3:29 pm

Re: Need function to return elapsed microseconds

Postby jjuni » Wed Oct 11, 2017 8:55 pm

Yes! It seems to be correct.


Return to “Embedded target code development discussions”

Who is online

Users browsing this forum: No registered users and 1 guest