MoRoH
New Member
Hello all,
I have a PIC16f873A microcontroller and my goal is to put an analog signal on RA0 and get a PWM waveform output. I would like 0v = 0%duty and 5v = 100% duty to control a small DC motor.
This is the code i have...right now, on CCP2 i am getting whatever i set CCPPRL1 = X...so if i set it to 50 im getting a constant 50% duty cycle.
Any ideas how to read the analog input?
I have a PIC16f873A microcontroller and my goal is to put an analog signal on RA0 and get a PWM waveform output. I would like 0v = 0%duty and 5v = 100% duty to control a small DC motor.
This is the code i have...right now, on CCP2 i am getting whatever i set CCPPRL1 = X...so if i set it to 50 im getting a constant 50% duty cycle.
Any ideas how to read the analog input?
Code:
unsigned short duty_cycle;
unsigned short adc_val;
void InitMain() {
ADCON1 = 0xfe; // All ADC pin 1 to on
TRISA = 0x01; // PORTA is input
PORTC = 0; // Set PORTC to
TRISC = 0x00; // PORTC is output
Pwm_Init(5000); // Initialize PWM module
// Timer 2
PR2=100; // 4 MHz clock -> 5kHz PWM frequency
T2CON = (1<<TMR2ON);
// Initialize Control PWM
CCPR1L = 50; // Initial Duty
CCP1CON = 0x0f; // PWM mode set and 5,4 duty = 0
}
void main() {
InitMain();
Pwm_Start(); // Start PWM
while (2)
{
adc_val = adc_read(0); //read analog input RA0
if (adc_val > duty_cycle) // if value is higher
Pwm_Change_Duty(++duty_cycle); //then increase duty
else if (adc_val < duty_cycle) //if value is lower
Pwm_Change_Duty(--duty_cycle); //lower duty
PORTC = duty_cycle; //output PWM on C
Delay_ms(200); //slow down process
}
}