This is part 4 of my “Building Robots using Arduino” tutorial series, explaining how you can create robots using Arduino.
In this article we will see how we can control the speed of the DC motor using Arduino.
Last week, I explained how we can control the direction of DC motors using the H-Bridge L293D IC.
This week we will see how we can control the speed of the motor as well using the IC. Also I will talk about how we can encapsulate the entire logic into an Arduino Library.
Before we go ahead, we need to know about
analogWrite function in Arduino.
In Arduino, the
analogWrite function allows you to generate a PWM wave in a pin. If you have tried out the LED fade example in Arduino, then you already know how to use it. If not, then checkout the PWM tutorial from Arduino reference.
This function takes a value between 0 and 255 and doesn’t work on all pins in Arduino. In Arduino Uno, it works on pins 3, 5, 6, 9, 10 and 11.
Controlling Speed of DC Motors
To control the speed of the motor, all we need to do is to replace
digitalWrite function on L293D enable pins to
analogWrite. The speed of the motor depends on value that was passed to the
analogWrite function. Remember the value can be between 0 and 255. If you pass 0, then the motor will stop and if you pass 255 then it will run at full speed. If you pass a value between 1 and 254, then the speed of the motor will vary accordingly.
You can just reuse the same circuit from last week.
Remember, I asked you to connect the enable pins of H-bridge to pins 10 and 11 of Arduino. This is because pins 10 and 11 are PWM pins.
You just have to replace the function
analogWrite in last weeks code. The value you pass to
analogWrite function will decide the speed of the motor.
Here is the modified sketch that you can use to change the direction as well as the speed of the DC motors.
I have encapsulated the logic of changing directions of DC motors in an Arduino library called DCMotorBot. The library is available in github from where you can download it.
Instead of setting the pins individually, you can call the following directions to change the direction of the motors. Check out the examples sketches inside the
/examples folder of the library.
Note: I am still working on adding support for changing the speed(pwm) as well.
Next week we will see how we can put together all we have learned so far and build a complete bot. It’s going to be existing, so don’t miss it 😉
Till then, happy roboting 😉