|
| 1 | +/* |
| 2 | + Repeat timer example |
| 3 | +
|
| 4 | + This example shows how to use hardware timer in ESP32. The timer calls onTimer |
| 5 | + function every second. The timer can be stopped with button attached to PIN 0 |
| 6 | + (IO0). |
| 7 | +
|
| 8 | + This example code is in the public domain. |
| 9 | + */ |
| 10 | + |
| 11 | +// Stop button is attached to PIN 0 (IO0) |
| 12 | +#define BTN_STOP_ALARM 0 |
| 13 | + |
| 14 | +hw_timer_t * timer = NULL; |
| 15 | + |
| 16 | +void onTimer(){ |
| 17 | + static unsigned int counter = 1; |
| 18 | + |
| 19 | + Serial.print("onTimer no. "); |
| 20 | + Serial.print(counter); |
| 21 | + Serial.print(" at "); |
| 22 | + Serial.print(millis()); |
| 23 | + Serial.println(" ms"); |
| 24 | + |
| 25 | + counter++; |
| 26 | +} |
| 27 | + |
| 28 | +void setup() { |
| 29 | + Serial.begin(115200); |
| 30 | + |
| 31 | + // Set BTN_STOP_ALARM to input mode |
| 32 | + pinMode(BTN_STOP_ALARM, INPUT); |
| 33 | + |
| 34 | + // Use 1st timer of 4 (counted from zero). |
| 35 | + // Set 80 divider for prescaler (see ESP32 Technical Reference Manual for more |
| 36 | + // info). |
| 37 | + timer = timerBegin(0, 80, true); |
| 38 | + |
| 39 | + // Attach onTimer function to our timer. |
| 40 | + timerAttachInterrupt(timer, &onTimer, true); |
| 41 | + |
| 42 | + // Set alarm to call onTimer function every second (value in microseconds). |
| 43 | + // Repeat the alarm (third parameter) |
| 44 | + timerAlarmWrite(timer, 1000000, true); |
| 45 | + |
| 46 | + // Start an alarm |
| 47 | + timerAlarmEnable(timer); |
| 48 | +} |
| 49 | + |
| 50 | +void loop() { |
| 51 | + // If button is pressed |
| 52 | + if (digitalRead(BTN_STOP_ALARM) == LOW) { |
| 53 | + // If timer is still running |
| 54 | + if (timer) { |
| 55 | + // Stop and free timer |
| 56 | + timerEnd(timer); |
| 57 | + timer = NULL; |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments