timer.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * =====================================================================================
  3. *
  4. * ________ .__ __ ________ ____ ________
  5. * \_____ \ __ __|__| ____ | | __\______ \ _______ _/_ |/ _____/
  6. * / / \ \| | \ |/ ___\| |/ / | | \_/ __ \ \/ /| / __ \
  7. * / \_/. \ | / \ \___| < | ` \ ___/\ / | \ |__\ \
  8. * \_____\ \_/____/|__|\___ >__|_ \/_______ /\___ >\_/ |___|\_____ /
  9. * \__> \/ \/ \/ \/ \/
  10. *
  11. * www.optixx.org
  12. *
  13. *
  14. * Version: 1.0
  15. * Created: 07/21/2009 03:32:16 PM
  16. * Author: david@optixx.org
  17. *
  18. * =====================================================================================
  19. */
  20. #include <stdint.h>
  21. #include <stdio.h>
  22. #include <avr/io.h>
  23. #include <avr/io.h>
  24. #include <avr/interrupt.h> /* for sei() */
  25. #include "debug.h"
  26. #include "info.h"
  27. #ifndef OCR1A
  28. #define OCR1A OCR1 // 2313 support
  29. #endif
  30. #ifndef WGM12
  31. #define WGM12 CTC1 // 2313 support
  32. #endif
  33. //#define XTAL 11059201L // nominal value
  34. #define XTAL 20000000UL
  35. #define DEBOUNCE 500L // debounce clock (256Hz = 4msec)
  36. #define uint8_t unsigned char
  37. #define uint unsigned int
  38. uint16_t prescaler;
  39. uint16_t volatile second; // count seconds
  40. ISR (SIG_OUTPUT_COMPARE1A)
  41. {
  42. #if XTAL % DEBOUNCE // bei rest
  43. OCR1A = 20000000UL / DEBOUNCE - 1; // compare DEBOUNCE - 1 times
  44. #endif
  45. if( --prescaler == 0 ){
  46. prescaler = (uint16_t)DEBOUNCE;
  47. second++; // exact one second over
  48. #if XTAL % DEBOUNCE // handle remainder
  49. OCR1A = XTAL / DEBOUNCE + XTAL % DEBOUNCE - 1; // compare once per second
  50. #endif
  51. }
  52. }
  53. void timer_start( void )
  54. {
  55. TCCR1B = (1<<WGM12) | (1<<CS10); // divide by 1
  56. // clear on compare
  57. OCR1A = XTAL / DEBOUNCE - 1UL; // Output Compare Register
  58. TCNT1 = 0; // Timmer startet mit 0
  59. second = 0;
  60. prescaler = (uint16_t)DEBOUNCE; //software teiler
  61. TIMSK1 = 1<<OCIE1A; // beim Vergleichswertes Compare Match
  62. // Interrupt (SIG_OUTPUT_COMPARE1A)
  63. sei();
  64. }
  65. uint16_t timer_stop_int(void)
  66. {
  67. uint16_t t = ((DEBOUNCE - prescaler) / DEBOUNCE ) + second;
  68. return t;
  69. }