pwcdecode
changeset 1:4ea5d2920f89 tip
made the timing more accurate
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Fri, 01 Nov 2013 21:33:14 +0200 |
parents | 050c04723d37 |
children | |
files | pwcdecode.c |
diffstat | 1 files changed, 9 insertions(+), 10 deletions(-) [+] |
line diff
1.1 --- a/pwcdecode.c Fri Nov 01 09:40:20 2013 +0200 1.2 +++ b/pwcdecode.c Fri Nov 01 21:33:14 2013 +0200 1.3 @@ -75,20 +75,15 @@ 1.4 printf("initializing..."); 1.5 1.6 TCCR1B |= (1 << ICES1); /* set first capture to occur on a rising edge */ 1.7 - TCCR1B = (TCCR1B & 0xf8) | 1; /* no prescaling */ 1.8 + TCCR1B = (TCCR1B & 0xf8) | 2; /* /8 prescaling */ 1.9 TIMSK1 |= (1 << ICIE1); /* enable timer1 input capture interrupt */ 1.10 sei(); 1.11 1.12 for(;;) { 1.13 - static int blink = 0; 1.14 - 1.15 - PORTB = blink ? 1 : 0; 1.16 - blink = (blink + 1) & 1; 1.17 - 1.18 lcd_set_cursor_addr(0); 1.19 printf("pulse time: %u us ", pulse_time); 1.20 lcd_set_cursor_addr(64); 1.21 - printf("pos: %u%% ", (pulse_time - 1000) / 10); 1.22 + printf("pos: %u %% ", (pulse_time - 1000) / 10); 1.23 _delay_ms(100); 1.24 } 1.25 return 0; 1.26 @@ -97,18 +92,22 @@ 1.27 ISR(TIMER1_CAPT_vect) 1.28 { 1.29 static int rising; 1.30 + static unsigned int start_time; 1.31 1.32 rising = !rising; 1.33 if(rising) { 1.34 - /* rising edge: reset the timer */ 1.35 - TCNT1 = 0; 1.36 + /* start counting ... */ 1.37 + start_time = ICR1; 1.38 /* and set a falling edge trigger */ 1.39 TCCR1B &= ~(1 << ICES1); 1.40 } else { 1.41 /* falling edge: calculate the time since the last rise */ 1.42 - pulse_time = ICR1; 1.43 + pulse_time = (ICR1 - start_time) * 8; /* 8x to cancel out prescaling */ 1.44 /* and set a rising edge trigger */ 1.45 TCCR1B |= 1 << ICES1; 1.46 + 1.47 + /* also clear the timer so it won't overflow */ 1.48 + TCNT1 = 0; 1.49 } 1.50 } 1.51