DC Motor control

Hi everybody,

I am new to Arduino programming, but have done many of the examples.
My project i quite simple but i have a few issues which i could use some guidance/help to solve.
I try to make a setup where a Pushbutton by activation ramp up a DC motor, which run at full speed until a microswitch i activated, then the motor ramps down and the system should now be ready for a new Pushbutton activation.

In the attached code this is kind of working but:

  • If Pushbutton is kept activated, the ramp up continuous to run (0->255, 0->255…)
  • The same goes for the ramp down, the motor stop at microswitch activation, but if microswitch is kept activated the motor ramp down (255->0, 255->0…)

The microswitch is used as a positionswitch, meaning that it will be high at starting point.
The LED is not used at this point.

My code:

int PushButton = 8;
int PositionSwitch =12;
int Motor = 3;
int LED = 5;

void setup() {

pinMode(PushButton, INPUT);
pinMode(PositionSwitch, INPUT);
pinMode(Motor, OUTPUT);
pinMode(LED, OUTPUT);

void loop() {

// Read state of PushButton
while(digitalRead(PushButton) == HIGH)

// Ramp up Motor speed
for(int x = 40; x <= 255; x++)
{analogWrite(Motor, x);

if(digitalRead(PositionSwitch) ==HIGH)

// Ramp down Motor speed
for(int x = 255; x >= 0; x–)
{analogWrite(Motor, x);


Best Regards

In general do not mix up the button reading with other parts of the code as you are doing in

 while(digitalRead(PushButton) == HIGH)

At the top of loop() check the states of the buttons and save the values in variables.

Then use those values to make decisions. Have a look at Planning and Implementing a Program

You probably also need to detect when the switch changes from not-pressed to pressed rather than detect the fact that it is pressed. Look at the state-change detection example that comes with the Arduino IDE


Thanks Robin,
I will take a look at your suggestions.