Controlling a fan using a press button

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)

Thanks for the quick reply. I changed the input type for the button to INPUT_PULLUP. The code still runs but I am getting the same problem with it shutting itself off again, the weird part is the time is takes to shut itself down is random it seems. Always within 10 seconds though.

Delta_G:
Did you also change the wiring to match the new code?

I believe so, the button works to turn the fan on and off it just also has the problem of shutting itself off. At first I thought it was the physical button itself at fault because it seemed to turn off if the circuit was moved at all, however, the fan has never mysteriously turned itself on.

Delta_G:
How are you powering the fan? Can you post a quickie schematic or wiring diagram?

I will make an attempt! I dont know of any software that would have let me draw it out with the arduino and a bread board... sorry. Let me know if this helps you out at all.