Advertisement
patryk

Frequency Counter

Apr 23rd, 2015
555
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. #include <avr/io.h>
  2. #include <avr/delay.h>
  3. #include <avr/interrupt.h>
  4.  
  5. volatile unsigned int one_second_ready;
  6. volatile unsigned int overflow_ticks;
  7.  
  8. /*--------------------------INTERUPTS----------------------------*/
  9.  
  10. // TIMER 0 OVERFLOW INTERRUPT
  11. ISR (TIMER0_OVF_vect) {
  12.     overflow_ticks++;
  13. }
  14.  
  15.  
  16. // TIMER 1 COMPARE VALUE INTERRUPT
  17. ISR (TIMER1_COMPA_vect) {
  18.  
  19.     // T0 DISABLE
  20.     TCCR0 &= ~(1 << CS02) & ~(1 << CS01) & ~(1 << CS00);
  21.     TIMSK &= ~(1 << TOIE0);
  22.  
  23.     // T1 DISABLE
  24.     TCCR1B &= ~(1 << WGM12) & ~(1 << CS12) & ~(1 << CS10);
  25.     TIMSK &= ~(1 << OCIE1A);
  26.  
  27.     one_second_ready = 1;   // Send Signal To sensorMeasurement() Function
  28. }
  29.  
  30. /*---------------------------------------------------------------*/
  31.  
  32.  
  33. int sensorMeasurement() {
  34.     one_second_ready = 0;
  35.     overflow_ticks = 0;
  36.  
  37. //  T0 INITIALIZE
  38.     TCCR0 |= (1 << CS02) | (1 << CS01) | (1 << CS00);   // External Clock T0 Rising Edge
  39.     TIMSK |= (1 << TOIE0);  // Enable T0 Interrupt
  40.  
  41. //   T1 INITIALIZE
  42.     TCCR1B |= (1 << WGM12) | (1 << CS12) | (1 << CS10);     // CTC MODE
  43.     OCR1A = F_CPU / 1024;       // 1 Second Delay
  44.     TIMSK |= (1 << OCIE1A);     // Enable T1 Interrupt
  45.  
  46.     sei();  // Enable Interrupts
  47.  
  48.     while (one_second_ready == 0);  // Wait until T1 is 1 second
  49.  
  50.     cli();  // Disable Interrupts
  51.  
  52.     return overflow_ticks * 256;    // Signal Frequency
  53. }
  54.  
  55.  
  56. int main() {
  57.  
  58.     DDRB |= (1 << PB0);
  59.  
  60.     int measure = sensorMeasurement();
  61.  
  62.     for (int i = 0 ; i < measure / 1000 ; i++) {
  63.         PORTB ^= (1 << PB0);
  64.         _delay_ms(300);
  65.     }
  66.  
  67.     while(1) {
  68.  
  69.     }
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement