0

How can I create a function that can control a DC motor's speed and direction?

configMotor(int speed, direction){
   pwmVal = speed;

   //need help with code for picking direction
}

//move FORWARD
void moveForward(){
  analogWrite(pwn, pwmVal);
  delay(sDelay);
  digitalWrite(ina, HIGH);
  digitalWrite(inb, LOW);
}

//move BACKWARD
void moveBackward(){
  analogWrite(pwn, pwmVal);
  delay(sDelay);
  digitalWrite(ina, LOW);
  digitalWrite(inb, HIGH);
}

I don't know what to write in the code for configMotor function so that it can choose going forward or backward.

1 Answer 1

0

All you need to do is pass a parameter to config that says forward or backwards (was direction). This parameter then sets the values of that the pins INA/B will be set to, because they are opposite.

Does that make sense? If not add a comment with you question and I'll try and clarify.

int inaDirection = LOW;
int inbDirection = LOW;

void configMotor( int speed, bool forwards = true)
{
   pwmVal = speed;
   inaDirection = forwards?HIGH:LOW;   // ? and : are the same as an if statement, just more compact.
   inbDirection = forwards?LOW:HIGH;
}

// move no need for forward and reverse anymore
void move()
{
    analogWrite(pwn, pwmVal);
    delay(sDelay);
    digitalWrite(ina, inaDirection);
    digitalWrite(inb, inbDirection);
}
2
  • why is bool forwards set to equal to true in the parameter declaration?
    – BOB123
    Oct 26, 2017 at 16:54
  • bool forwards = true means by default the function should go forwards. You can call configMotor(40); or configMotor(40, true);` they both mean the same thing, where as configMotor(40, false); means go backwards. I added the default value to make it clearer to you that true meant forwards, I guess it didn't work :) Oct 27, 2017 at 7:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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