Author Options:

Using an Arduino's PWM to control a DC motor hooked up to a SainSmart L298N board? Answered

Hi Instructables!

I am new to making electronics, completely. So please let me know if I am doing anything wrong.

I am working on making a UGV rover based on an Arduino UNO R3 and accompanied by a SainSmart L298N Module (to drive 2 DC motors).

I am capable of getting the DC motor to work in either direction but don't know how to control its speed.

pins 5 and 6 are either high or low (always opposite) to control direction, pin 11 enables the motor.
The board is powered by the Arduino's 5v power supply.

Here is my setup (it's just really basic so far):

void setup(){
  pinMode(11, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);

void loop(){
  digitalWrite(11, HIGH);
  digitalWrite(5, LOW);
  digitalWrite(6, HIGH);

If someone could show me how to control motor speed using this setup it would be very helpful.


Ok, first of all if you want to control the speed of the motor you will need to use PWM (pulse with modulation). This outputs a digital signal to any one of the pins on your board labeled PWM or with the~ symbol. This turns the motor on and off so fast that it seems that the motor is receiving a variable voltage.

To use PWM first you must have the motor controlled by PWM capable pins (the pins you have chosen are). Then instead of using digitalWrite(11, HIGH); use analogWrite(11, 255); The 255 sets the duty cycle (speed of the motor). The variable can be from 0 to 255.

I suggest that you read this it explains everything clearly and in depth.

Also like Steve said, you shouldn't be powering the motor from the board. You should be using a external power source and then have a common ground. I am surprised that your board isn't resetting with all that extra current being drawn.

Good luck with your project, David.

Not a good idea to use the computer's 5V supply to run the motor. Better to use a separate supply, so you can feed the motor with enough current.

If you connect the enable line to a PWM pin on the Arduino, then you should be able to control the speed by the duty cycle you put on it, and you can turn the motor off by writing '0' to the pin.

I was just using the computer for this setup. I am actually going to use a battery which I am going to solder to use with the circular power input (forgot what it was called)

No, DON'T take the power for the motor through the computer - power the SainSmart directly instead.

DoFollow Steve's advice !!

Those lile motors generate very strong RMS transients.