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:
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).
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.)