本帖最后由 Young.W 于 2022-2-8 16:53 编辑
1. 按键点亮led
2.在过了一段时间后熄灭(1s);
3.在两秒内按键就会点亮红的不点就另外一个绿的亮.
我感觉我的逻辑出了点问题.但是看不出来在哪里. 十分感谢.大神们帮忙看下指点一下!!
const int ledPinRed = 12;
const int ledPinGreen =13;
const int pushbutton =10;
const unsigned long randomtime =1000;//随便舍得一个随机时间
unsigned long previousLedGreen=0;//记录之前的时间
unsigned long previousButton=0;
unsigned long threfold=2000;//在2s内按键点亮
int buttonState = 0;
int ledGreenstate=HIGH;
void setup()
{
pinMode(ledPinRed, OUTPUT);
pinMode(ledPinGreen, OUTPUT);
pinMode(pushbutton, INPUT);
digitalWrite(ledPinGreen, ledGreenstate);
Serial.begin(9600);
}
void loop()
{
buttonState = digitalRead(pushbutton);
unsigned long currenttime = millis();
if (buttonState == HIGH) //如果按键就会亮
{
digitalWrite(ledPinGreen, HIGH);
previousButton=currenttime;
}
if(ledGreenstate==HIGH){
if (currenttime - previousButton>=randomtime)//过了一段时间熄灭
{
digitalWrite(ledPinGreen, LOW);
previousLedGreen=currenttime;
}
}
if(ledPinGreen==LOW){
if(currenttime-previousLedGreen>=threfold&&buttonState == HIGH )//如果在时间内按键灯就会亮
{
digitalWrite(ledPinRed, HIGH);
digitalWrite(ledPinGreen, LOW);
}
else{
digitalWrite(ledPinGreen, HIGH);//不按就另一个亮
}
}
}
|