APM:Libraries
hrt.c
Go to the documentation of this file.
1 /*
2  * Copyright (C) Siddharth Bharat Purohit 2017
3  * This file is free software: you can redistribute it and/or modify it
4  * under the terms of the GNU General Public License as published by the
5  * Free Software Foundation, either version 3 of the License, or
6  * (at your option) any later version.
7  *
8  * This file is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11  * See the GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program. If not, see <http://www.gnu.org/licenses/>.
15  */
16 // High Resolution Timer
17 
18 #include "ch.h"
19 #include "hal.h"
20 #include "hrt.h"
21 #include <stdint.h>
22 
23 static uint64_t timer_base = 0;
24 
25 uint64_t hrt_micros()
26 {
27  static volatile uint64_t last_micros;
28 
29  /*
30  use chSysGetStatusAndLockX() to prevent an interrupt while
31  allowing this call from any context
32  */
33  syssts_t sts = chSysGetStatusAndLockX();
34  uint64_t micros;
35  micros = timer_base + (uint64_t)chVTGetSystemTimeX();
36  // we are doing this to avoid an additional interupt routing
37  // since we are definitely going to get called atleast once in
38  // a full timer period
39  if (last_micros > micros) {
40  const uint64_t step = ST2US(1ULL<<CH_CFG_ST_RESOLUTION);
41  timer_base += step;
42  micros += step;
43  }
44  last_micros = micros;
45  chSysRestoreStatusX(sts);
46  return micros;
47 }
static uint64_t timer_base
Definition: hrt.c:23
#define CH_CFG_ST_RESOLUTION
System time counter resolution.
Definition: chconf.h:47
uint64_t hrt_micros()
Definition: hrt.c:25
uint32_t micros()
Definition: system.cpp:152