Gradual Acceleration With Button Switch HELP!

I am trying to have a gradual acceleration when a button is pressed, I have been using the code:

//Pressing button 3
if (Button3State == HIGH){

bitSet(leds,4);
updateShiftRegister();
bitClear(leds,5);
updateShiftRegister();
bitSet(leds,6);
updateShiftRegister();
bitClear(leds,7);
updateShiftRegister();
for(int i = 70; i <= 120; i++){
analogWrite(PWM1, i);
analogWrite(PWM2, i);
delay(1500);
}

delay(10);
}

else{

bitClear(leds,4);
updateShiftRegister();
bitClear(leds,5);
updateShiftRegister();
bitClear(leds,6);
updateShiftRegister();
bitClear(leds,7);
updateShiftRegister();
analogWrite(PWM1,0);
analogWrite(PWM2,0);
}

This is with a use of a shift register and it is just turning pins on and off for a motor driver. The PWM are connected straight to the Arduino. When I press the button the motors will gradually move into the 120 value but when the button is released it stays on that for loop and does not stop.

Is there a way for it to exit this for loop after the button is released?

Is there a way for it to exit this for loop after the button is released?

Better not to use a for loop in the first place. Use the loop() function to do the looping for you and you can read and act on the button press/release thousands of time a second.

To do this you need to use millis() for timing as in the BlinkWithoutDelay example.

Save the millis() value at the time that the start action happens, such as setting the speed to a value. Then, each time through loop(), check whether the required wait period has elapsed by subtracting the start time from the millis() value now. If the period has elapsed then act accordingly and maybe save the start time for the next activity. If not, then go round loop() again, perhaps taking other actions and/or reading inputs, but don't block the free running of loop().

Using loop() instead of a for loop

speed = 0
startTime = millis()
accel = true

start of loop()
  if millis() - startTime >= period and accel is true
    write speed to motor
    increment speed
    if speed at max
      accel = false
    end if
    startTime = millis()
  end if
  read inputs etc and act on them if required
end of loop()

Are you talking about the void loop()?

I am talking about the loop() function. There is no such thing as the "void loop"

Hi,
Welcome to the forum.

Please read the first post in any forum entitled how to use this forum.
http://forum.arduino.cc/index.php/topic,148850.0.html then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Thanks.. Tom.. :slight_smile: