PWM sketch to control motors?


Im trying to control 2 DC motors via a motor driver and arduino mega, but it just hasnt worked. The motor driver has 2 digital inputs for each motor and a PWM input as well.

Could someone please have a look at the code and see if it is correct? Thanks very much.

This is the main post, if anyone wants to refer to the connection diagram >

int motor1Input1 = 4 ;       // Motor1 inputs connected to pin 4 & 2
int motor1Input2 = 2;
int motor1Pwm= 9;       // Motor1 PWM pin
int motor2Input1= 7;       // Motor2 inputs connected to pin 7 & 5
int motor2Input2= 5;
int motor2Pwm= 11;       // Motor2 PWM pin
int ledPin = 13;       // LED on pin 13

void setup()                    
  pinMode(motor1Input1, OUTPUT);      // sets all pins as output
  pinMode(motor1Input2, OUTPUT);
  pinMode(motor2Input1, OUTPUT);
  pinMode(motor2Input2, OUTPUT);
  pinMode(ledPin, OUTPUT);
//  pinMode(motor2Pwm, OUTPUT); > Disabled this line as analogWrite doesnt need pinMode to be defined
//  pinMode(motor1Pwm, OUTPUT); > Same as above


void loop()
  digitalWrite(motor1Input1, HIGH);   // Motor1 on
  analogWrite(motor1Pwm,255);  // Motor1 PWM Pulse

  digitalWrite(motor2Input1, HIGH);   // Motor2 on
  analogWrite(motor2Pwm,255);  // Motor2 PWM Pulse
  digitalWrite(ledPin,HIGH); // LED test  

but it just hasnt worked.

In what way hasn't it worked?

 digitalWrite(motor2Input1, HIGH);   // Motor1 on


I meant that after i upload the sketch, the motors dont turn. The led lights up, but the motors just sit there and do nothing.

Sorry bout the comment, it should have been '// Motor2 on' . I've modified it now.

If the LED lights, it seems likely that the problem is a hardware one, not software.

If you set the PWM to a lower ratio, say 50%, you could check that you're getting PWM correctly by attaching an old earphone to the PWM pin and listening for a tone. (that's assuming you don't have an oscilloscope!)

Ok, I'll try the lowering the ratio. Would this be correct to get it at 50%?

 analogWrite(motor1Pwm, 127);

Also, is the whole sketch correct? ie, should the motors turn if upload this sketch, assuming that all connections are right and there is no hardware fault?

Thanks very much

Yes, 127 is fine. Probably any value within about 10% of the end-stops would allow you to hear a tone.

The rest of the sketch looks to me to be OK.

You should be able to simulate the sketch just using jumper wires to the controller, with 5V for a high or 100% PWM, and GND for low. Disconnect the Arduino first.

If the motor doesn't move then, then the controller is possibly faulty.

Ok, thanks for the suggestions.

I got it to work finally. It was a faulty capacitor (noise suppresion) that caused all the problems!