Debounce Push Button Motor Control

I'm a noob when it comes to programming. I'm trying to use a push button to turn on a dc motor and have it run for 5 sec and then turn itself off and not turn on again until the button is pushed again. Every time the button is pushed it only runs for 5 sec. I'm using a ATtiny85 that is programmed with an Arduino Nano as an ISP. I used Tinker Circuits and it worked perfectly with the code you see below, but when I actually made the circuit it was all over the place. After doing some research I learned you need to debounce the push button to get rid of the sporadic readings. I'm not sure how to incorporate that code into what I have already done though. Any help is greatly appreciated.

int PushButton = 0; // Pin 0 on ATtiny85
int MosfetOutput = 2; // Pin 2 on ATtiny85

int val = 0;
 void setup()

{
  pinMode(PushButton, INPUT);   //Push Button

  pinMode(MosfetOutput, OUTPUT);  //Output to Mosfet
}
  void loop ()
  {
    val = digitalRead(PushButton); // Push Button is currently wired to alway show it as High unless button is pressed.  Then it is read as low.
    if (val == LOW) 
    {
    digitalWrite(MosfetOutput, HIGH);
    delay (5000);                       // Runs Motor for 5 seconds
    }
    else
    {
      digitalWrite(MosfetOutput, LOW);  // Motor stays off until Push Button is pressed.
    }  
  }

Welcome to the forum.

Your code is debouncing the switch input by accident.

Debouncing is necessary because a mechanical switch will bounce and therefore create pulses on an input. Because microcontrollers are fast, they can detect these pulses e.g., when you read the pin often enough or use interrupts even if you press the button only once.

Because you use delay after activating the motor you stop reading the button and therefore the bounce will be ignored. But your code will also not do anything useful during that time.

Have a look at the following example, it will teach you how to control the timing parts of your code without using delay().

File -> Examples -> 02.Digital -> BlinkWithoutDelay

Your goal should be to ensure the loop() function is run as often as possible. This will first make your code slightly more complicated, but you will be able to extend it quite easy. For instance, you could not make your code react to two buttons and start two motors for 5 seconds with your style of code. But it will be easy to do for many buttons and motors using the example above.

"Tinker Circuits" You're hanging out on the wrong side of the tracks..

-jim lee

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.