Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Original by Karl Buchka. Modded by blabla
- #include <avr/io.h>
- #include <avr/interrupt.h>
- #include <util/delay.h>
- uint16_t current = 0;
- uint16_t lastcount = 0;
- uint16_t average = 0;
- uint8_t toothCount = 0;
- uint8_t avgIndex = 0;
- uint8_t firstRun = 2;
- uint16_t lastFour[4] = {0,0,0,0};
- int main(void)
- {
- cli();
- _delay_ms(10); // Wait
- DDRC |= ( (1 << DDC0) | (1 << DDC1) ); //Enable PC0 and PC1 as output
- _delay_ms(10); // Wait
- DDRA |= ( (1 << DDA0) | (1 << DDA1) );
- _delay_ms(10); // Wait
- TCCR1B = 0b01000011; // Rising edge input capture, Timer1 t/256 prescaling.
- _delay_ms(10); // Wait
- TIMSK = 0b00100000; // Interrupt on Input Capture
- _delay_ms(10); // Wait
- sei();
- while(1) {
- //Do stuff
- }
- }
- ISR(TIMER1_CAPT_vect)
- {
- // Rising edge only
- if (firstRun == 2) // First pulse, cannot calculate time between pulses. Just save captured TIMER value.
- {
- lastcount = ICR1;
- firstRun=1;
- return;
- }
- if (ICR1 < lastcount) {
- current = (0xFFFF - lastcount) + ICR1; // Counter overflow
- } else {
- current = ICR1 - lastcount;
- }
- lastcount =ICR1;
- // Second run of code, fill running average with first real tooth time.
- if (firstRun == 1) {
- for (uint8_t i = 0; i < 4; i++) {
- lastFour[i] = current;
- }
- firstRun = 0;
- }
- // Calculate average of last 4 non-missing teeth.
- for (uint8_t i = 0; i < 4; i++) {
- average += lastFour[i];
- }
- average >>= 1; // Divide by 2
- // If missing tooth, zero tooth count, else (non-missing), check for trigger
- // teeth, add tooth time to running average, and increment toothCount.
- if (current > average) {
- toothCount = 0;
- } else {
- if (toothCount == 15) {
- PORTC |= (1<<PORTC0);
- PORTC &= ~(1<<PORTC1);
- PORTA |= (1<<PORTA0);
- PORTA &= ~(1<<PORTA1);
- }
- if (toothCount == 45) {
- PORTC &= ~(1<<PORTC0);
- PORTC |= (1<<PORTC1);
- PORTA &= ~(1<<PORTA0);
- PORTA |= (1<<PORTA1);
- }
- lastFour[avgIndex] = current;
- avgIndex += 1;
- avgIndex %= 4;
- toothCount++;
- average = 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement