-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathdwt_delay.c
executable file
·72 lines (66 loc) · 2.03 KB
/
dwt_delay.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Simple microseconds delay routine, utilizing ARM's DWT
* (Data Watchpoint and Trace Unit) and HAL library.
* Intended to use with gcc compiler, but I hope it can be used
* with any other C compiler across the Universe (provided that
* ARM and CMSIS already invented) :)
* Max K
*
*
* This file is part of DWT_Delay package.
* DWT_Delay is free software: you can redistribute it and/or modify it
* under the terms of the MIT License
*/
#include "stm32f1xx_hal.h" // change to whatever MCU or Cortex-M core you use
#include "dwt_delay.h"
/**
* Initialization routine.
* You might need to enable access to DWT registers on Cortex-M7
* DWT->LAR = 0xC5ACCE55
*/
void DWT_Init(void)
{
if (!(CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk)) {
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
DWT->CYCCNT = 0;
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
}
}
#if DWT_DELAY_NEWBIE
/**
* If you are a newbie and see magic in DWT_Delay, consider this more
* illustrative function, where you explicitly determine a counter
* value when delay should stop while keeping things in bounds of uint32.
*
* @param uint32_t us Number of microseconds to delay for
*/
void DWT_Delay(uint32_t us)
{
uint32_t startTick = DWT->CYCCNT,
targetTick = DWT->CYCCNT + us * (SystemCoreClock/1000000);
// Must check if target tick is out of bounds and overflowed
if (targetTick > startTick) {
// Not overflowed
while (DWT->CYCCNT < targetTick);
} else {
// Overflowed
while (DWT->CYCCNT > startTick || DWT->CYCCNT < targetTick);
}
}
#else
/**
* Delay routine itself.
* Time is in microseconds (1/1000000th of a second), not to be
* confused with millisecond (1/1000th).
*
* No need to check an overflow. Let it just tick :)
*
* @param uint32_t us Number of microseconds to delay for
*/
void DWT_Delay(uint32_t us)
{
uint32_t startTick = DWT->CYCCNT,
delayTicks = us * (SystemCoreClock/1000000);
while (DWT->CYCCNT - startTick < delayTicks);
}
#endif