Hi there,
I am still trying to figure out the best way to do this: I have some led (pin9) being dimmed by a button (pin4) and a cooling fan(pin 10) which needs to be on when the leds are on, and also to STAY on for some seconds when the leds are switched off.
I am using boolean debounce and millis, but for some odd reason this only works the first time that I run it on the arduino, if I press the button again the fan doesn't switch on until the leds are off.. pretty confusing. Stupid mistake?
//Milano 0.1
int buttonPin = 4;
int ledPin = 9;
int fanPin = 10;
boolean lastButton = LOW;
boolean currentButton = LOW;
int ledpwmLevel = 0;
int lastLEDtime = 0;
boolean fanOn = false;
void setup()
{
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(fanPin, OUTPUT);
Serial.begin(9600);
}
boolean debounce(boolean last)
{
boolean current = digitalRead(buttonPin);
if (last != current)
{
delay(5);
current = digitalRead(buttonPin);
}
return current;
}
void loop()
{
currentButton = debounce(lastButton);
if (lastButton == LOW && currentButton == HIGH)
{
fanOn = true;
analogWrite(fanPin, 255);
ledpwmLevel = ledpwmLevel + 85;
Serial.println("BUTTON");
}
if (ledpwmLevel > 255)
{
ledpwmLevel = 0;
lastLEDtime = millis();
}
analogWrite(ledPin, ledpwmLevel);
if (fanOn && millis() - lastLEDtime > 5000)
{
fanOn = false;
analogWrite(fanPin, 0);
}
lastButton = currentButton;
}