esp32C3按键控制灯光开关
时间: 2025-02-21 09:12:46 浏览: 114
### 实现 ESP32-C3 通过按键控制灯光开关
为了实现 ESP32-C3 通过按键控制灯光开关的功能,可以参考如下方法。这里假设使用一个外部按钮连接到 GPIO9,并且 LED 连接到另一个 GPIO 口(例如 GPIO5)。当按下按钮时,LED 将被点亮;再次按下则熄灭。
#### 硬件连接说明
- 按钮的一端连接至 GPIO9,另一端接地。
- 使用上拉电阻确保未按压状态下输入高电平。
- LED 正极接 GPIO5 并串联限流电阻后接入电源正极。
- LED 负极直接接地。
#### 示例代码
下面提供了一个简单的 Arduino IDE 下运行的程序来完成上述功能:
```cpp
const int buttonPin = 9; // the number of the pushbutton pin
const int ledPin = 5; // the number of the LED pin
// Variables will change:
int ledState = LOW; // the current state of the output pin
int lastButtonState = LOW; // the previous reading from the input pin
int currentButtonState = LOW; // the current reading from the input pin
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // Initialize the pushbutton pin as an input with internal pull-up resistor.
pinMode(ledPin, OUTPUT); // Initialize the digital pin as an output.
}
void loop() {
currentButtonState = digitalRead(buttonPin);
if (currentButtonState != lastButtonState) { // Check for changes on the button pin
if (currentButtonState == HIGH) {
ledState = !ledState; // Toggle the LED state when pressed
}
digitalWrite(ledPin, ledState);
}
lastButtonState = currentButtonState;
}
```
此段代码实现了基本的按键触发翻转逻辑[^1]。每当检测到按钮状态改变时就会切换一次灯的状态。注意这里的 `INPUT_PULLUP` 设置是为了利用内部上拉电阻简化电路设计。
阅读全文
相关推荐

















