int reading;
int btn_state;
int last_btn_state=LOW;
unsigned long last_debounce_time=0;
int brightness=0;
int fade_amount=5;
void setup()
{
Serial.begin(9600);
pinMode(2,INPUT);
pinMode(3,OUTPUT);
}
void loop()
{
reading=digitalRead(2);
if(reading !=last_btn_state)
{
last_debounce_time=millis();
}
if((millis()-last_debounce_time)>50)
{
if(reading != btn_state)
{
btn_state=reading;
if(btn_state==LOW)
{
chg_brightness();
}
else
{
if((millis()-last_debounce_time)>1000)
{
if(btn_state==LOW)chg_brightness();
}
}
}
}
last_btn_state=reading;
}
void chg_brightness()
{
brightness=brightness+fade_amount;
if(brightness>255) brightness=255;
if(brightness<0) brightness=0;
if(brightness==0 || brightness==255) fade_amount=-fade_amount;
analogWrite(3,brightness);
Serial.println(brightness);
delay(30);
}
沒有留言:
張貼留言