12
12
#define BTN_STOP_ALARM 0
13
13
14
14
hw_timer_t * timer = NULL ;
15
+ volatile SemaphoreHandle_t timerSemaphore;
16
+ portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
15
17
16
- void onTimer (){
17
- static unsigned int counter = 1 ;
18
+ volatile uint32_t isrCounter = 0 ;
19
+ volatile uint32_t lastIsrAt = 0 ;
18
20
19
- Serial.print (" onTimer no. " );
20
- Serial.print (counter);
21
- Serial.print (" at " );
22
- Serial.print (millis ());
23
- Serial.println (" ms" );
24
-
25
- counter++;
21
+ void IRAM_ATTR onTimer (){
22
+ // Increment the counter and set the time of ISR
23
+ portENTER_CRITICAL_ISR (&timerMux);
24
+ isrCounter++;
25
+ lastIsrAt = millis ();
26
+ portEXIT_CRITICAL_ISR (&timerMux);
27
+ // Give a semaphore that we can check in the loop
28
+ xSemaphoreGiveFromISR (timerSemaphore, NULL );
29
+ // It is safe to use digitalRead/Write here if you want to toggle an output
26
30
}
27
31
28
32
void setup () {
@@ -31,6 +35,9 @@ void setup() {
31
35
// Set BTN_STOP_ALARM to input mode
32
36
pinMode (BTN_STOP_ALARM, INPUT);
33
37
38
+ // Create semaphore to inform us when the timer has fired
39
+ timerSemaphore = xSemaphoreCreateBinary ();
40
+
34
41
// Use 1st timer of 4 (counted from zero).
35
42
// Set 80 divider for prescaler (see ESP32 Technical Reference Manual for more
36
43
// info).
@@ -48,6 +55,21 @@ void setup() {
48
55
}
49
56
50
57
void loop () {
58
+ // If Timer has fired
59
+ if (xSemaphoreTake (timerSemaphore, 0 ) == pdTRUE){
60
+ uint32_t isrCount = 0 , isrTime = 0 ;
61
+ // Read the interrupt count and time
62
+ portENTER_CRITICAL (&timerMux);
63
+ isrCount = isrCounter;
64
+ isrTime = lastIsrAt;
65
+ portEXIT_CRITICAL (&timerMux);
66
+ // Print it
67
+ Serial.print (" onTimer no. " );
68
+ Serial.print (isrCount);
69
+ Serial.print (" at " );
70
+ Serial.print (isrTime);
71
+ Serial.println (" ms" );
72
+ }
51
73
// If button is pressed
52
74
if (digitalRead (BTN_STOP_ALARM) == LOW) {
53
75
// If timer is still running
0 commit comments