receiver/main.c

Sun, 02 Dec 2012 18:03:06 +0100

author
Malte Bayer <mbayer@neo-soft.org>
date
Sun, 02 Dec 2012 18:03:06 +0100
changeset 114
313aad7435a8
parent 17
9e6feafc19e1
permissions
-rw-r--r--

fix #688

#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/wdt.h>
#include <avr/eeprom.h>
#include <stdlib.h>
#include <stdint.h>
#include <avr/pgmspace.h>

#include "main.h"

#include "driver/rs232.h"
#include "util/delay.h"


ISR ( USART_RXC_vect ) {
}

// PD2 / PD3 = INT0 / INT1
// connect IR receiver to these pins to measure frequencies

volatile uint8_t car0, car1;
uint8_t car_tmp0, car_tmp1, car_count0, car_count1, car_buffer0, car_buffer1;
#define CARDETECT_CYCLES 2
ISR ( TIMER0_OVF_vect ) {
    // divides f_cpu by 256
    // Interrupt every 32µs

    if ( (PIN(PORTD) & _BV(PD2)) == 0) {
        car_tmp0++;
    } else {
        // return car ID length
        if (car_tmp0 != 0) {
            car_count0++;
            car_buffer0 += car_tmp0;
            if (car_count0 == CARDETECT_CYCLES) {
                car_buffer0 = (car_buffer0) / CARDETECT_CYCLES;
                if (car_buffer0 == car_tmp0) car0 = car_tmp0;
                //car0 = car_buffer0;
                car_buffer0 = 0;
                car_count0 = 0;
            }
            car_tmp0 = 0;
        }
    }

}


uint8_t get_car(uint8_t pin) {
    uint8_t i=0xff;
    // wait ~~ Xµs for low signal
    while ( (PIN(PORTD) & pin) != 0) {
        _delay_us(5);
        i--;
        if (i==0) return 0; // no low signal, do not longer block
    }
    // wait until signal is high again to start measurement
    while ( (PIN(PORTD) & pin) == 0) ;
    i = 0;
    while (i<100) {
        _delay_us(4);
        i++;
        if ( (PIN(PORTD) & pin) == 0) { // return car ID
            if ( (i>= 5) & (i<= 9) ) return 1; // 05-09 = car1
            if ( (i>=13) & (i<=16) ) return 2; // 13-16 = car2
            if ( (i>=19) & (i<=22) ) return 3; // 19-22 = car3
            if ( (i>=28) & (i<=31) ) return 4; // 28-31 = car4
            // debug: return higher values:
            if (i>32) return i;
        }
    }
    return 0; // timeout or incorrect measurement
}


int main(void)
{
    uint16_t i;
    unsigned char s[30];
    
    // initialize timer0 for IR signal detection
    TCCR0 = _BV(CS00); // system clock, no prescaling
    TIMSK = _BV(TOIE0);

    RS232_init(); // initialize RS232 interface
    RS232_puts_p(PSTR("Car ID Scanner v0.1\n"));
    sei();
    
    while (1) {
        // main loop

/*
        i = get_car(_BV(PD2));
        if (i > 0) {
            itoa ( i , s, 10);
            RS232_puts(s);
            RS232_putc('\n');
        }
*/

        if (car0 > 0) {
            itoa ( car0 , s, 10);
            car0 = 0;
            RS232_puts(s);
            RS232_putc('\n');
        }

    } // main loop end
};

mercurial