// delay for given number of microseconds void sys_tick_udelay(uint32_t usec) { if (query_irq() == IRQ_STATE_ENABLED) { // IRQs enabled, so can use systick counter to do the delay uint32_t start = sys_tick_get_microseconds(); while (sys_tick_get_microseconds() - start < usec) { } } else { // IRQs disabled, so need to use a busy loop for the delay // sys freq is always a multiple of 2MHz, so division here won't lose precision const uint32_t ucount = HAL_RCC_GetSysClockFreq() / 2000000 * usec / 2; for (uint32_t count = 0; ++count <= ucount;) { } } }
STATIC mp_obj_t time_ticks_us(void) { // We want to "cast" the 32 bit unsigned into a 30-bit small-int return MP_OBJ_NEW_SMALL_INT(sys_tick_get_microseconds() & MP_SMALL_INT_POSITIVE_MASK); }
/// \function elapsed_micros(start) /// Returns the number of microseconds which have elapsed since `start`. /// /// This function takes care of counter wrap, and always returns a positive /// number. This means it can be used to measure periods upto about 17.8 minutes. /// /// Example: /// start = pyb.micros() /// while pyb.elapsed_micros(start) < 1000: /// # Perform some operation STATIC mp_obj_t pyb_elapsed_micros(mp_obj_t start) { uint32_t startMicros = mp_obj_get_int(start); uint32_t currMicros = sys_tick_get_microseconds(); return MP_OBJ_NEW_SMALL_INT((currMicros - startMicros) & 0x3fffffff); }
/// \function micros() /// Returns the number of microseconds since the board was last reset. /// /// The result is always a micropython smallint (31-bit signed number), so /// after 2^30 microseconds (about 17.8 minutes) this will start to return /// negative numbers. STATIC mp_obj_t pyb_micros(void) { // We want to "cast" the 32 bit unsigned into a small-int. This means // copying the MSB down 1 bit (extending the sign down), which is // equivalent to just using the MP_OBJ_NEW_SMALL_INT macro. return MP_OBJ_NEW_SMALL_INT(sys_tick_get_microseconds()); }
STATIC mp_obj_t time_ticks_us(void) { return MP_OBJ_NEW_SMALL_INT(sys_tick_get_microseconds() & MP_SMALL_INT_POSITIVE_MASK); }