timer.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. ** Made by fabien le mentec <texane@gmail.com>
  3. **
  4. ** Started on Sun May 31 01:58:07 2009 texane
  5. ** Last update Sat Oct 10 22:02:37 2009 texane
  6. */
  7. /* timer1 provides a way to be interrputed when
  8. the timer per clock cycle incremented register
  9. matches the value of a period register.
  10. */
  11. #include <pic18fregs.h>
  12. static volatile int has_interrupted = 0;
  13. void timer_loop(unsigned int usecs)
  14. {
  15. /* the timer is set to be incremented at
  16. each insn cycle. an instruction cycle
  17. occurs at fosc / 4. at a fosc of 8mhz
  18. there are 2 insns per micro seconds.
  19. */
  20. unsigned int d = 0xffff - usecs * 2;
  21. T1CONbits.TMR1ON = 0; /* disable timer1 */
  22. T1CONbits.RD16 = 0; /* read/write in 2 8 bits operations */
  23. TMR1L = d & 0xff;
  24. TMR1H = (d >> 8) & 0xff;
  25. T1CONbits.T1CKPS0 = 0; /* 1:1 prescaler */
  26. T1CONbits.T1CKPS1 = 0; /* 1:1 prescaler */
  27. T1CONbits.T1OSCEN = 0; /* t1 osc shut off */
  28. T1CONbits.TMR1CS = 0; /* internal clock */
  29. T1CONbits.TMR1ON = 1; /* enable timer1 */
  30. PIE1bits.TMR1IE = 1; /* enable int */
  31. /* wait for interrupt */
  32. while (1)
  33. {
  34. PIE1bits.TMR1IE = 0; /* acquire */
  35. if (has_interrupted)
  36. {
  37. has_interrupted = 0;
  38. break;
  39. }
  40. PIE1bits.TMR1IE = 1; /* release */
  41. }
  42. T1CONbits.TMR1ON = 0; /* disable timer1 */
  43. }
  44. unsigned int timer_stop(void)
  45. {
  46. unsigned int n;
  47. n = (TMR1H << 8) | TMR1L;
  48. T1CONbits.TMR1ON = 0;
  49. return n;
  50. }
  51. void timer_start(void)
  52. {
  53. T1CONbits.TMR1ON = 0; /* disable timer1 */
  54. T1CONbits.RD16 = 0; /* read/write in 2 8 bits operations */
  55. TMR1L = 0;
  56. TMR1H = 0;
  57. T1CONbits.T1CKPS0 = 0; /* 1:1 prescaler */
  58. T1CONbits.T1CKPS1 = 0; /* 1:1 prescaler */
  59. T1CONbits.T1OSCEN = 0; /* t1 osc shut off */
  60. T1CONbits.TMR1CS = 0; /* internal clock */
  61. T1CONbits.TMR1ON = 1; /* enable timer1 */
  62. PIE1bits.TMR1IE = 0; /* enable int */
  63. }
  64. int timer_handle_interrupt(void)
  65. {
  66. if (!PIR1bits.TMR1IF)
  67. return -1;
  68. PIR1bits.TMR1IF = 0;
  69. has_interrupted = 1;
  70. return 0;
  71. }