Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Main.c file generated by New Project wizard
- *
- * Created: jue nov 9 2017
- * Processor: PIC18F4550
- * Compiler: MPLAB XC8
- */
- #include <xc.h>
- #include <p18f4550.h>
- #include "config.h"
- //Variables globales
- int contador = 0; // indicara cuando han pasado 4 ms
- int i = 0; // indicara el numero de incrementos de CCPR1L (0 <= i <= 399)
- void interrupt timer2(void) {
- if (PIR1bits.TMR2IF) { // Ha pasado 2 ms
- ++contador;
- if (contador == 8) { // Han pasado 16 ms (para no cambiar el DC1B0 y DC1B1 (bits de menos peso))
- contador = 0;
- ++i;
- if (i <= 99) CCPR1L = i + i / 4; // duty-cycle oscil·lant entre 0 i 100%
- if (i > 100) CCPR1L = 250 - (i + i / 4); // duty-cycle oscil·lant entre 100 i 0%
- if (i >= 199) { // Ya ha pasado 1.6 segundos
- i = 0;
- CCPR1L = 0;
- }
- }
- PIR1bits.TMR2IF = 0;
- }
- }
- void main(void)
- {
- ADCON1 = 0x0F;
- TRISCbits.RC2 = 0; // RC2 como salida
- INTCONbits.GIE = 1; // Enables all interrupts
- PIE1bits.TMR2IE = 1; // Enables the TMR2 to PR2 match interrupt
- // The PIE registers contain enable bits for the peripheral interrupts => TMR2 es una interrupcion periferica
- INTCONbits.PEIE = 1; // Enables peripheral interrupts
- T2CONbits.T2CKPS1 = 1; // T2CKPS1 = 1, T2CKPS0 = x => Prescaler de 16
- PR2 = 124; // PWM Period = (PR2 + 1) * 4 * TOSC *(TMR2 Prescale Value)
- // 1*10^-3 = (PR2 + 1) * 4 * (1/[8*10^6]) * 16 => 1*10^-3 = (PR2 + 1) * 8*10^-6
- // PR2 = [(1*10^-3)/(8*10^-6)] - 1 = 124
- // The PWM duty cycle is specified by writing to the CCPRxL register and to the CCPxCON<5:4> bits
- // PWM Duty Cycle = (CCPRXL<7:0>:CCPXCON<5:4>) • TOSC • (TMR2 Prescale Value)
- // ej.- DC = 100% (lo que dura el periodo, en nuestro caso 1 ms, esta a 1) => 1*10^-3 = x * (1/[8*10^6]) * 16 =>
- // => x = 500 = 0111110100 => CCPR1L = 01111101 = 125, DC1B1 = DC1B0 = 0
- CCP1CONbits.CCP1M3 = 1;
- CCP1CONbits.CCP1M2 = 1; // PWM mode
- // Queremos que el duty cicle oscile entre 0% y 100% en 1 segundo, es decir, que CCPR1L tiene que ir de 0 a 125
- // y de 125 a 0 en 1,6 segundo => CCPR1L cambiara de valor 250 veces por segundo. Cada cuanto hemos de incrementar
- // su valor? Cada 4 ms (1/250 = 4*10^-3 s)
- CCPR1L = 0;
- CCP1CONbits.DC1B1 = 0;
- CCP1CONbits.DC1B0 = 0; // DC lo inicializamos a 0%
- T2CONbits.TMR2ON = 1; // Timer2 is on
- while(1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement