Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.84 KB | None | 0 0
  1. #include <htc.h>
  2.  
  3. #define _XTAL_FREQ 8e6 // 8MHz
  4. #define ZERO_CROSS_PIN GP0
  5. #define ZERO_CROSS_PIN_TRIS TRISIO0
  6. #define OUTPUT_PIN GP1
  7. #define OUTPUT_PIN_TRIS TRISIO1
  8.  
  9. /*
  10.    _delay( 1 ); // 1 instruction cycle delay
  11.    __delay_us( 2 ); // 2 us delay
  12.    __delay_ms( 3 ); // 3 ms delay
  13. */
  14.  
  15. unsigned char timerArmed = 0; // set if timer is waiting to go off
  16. unsigned int delayTicks = 0; // number of ticks to set the timer to for the desired delay
  17. unsigned int delayFor = 0; // delay for this many uS
  18.  
  19. int main (void)
  20. {
  21.     // -- Oscillator setup
  22.     OSCCONbits.IRCF = 7; // set internal osc to 8MHz   
  23.     while (!OSCCONbits.HTS); // wait for osc to be stable
  24.    
  25.     // -- IO setup
  26.     ZERO_CROSS_PIN_TRIS = 1; // read from Z_C_PIN
  27.     OUTPUT_PIN_TRIS = 0; // write to O_P
  28.     OUTPUT_PIN = 0; // set it to a known state
  29.    
  30.     // -- Timer1 setup
  31.     T1CONbits.T1CKPS = 0; // 1:1 prescaler
  32.     T1CONbits.T1OSCEN = 0; // disable Timer1 oscillator
  33.     T1CONbits.TMR1CS = 0; // internal clock (fosc/4)
  34.    
  35.     // -- Timer1 interrupt setup
  36.     TMR1 = 0; // clear timer1 counter
  37.     TMR1IF = 0; // clear timer1 flag
  38.     TMR1IE = 1; // enable timer1 interrupt
  39.     PEIE = 1; // enable peripheral interrupts
  40.     GIE = 1; // enable all interrupts      
  41.        
  42.     while (1)
  43.     {
  44.         if (ZERO_CROSS_PIN && !timerArmed) // if we have a pulse and the
  45.         {                                  // timer isnt armed, arm it
  46.             delayFor = 4000; // in uS
  47.             delayTicks = (2 * delayFor);
  48.             TMR1 = (0xFFFF - delayTicks) + 1; // +1 to account for ffff->0 rollover
  49.             T1CONbits.TMR1ON = 1; // arm timer1
  50.             timerArmed = 1;
  51.         }  
  52.     }
  53.    
  54.     return 0; // should never get here
  55.  
  56. }
  57.  
  58. void interrupt interrupt_handler(void)
  59. {
  60.     if (TMR1IE && TMR1IF) // if TMR1 caused the interrupt
  61.     {
  62.         OUTPUT_PIN = 1; // fire!
  63.         __delay_us(10); // for the triac to catch up
  64.         OUTPUT_PIN = 0; // triac will continue to conduct until current drops
  65.         timerArmed = 0; // timer not armed anymore
  66.         TMR1IF = 0; // clear interrupt flag
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement