Advertisement
Guest User

Timer

a guest
Jun 28th, 2016
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. /*
  2. * RadekTimer.c
  3. *
  4. * Created: 7. 6. 2016 16:32:43
  5. * Author: MartinPC
  6. *
  7. * CPUCLK = 6,4MHz
  8. *
  9. * Fuses:
  10. * LOW: 0x43
  11. * HIGH: 0xDF
  12. * EXTENDED: 0xFF
  13. * LOCK: none
  14. *
  15. */
  16.  
  17. #include <avr/io.h>
  18. #include <avr/interrupt.h>
  19.  
  20. #define bit_is_set(sfr,bit) (_SFR_BYTE(sfr) & _BV(bit))
  21.  
  22. static int counter = 0;
  23. unsigned long ADCResult = 0;
  24.  
  25. typedef unsigned char u08;
  26. typedef unsigned short u16;
  27. typedef unsigned long u32;
  28.  
  29.  
  30. int main(void)
  31. {
  32. DDRB |= (1 << PB0); // LED on PB0
  33.  
  34. MCUCR = (1 << ISC01) | (1 << ISC00); // ISC01 = 1, ISC00 = 1 => rissing edge, ISC01 = 1, ISC00 = 0 => falling edge
  35. GIMSK = (1 << INT0);
  36. // Timer 1ms (6 400 000 / 8 / 8 / 100 = 1 000Hz; 1/1000 = 1ms
  37. // CPU_Freq (6,4MHz) / CKDIV8 / TIMER_Prescaller (8) / Timer compare counter (100)
  38. OCR0A = 0x64; // number to count up to (0x64 = 100)
  39. TCCR0A = (1 << WGM01); // Clear Timer on Compare Match (CTC) mode
  40. TIFR = 0; // clear interrupt flag
  41. TIMSK = (1 << OCIE0A); // TC0 compare match A interrupt enable
  42. TCCR0B = (1 << CS01); // clock source CLK/8, start timer
  43.  
  44. DIDR0 = (1<<ADC2D);
  45. ADMUX = (1<<MUX1) | (1<<ADLAR);
  46. ADCSRA = (1<<ADEN) | (1<<ADIE) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0);
  47.  
  48. sei(); // global interrupt enable
  49. ADCSRA |= (1<<ADSC);
  50.  
  51. while(1)
  52. {
  53. // do nothing
  54. }
  55. }
  56.  
  57. ISR(INT0_vect)
  58. {
  59. TIFR &= ~(1 << OCF0A);
  60. ADCSRA &= ~(1 << ADIF);
  61. ADCSRA |= (1 << ADIE);
  62. TIMSK |= (1 << OCIE0A);
  63. TCNT0 = 0;
  64. if (bit_is_set(PORTB,PB3))
  65. {
  66. PORTB |= (1 << PB0);
  67. } else {
  68. PORTB &= ~(1 << PB0);
  69. }
  70. }
  71.  
  72. ISR(TIMER0_COMPA_vect)
  73. {
  74. if (bit_is_set(PORTB, PB1))
  75. {
  76. counter ++;
  77.  
  78. if (counter >= (100 * ADCResult))
  79. {
  80. ADCSRA &= ~(1 << ADIE);
  81. TIMSK &= ~(1 << OCIE0A);
  82.  
  83. counter = 0;
  84.  
  85. if (bit_is_set(PORTB,PB3))
  86. {
  87. PORTB &= ~(1 << PB0);
  88. } else {
  89. PORTB |= (1 << PB0);
  90. }
  91. }
  92. }
  93. }
  94.  
  95. ISR(ADC_vect)
  96. {
  97. ADCResult = ((u32)(((u32)((u32)ADCH*(u32)2700))/((u32)256/*(u32)10*/))); //ADCResult = 2700/256 = 0-2700 => 0 -> 270 000ms
  98. ADCSRA |= (1<<ADSC);
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement