alexandru321
Newbie level 2
hello guys i have some problem with pwm ,i want to control a servo motor with adc ,i cant make 20 ms period....i tried but max is 16 ms...i don t know wath i do wrog ,pls help.
Code C - [expand] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 #pragma config FOSC = HS // Oscillator Selection bits (HS oscillator) #pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled) #pragma config PWRTE = ON // Power-up Timer Enable bit (PWRT enabled) #pragma config BOREN = OFF // Brown-out Reset Enable bit (BOR disabled) #pragma config LVP = ON // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3/PGM pin has PGM function; low-voltage programming enabled) #pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off) #pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off; all program memory may be written to by EECON control) #pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off) #define _XTAL_FREQ 20000000 #define TMR2PRESCALE 4 #include"pic16f1825.h" #include <xc.h> long PWM_freq = 5000; long PWM_period; PWM_Initialize() { PR2 =(_XTAL_FREQ/(PWM_freq*4*TMR2PRESCALE)) - 1; //Setting the PR2 formulae using Datasheet // Makes the PWM work in 5KHZ CCP4M3 = 1; CCP4M2 = 1; T2CKPS0= 1; T2CKPS1= 1; TMR2ON= 1; //Configure the Timer module TRISC1=0; } PWM_Duty(unsigned int duty) { if(duty<1023) { duty = ((float)duty/1023)*(_XTAL_FREQ/(PWM_freq*TMR2PRESCALE)); DC4B1 = duty & 1; DC4B0 = duty & 2; CCPR1L = duty>>2; } } void ADC_Initialize() { ADCON0 = 0b0000001; //ADC ON and Fosc/16 is selected ADCON1 = 0b11010000; } unsigned int ADC_Read(unsigned char channel) { ADCON0 &= 0x11000101; //Clearing the Channel Selection Bits ADCON0 |= channel<<3; //Setting the required Bits __delay_ms(2); GO_nDONE = 1; //Initializes A/D Conversion while(GO_nDONE); //Wait for A/D Conversion to complete return ((ADRESH<<8)+ADRESL); //Returns Result } void main() { int adc_value; int pot; TRISC = 0x00; //PORTC as output TRISA = 0xFF; //PORTA as input //TRISD = 0x00; ADC_Initialize(); //Initializes ADC Module PWM_Initialize(); //This sets the PWM frequency of PWM1 do { adc_value =0.01825*ADC_Read(0)+7; pot =170 -adc_value ; __delay_ms(5); //Reading Analog Channel 0 PWM_Duty(adc_value); __delay_ms(50); }while(1); //Infinite Loop }
Last edited by a moderator: