arduino esp32-c3定时器在按下开关键后才开始计数代码
时间: 2023-12-27 16:03:00 浏览: 115
你好,关于你的问题,可以参考以下代码:
```
#include <Arduino.h>
int switchPin = 2; // 开关键所连接的引脚
volatile int count = 0; // 定时器计数器,注意要加volatile
hw_timer_t *timer = NULL; // 定时器对象指针
void IRAM_ATTR onTimer(){
count++; // 定时器中断触发时计数器加1
}
void setup(){
pinMode(switchPin, INPUT_PULLUP); // 设置开关键为输入模式并开启上拉电阻
Serial.begin(9600); // 初始化串口通信
timer = timerBegin(0, 80, true); // 初始化定时器,参数分别为定时器编号、分频系数、是否自动重载
timerAttachInterrupt(timer, &onTimer, true); // 绑定定时器中断函数
}
void loop(){
if(digitalRead(switchPin) == LOW){ // 检测开关键是否按下
count = 0; // 如果按下,则将计数器清零
timerAlarmWrite(timer, 1000000, true); // 设置定时器周期为1秒
timerAlarmEnable(timer); // 开启定时器
}
if(count > 0){ // 如果计数器不为0,则说明定时器已经开始计数
Serial.println(count); // 输出计数器的值
}
}
```
希望能对你有所帮助。如果有更多问题,请继续提问。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)