Advertisement
csansoon

Untitled

Nov 18th, 2019
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. /* Main.c file generated by New Project wizard
  2. *
  3. * Created: jue nov 9 2017
  4. * Processor: PIC18F4550
  5. * Compiler: MPLAB XC8
  6. */
  7.  
  8.  
  9. #include <xc.h>
  10. #include <p18f4550.h>
  11. #include "config.h"
  12.  
  13. //Variables globales
  14. int contador = 0; // indicara cuando han pasado 4 ms
  15. int i = 0; // indicara el numero de incrementos de CCPR1L (0 <= i <= 399)
  16.  
  17. void interrupt timer2(void) {
  18. if (PIR1bits.TMR2IF) { // Ha pasado 2 ms
  19. ++contador;
  20. if (contador == 8) { // Han pasado 16 ms (para no cambiar el DC1B0 y DC1B1 (bits de menos peso))
  21. contador = 0;
  22. ++i;
  23. if (i <= 99) CCPR1L = i + i / 4; // duty-cycle oscil·lant entre 0 i 100%
  24. if (i > 100) CCPR1L = 250 - (i + i / 4); // duty-cycle oscil·lant entre 100 i 0%
  25. if (i >= 199) { // Ya ha pasado 1.6 segundos
  26. i = 0;
  27. CCPR1L = 0;
  28. }
  29. }
  30. PIR1bits.TMR2IF = 0;
  31. }
  32. }
  33.  
  34. void main(void)
  35. {
  36. ADCON1 = 0x0F;
  37. TRISCbits.RC2 = 0; // RC2 como salida
  38. INTCONbits.GIE = 1; // Enables all interrupts
  39. PIE1bits.TMR2IE = 1; // Enables the TMR2 to PR2 match interrupt
  40. // The PIE registers contain enable bits for the peripheral interrupts => TMR2 es una interrupcion periferica
  41. INTCONbits.PEIE = 1; // Enables peripheral interrupts
  42. T2CONbits.T2CKPS1 = 1; // T2CKPS1 = 1, T2CKPS0 = x => Prescaler de 16
  43. PR2 = 124; // PWM Period = (PR2 + 1) * 4 * TOSC *(TMR2 Prescale Value)
  44. // 1*10^-3 = (PR2 + 1) * 4 * (1/[8*10^6]) * 16 => 1*10^-3 = (PR2 + 1) * 8*10^-6
  45. // PR2 = [(1*10^-3)/(8*10^-6)] - 1 = 124
  46. // The PWM duty cycle is specified by writing to the CCPRxL register and to the CCPxCON<5:4> bits
  47. // PWM Duty Cycle = (CCPRXL<7:0>:CCPXCON<5:4>) • TOSC • (TMR2 Prescale Value)
  48. // 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 =>
  49. // => x = 500 = 0111110100 => CCPR1L = 01111101 = 125, DC1B1 = DC1B0 = 0
  50. CCP1CONbits.CCP1M3 = 1;
  51. CCP1CONbits.CCP1M2 = 1; // PWM mode
  52. // Queremos que el duty cicle oscile entre 0% y 100% en 1 segundo, es decir, que CCPR1L tiene que ir de 0 a 125
  53. // y de 125 a 0 en 1,6 segundo => CCPR1L cambiara de valor 250 veces por segundo. Cada cuanto hemos de incrementar
  54. // su valor? Cada 4 ms (1/250 = 4*10^-3 s)
  55. CCPR1L = 0;
  56. CCP1CONbits.DC1B1 = 0;
  57. CCP1CONbits.DC1B0 = 0; // DC lo inicializamos a 0%
  58. T2CONbits.TMR2ON = 1; // Timer2 is on
  59. while(1);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement