DC Motor Tutorial


DC Motor Speed Control

A DC motor works by converting electric power into mechanical work. This is accomplished by forcing current through a coil and producing a magnetic field that spins the motor. 

One technique to vary the speed of a DC motor is by varying the voltage on the coil. To do this with a microcontroller, PWM output must be used so that the Duty cycle can be changed and automatically the average voltage output will be changed too. Consequently the speed of the motor will be changed. This can be seen in the figure below:

pulse width modulation

DC motor speed control Circuit:

To drive a dc motor from a micro-controller, there must be a buffer or an H-bridge driver so that the motor will not be driven directly by the micro because the current needed is not sufficient. The schematic below shows an example how to connect the motor to be driven in both direction (foward and reverse) with an L298 driver and connected to a microcontroler (using PWM to control the speed control).

l298 circuit

Download L298 Datasheet 


PIC C Code:

(PWM duty cycle every 1/2 second on portb which is used to control a motor with the l298hn motor driver. The Input PWM runs at 1 KHz frequency. A simple for loop creates the PWM.)

#include <p18f452.h> #include <delays.h> void main(void) { //Used In Main Control long int i=0; int on_off =1; //L298 Control Parameters int speed_pos=5; int speed_neg=45; int direction = 0; //Digital Port Setups TRISA = 0x00; TRISB = 0x00; PORTA = 0x00; PORTB = 0x00; //Enable The Motor PORTBbits.RB0 = 1; //Main Infinite While Loop while(1){ //Change LED State Each Loop PORTAbits.RA0 = on_off; //Generates PWM To Drive The Motor //For 0.5 Seconds for(i=0;i<500;i++){ Delay100TCYx(speed_pos); PORTBbits.RB1 = 1; PORTBbits.RB2 = 0; Delay100TCYx(speed_neg); PORTBbits.RB1 = 0; PORTBbits.RB2 = 1; } //Control Method For Continous //Speed Up/Slow Down & Reversing Direction if(speed_pos == 5 && speed_neg == 48) direction = 0; else if(speed_pos == 45 && speed_neg == 5) direction = 1; //Speed Variation Through Changing The PWM if(direction == 0){ speed_pos++; speed_neg--; } if(direction == 1){ speed_pos--; speed_neg++; } } }