功能:用一个小的四角蜘蛛按钮开关,控制一个小灯泡得明暗,按下熄灭 放开就是亮
实拍电路
接线图
代码:
//定义作用灯光引脚
int lightFoot = 12;
int OpenFoot = 8;
void setup() {
//初始化数字引脚LED_BUILTIN作为输出。
Serial.begin(9600); //初始化串口通讯
pinMode(lightFoot, OUTPUT);
pinMode(OpenFoot, INPUT);
}
// the loop function runs over and over again forever
void loop() {
int openNow = digitalRead(OpenFoot); //显示按键状态
Serial.println(openNow); //打印按键状态
delay(10);
if (openNow) {
digitalWrite(lightFoot, LOW);
} else {
digitalWrite(lightFoot, HIGH);
}
// digitalWrite(lightFoot, HIGH); // 定义得12好引脚高电平点亮
// delay(5000); // 延迟500毫秒
// digitalWrite(lightFoot, LOW); // 定义得12好引脚低电平熄灭
// delay(1000); //延迟500毫秒
}
一样得电路 通过时间戳写浅按下开灯 长按关灯
//定义作用灯光引脚
int lightFoot = 12;
int OpenFoot = 8;
int buttonState = 0; // 按钮的当前状态
int lastButtonState = 0; // 按钮的先前状态
int startPressed = 0; // 按下按钮的那一刻
int endPressed = 0; // 松开按钮的那一刻
int holdTime = 0; // 按钮按住了多长时间
int idleTime = 0; // 按钮闲置了多长时间
class btn {
public:
int now = 2;
};
btn a; //实例化一下
void setup() {
//初始化数字引脚LED_BUILTIN作为输出。
Serial.begin(9600); //初始化串口通讯
pinMode(lightFoot, OUTPUT);
pinMode(OpenFoot, INPUT);
}
// the loop function runs over and over again forever
void loop() {
buttonState = digitalRead(OpenFoot); //读取脚位显示状态显示按键状态
Serial.println(buttonState);
delay(500);
if (buttonState != lastButtonState) { // button state changed
updateState();
}
lastButtonState = buttonState;
// int openNow = digitalRead(OpenFoot); //显示按键状态
// Serial.println(openNow); //打印按键状态
delay(1000);
// if (openNow) {
// digitalWrite(lightFoot, HIGH);
// } else {
// digitalWrite(lightFoot, LOW);
// }
// digitalWrite(lightFoot, HIGH); // 定义得12好引脚高电平点亮
// delay(5000); // 延迟500毫秒
// digitalWrite(lightFoot, LOW); // 定义得12好引脚低电平熄灭
// delay(1000); //延迟500毫秒
}
void updateState() {
// the button has been just pressed
if (buttonState == HIGH) {
startPressed = millis();
idleTime = startPressed - endPressed;
digitalWrite(lightFoot, HIGH);
if (idleTime >= 500 && idleTime < 1000) {
Serial.println("按钮闲置了半秒钟");
}
if (idleTime >= 1000) {
Serial.println("按钮空闲一秒钟或更长时间");
// 定义得12好引脚低电平熄灭
}
// the button has been just released
} else {
endPressed = millis();
holdTime = endPressed - startPressed;
if (holdTime >= 1000) {
digitalWrite(lightFoot, LOW); // 定义得12好引脚低电平熄灭
Serial.println("按钮被按住一秒钟或更长时间");
}
}
};
|