# HG changeset patch # User John Tsiombikas # Date 1383334394 -7200 # Node ID 4ea5d2920f89490c9c40905603614b95ae76cb23 # Parent 050c04723d3761233f3db29392e2e2ea910f24d4 made the timing more accurate diff -r 050c04723d37 -r 4ea5d2920f89 pwcdecode.c --- a/pwcdecode.c Fri Nov 01 09:40:20 2013 +0200 +++ b/pwcdecode.c Fri Nov 01 21:33:14 2013 +0200 @@ -75,20 +75,15 @@ printf("initializing..."); TCCR1B |= (1 << ICES1); /* set first capture to occur on a rising edge */ - TCCR1B = (TCCR1B & 0xf8) | 1; /* no prescaling */ + TCCR1B = (TCCR1B & 0xf8) | 2; /* /8 prescaling */ TIMSK1 |= (1 << ICIE1); /* enable timer1 input capture interrupt */ sei(); for(;;) { - static int blink = 0; - - PORTB = blink ? 1 : 0; - blink = (blink + 1) & 1; - lcd_set_cursor_addr(0); printf("pulse time: %u us ", pulse_time); lcd_set_cursor_addr(64); - printf("pos: %u%% ", (pulse_time - 1000) / 10); + printf("pos: %u %% ", (pulse_time - 1000) / 10); _delay_ms(100); } return 0; @@ -97,18 +92,22 @@ ISR(TIMER1_CAPT_vect) { static int rising; + static unsigned int start_time; rising = !rising; if(rising) { - /* rising edge: reset the timer */ - TCNT1 = 0; + /* start counting ... */ + start_time = ICR1; /* and set a falling edge trigger */ TCCR1B &= ~(1 << ICES1); } else { /* falling edge: calculate the time since the last rise */ - pulse_time = ICR1; + pulse_time = (ICR1 - start_time) * 8; /* 8x to cancel out prescaling */ /* and set a rising edge trigger */ TCCR1B |= 1 << ICES1; + + /* also clear the timer so it won't overflow */ + TCNT1 = 0; } }