Precision DC Motor Speed Control using Arduino PWM
PIC Microcontroller PWM & Timer2 Motor Control Tutorial
Controlling motors is a common requirement in embedded systems. On PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization., timers and PWM (Pulse-Width Modulation) are fundamental features that enable you to drive DC motors, servo motors, or even brushless motors efficiently. In this tutorial, we will explore how to configure timers and generate PWM signals on a PIC microcontroller
Introduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization. to control motor speed and direction.
Understanding the Role of Timers in Motor Control🔗
Timers in PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization. are hardware modules that increment at a specific rate based on an internal or external clock. By monitoring or comparing the timer value, we can generate precise delays, create periodic interrupts
Building Real-Time Projects with PIC Using Timer1 and Input CaptureDiscover how to leverage Timer1 and Input Capture on PIC microcontrollers for precise real-time applications, pulse measurements, and periodic interrupts., and produce PWM signals.
Key points about PIC timers:
- They operate independently of the CPU, allowing the microcontroller to perform other tasks while timing events continue.
- Most PIC MCUs
Mastering Digital I/O on PIC MCUs with Practical ExamplesLearn hands-on techniques for configuring and using digital I/O pins on PIC microcontrollers to control LEDs, sensors, and more in practical projects. feature multiple timers (e.g., Timer0, Timer1, Timer2, Timer3, etc.), each with different capabilities.
- Often, Timer2 or Timer4 is used in PWM applications because these timers are typically tied to PIC’s capture/compare/PWM (CCP) or enhanced CCP modules.
Pulse-Width Modulation (PWM) Concept🔗
PWM controls the amount of power delivered to a load by varying the relative amount of “on” and “off” times within a given switching period. For motor control, changing the duty cycle (the percentage of the time the signal is “high”) adjusts the motor’s speed or torque.
A typical PWM signal can be represented as follows:
- Period: The total time for one cycle of the PWM signal.
- Duty Cycle: The fraction of the period during which the PWM output is high.
Increasing the duty cycle increases the voltage applied to the motor (on average), thus increasing motor speed.
Configuring Timer2 and PWM Registers🔗
On many PIC devices, Timer2 is commonly used for PWM generation via a CCP (Capture/Compare/PWM) module. Below is a simplified overview of the relevant registers:
Register | Purpose |
---|---|
T2CON | Controls Timer2 operation (prescaler, on/off). |
PR2 | Sets the PWM period. |
CCPxCON | Configures the CCP module for PWM mode. |
CCPRxL | High 8 bits of the PWM duty cycle. |
CCPRxH (or DCxB bits) | Additional bits (lower) for duty cycle. |
Calculating the PWM Frequency
The PWM frequency can be calculated (for many PIC MCUsMastering Digital I/O on PIC MCUs with Practical ExamplesLearn hands-on techniques for configuring and using digital I/O pins on PIC microcontrollers to control LEDs, sensors, and more in practical projects.) by:
Where:
- \( F_{\text{OSC}} \) is the PIC clock frequency
Low-Power Strategies: Maximizing PIC Battery LifeDiscover proven low-power strategies for PIC microcontrollers that maximize battery life through smart oscillator use, sleep modes, and efficient coding..
- Prescaler
Building Real-Time Projects with PIC Using Timer1 and Input CaptureDiscover how to leverage Timer1 and Input Capture on PIC microcontrollers for precise real-time applications, pulse measurements, and periodic interrupts. is configured in T2CON (e.g., 1, 4, 16).
- PR2 is an 8-bit register defining the maximum Timer2 count.
Setting the Duty Cycle
The duty cycle is set through CCPRxL and the lower bits in CCPxCON. A common formula to determine the duty cycle register value is:
- The factor of 4 originates from how the PIC hardware organizes the duty cycle configuration (the DCxB bits in CCPxCON provide fractional duty cycle adjustments).
Motor Driver and H-Bridge Considerations🔗
While the PIC generates the PWM signal, the microcontroller’s I/O pins alone usually cannot supply enough current to drive motors directly. Thus, you often need:
- A transistor or MOSFET driver for single-direction speed control.
- An H-bridge driver IC (e.g., L293D or a MOSFET-based driver) for full bidirectional speed and direction control.
Ensure to power the motor from a stable power supply and include diodes or integrated flyback protection to safeguard against inductive voltage spikes.
Example: Basic DC Motor Speed Control🔗
Below is an illustrative code snippet in C using the XC8 compilerGetting Started with MPLAB X and the XC8 CompilerSet up MPLAB X IDE and XC8 compiler for PIC programming with our comprehensive guide detailing installation, configuration, and debugging techniques. for a generic PIC, demonstrating Timer2 setup for PWM on CCP1. Adjust register names and bits according to the specific PIC datasheet you are using.
#include <xc.h>
// Example Configuration Bits (adjust to your device and clock):
#pragma config FOSC = HS // External High-Speed oscillator
#pragma config WDTE = OFF // Watchdog Timer disabled
#pragma config PWRTE = ON // Power-up Timer enabled
#pragma config CP = OFF // Code Protection disabled
#pragma config BOREN = OFF // Brown-out Reset disabled
#pragma config LVP = OFF // Low-Voltage Programming disabled
#pragma config WRT = OFF // Flash Program Memory Write disabled
#pragma config CCPMX = RB0 // Example: CCP1 function on RB0 pin
#define _XTAL_FREQ 20000000UL // 20 MHz external oscillator example
void main(void)
{
// Set up the PWM pin as output (e.g., CCP1 pin):
TRISBbits.TRISB0 = 0; // Example: output on RB0
// Initialize Timer2 for PWM:
T2CON = 0b00000101; // Prescaler = 4 (T2CKPS1:T2CKPS0 = 01), Timer2 ON (TMR2ON = 1)
PR2 = 124; // Example PR2 value for ~20 kHz PWM (at 20 MHz clock)
// Configure CCP1 in PWM mode:
CCP1CON = 0b00001100; // CCP1 in PWM mode (CCP1M3:CCP1M0 = 1100)
// Set initial duty cycle ~50%:
CCPR1L = 62; // High 8 bits (PR2 is 124, so 62 is ~50% of 124)
// CCP1CON lower bits (DC1B1:DC1B0) can fine-tune duty cycle, e.g., 0 for simplicity:
CCP1CONbits.DC1B = 0;
// Wait for Timer2 to stabilize:
__delay_ms(10);
while (1)
{
// Example: ramp duty cycle from ~20% to ~80%
for (unsigned char duty = 25; duty < 100; duty += 5)
{
// Calculate approximate register value for the desired duty cycle:
unsigned int pwmValue = (unsigned int) (((float)duty/100.0) * (PR2 + 1) * 4);
// Split into CCPR1L and DC1B bits:
CCPR1L = (pwmValue >> 2) & 0xFF;
CCP1CONbits.DC1B = (pwmValue & 0x03);
__delay_ms(300);
}
}
}
Code Highlights
1. PR2 set to 124 generates a PWM period of approximately 20 kHz with a 20 MHz clock and a prescalerBuilding Real-Time Projects with PIC Using Timer1 and Input CaptureDiscover how to leverage Timer1 and Input Capture on PIC microcontrollers for precise real-time applications, pulse measurements, and periodic interrupts. of 4.
2. T2CON sets the prescalerBuilding Real-Time Projects with PIC Using Timer1 and Input CaptureDiscover how to leverage Timer1 and Input Capture on PIC microcontrollers for precise real-time applications, pulse measurements, and periodic interrupts. and turns Timer2 on.
3. CCP1CON configures the CCP1 module for PWM mode.
4. CCPR1L and CCP1CONbits.DC1B define the 10-bit duty cycle value.
Practical Tips🔗
1. Measure the Actual PWM Frequency with an oscilloscope or frequency counter to verify it matches design goals. Timing inaccuracies can arise from oscillator tolerances or prescalerBuilding Real-Time Projects with PIC Using Timer1 and Input CaptureDiscover how to leverage Timer1 and Input Capture on PIC microcontrollers for precise real-time applications, pulse measurements, and periodic interrupts. usage.
2. Use Proper Bypass Capacitors on the PIC’s VDD pins and motor driver power lines to minimize noise and ripple.
3. Include Flyback Protection such as diode clamps or integrated circuits specifically designed to handle inductive loads.
4. Implement a Ramp or Slew approach (as shown in the example) to smoothly accelerate motors, reducing voltage spikes and mechanical stress.
Conclusion🔗
Using Timers and PWM on PIC microcontrollersIntroduction to PIC: Exploring the Basics of Microcontroller ArchitectureExplore the core principles of PIC microcontroller architecture, including Harvard design, RISC processing, and efficient memory organization. is a straightforward yet powerful technique to drive motors with precision. By configuring Timer2 (or an equivalent timer) and the CCP module, you can produce stable PWM signals to control motor speed under varying loads. Master these fundamental steps-setting the PWM frequency, adjusting the duty cycle, and interfacing with a proper driver-and you will be well on your way to implementing reliable motor control solutions in your own PIC-based projects.
Author: Marcelo V. Souza - Engenheiro de Sistemas e Entusiasta em IoT e Desenvolvimento de Software, com foco em inovação tecnológica.
References🔗
- Microchip: www.microchip.com
- Microchip Developer Help: microchipdeveloper.com/