can anybody assist me with a code? I am using arduino uno with adafruit v2 motor shield stacked on top. I am using a pushbutton and one DC motor and I want the state of the push button to change after it has been pushed for a few seconds. That is I want the motor to stop running even though the push button is still pushed down.

Here is the code I'm using:

This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM

For use with the Adafruit Motor Shield v2 
---->   http://www.adafruit.com/products/1438

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield(); 
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61); 

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 4;

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  // turn on motor


void loop() {
  uint8_t i;

    // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  delay(0);        // delay in between reads for stability

  if (buttonState==1){



 else if (buttonState==0){


  • stop thinking I want the state of the push button to change after it has been pushed for a few seconds ........ start thinking I want the state of a variable to change when the push button is pressed and I want the state of the variable to remain the same for a few seconds – jsotola Mar 23 '19 at 18:57

You need to do various things:

You need to change your logic not to use delay. Search on "Arduino Blink Without Delay" to find examples of doing timed actions with millis() instead of using delay.

Then you need to adjust your logic to start running the motor when the user presses a button, and stop running the motor when either the user releases the button or enough time elapses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.