目前只能实现灯灭的时候按住按钮改亮度,但是无法实现灯亮着的时候按住按钮改亮度,帮忙看下代码怎么改。
int led = 11; //LED-->11
int button = 7; //button-->7
int val = 0; int old_val = 0;
int state = 0; //Switch HIGH/LOW
int brightness = 128; //PWM
void setup() {
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop() {
val = digitalRead(button); //读取按钮状态
if ((val == HIGH) && (old_val == LOW)) { //如果按下一次立马弹起
state = 1 - state; //状态改变
delay(150);
}
if ((val == HIGH) && (old_val == HIGH)) { //如果一直按住,改变亮度
delay(10);
brightness ++;
delay(5);
if (brightness > 225) brightness = 0;
}
if (state == 1){
analogWrite(led,brightness);
}else{
digitalWrite(led,LOW);
}
old_val = val;
}
int led = 11; //LED-->11
int button = 7; //button-->7
int val = 0; int old_val = 0;
int state = 0; //Switch HIGH/LOW
int brightness = 128; //PWM
void setup() {
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop() {
val = digitalRead(button); //读取按钮状态
if ((val == HIGH) && (old_val == LOW)) { //如果按下一次立马弹起
state = 1 - state; //状态改变
delay(150);
}
if ((val == HIGH) && (old_val == HIGH)) { //如果一直按住,改变亮度
delay(10);
brightness ++;
delay(5);
if (brightness > 225) brightness = 0;
}
if (state == 1){
analogWrite(led,brightness);
}else{
digitalWrite(led,LOW);
}
old_val = val;
}