我试图通过将变量e设置为1或0来将按钮转换为开关,具体取决于引脚12返回的是HIGH还是LOW,但是一次按下按钮后,LED会亮起并且不会不管我再按几次按钮都关闭。
#define boton 12
#define gled 7
#define rled 4
#define yled 8
int e=0;
int botonst=LOW;
void setup() {
// put your setup code here, to run once:
pinMode(boton,INPUT);
pinMode(gled,OUTPUT);
pinMode(rled,OUTPUT);
pinMode(yled,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
botonst=digitalRead(boton);
if ((botonst==HIGH) && (e=1)){
digitalWrite(yled,HIGH);
e=0;
}
else{
if(e=0){
digitalWrite(yled,LOW);
e=1;
}
}
delay(50);
}
```C
答案 0 :(得分:0)
您的逻辑不清楚!但是我想您有按钮和指示灯,并且如果您尝试执行此操作,则每次单击按钮时都尝试切换按钮..然后使用此代码
#define boton 12 // button conect on pin 12
#define yled 8 // led conect on pin 8
bool ledMode = false; // this mode use to save the current led state ( high or low )
int botonst=LOW;
void setup() {
pinMode(boton,INPUT); // make button as input pin
pinMode(yled,OUTPUT); // make led as output pin
}
void loop() {
botonst=digitalRead(boton); // read the button state
if (botonst==HIGH){ // if button is clicked (assume you connect the button as active high)
ledMode ^= true; // toggle the mode (if it true make it false and if it false make it ture)
if(ledMode == false) //if led mod is off
digitalWrite(yled,HIGH); // turn led on
else // if led mode is on
digitalWrite(yled,LOW); // turn led off
}
delay(200); //delay for Depounceing (if you use hardware Depounce technique remove it)
}