0

I use this code to turn on/off a small 5v dc motor. How can I modify it so that the arduino writes the potentiometer value to the motor when it is in ON state ?

int speed = analogRead(pot) / 4;
ButtonState = !digitalRead(Switch);

if (ButtonState != lastButtonState)
{ 
     if (ButtonState == 1) 
     {
         if (motorstate == 1) 
         {
             motorstate = 0;
         } 
         else
         {
             motorstate = 1; 
         }
     } 
     lastButtonState = ButtonState; 
}

digitalWrite(enable, motorstate);
delay(20);
  • It depends on whether enable is a pin capable of PWM or analogWrite(enable,speed). – Dave X Apr 18 at 15:55
  • yes it is. i tried removing the last output statement and replaced it with ``` if (motorstate == 1) analogWrite ( enable , speed ); ``` but it doesnt work. – Medhat Hamed Apr 18 at 16:04
1

(this is not an answer, but just a comment, used to use code alignment).

This sketch (which I aligned in your code) can be rewritten to

int speed = analogRead(pot) / 4;
ButtonState = !digitalRead(Switch);

if (ButtonState != lastButtonState)
{ 
     if (ButtonState == 1) 
     {
         motorstate = (motorstate == 1 ? 0 : 1);
     } 

     lastButtonState = ButtonState; 
}

digitalWrite(enable, motorstate);
delay(20);

I suggest the best way to proceed is to add print statements and use the serial monitor to check what values you get and see what you expect (which is not fully clear).

  • 2
    oh i just figured it out :D i used this statement analogWrite ( enable , motorstate*speed) – Medhat Hamed Apr 18 at 17:03

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.