Hello everyone,
I am attempting to make a small desktop fan and I seem to be having some trouble in my IF statements. The main problem I have right now is that a couple of seconds after turning the fan on with the button it will turn off again. Looking at the Serial monitor I see that at the reason for the fan shutting down is that the program somehow passes the if (buttoncounter % 2 == 0) statement. The plan is to get it working as a solid on off switch and then figure out adjustable speed for the motor, but for now it seems I am only able to have one or the other. Any ideas on what I have done wrong are appreciated, thanks!
const int buttonpin = 13;
const int FanPin = 11;
const int PotentPin = A0;
int buttonstate = 0;
int lastbuttonstate = 0;
int FanSpeed = 0;
int buttoncounter = 0;
void setup() {
Serial.begin(9600);
pinMode(buttonpin,INPUT);
pinMode(FanPin,OUTPUT);
}
void loop() {
int Potent = map(analogRead(PotentPin),0,1023,0,255);
int FanSpeed = Potent;
buttonstate = digitalRead(buttonpin);
if (buttonstate != lastbuttonstate){
if (buttonstate == HIGH){
analogWrite(FanPin,FanSpeed);
buttoncounter = buttoncounter + 1;
Serial.println("Fan On");
} else if (buttoncounter % 2 == 0) {
analogWrite(FanPin,0);
Serial.println("Fan Off");
}
Serial.println(buttonstate);
Serial.println(buttoncounter);
Serial.println(lastbuttonstate);
lastbuttonstate = buttonstate;
delay(50);
}
}
button_practice.ino (837 Bytes)