// RFID Door Lock
// 20060729 - Mikey Sklar

#include <avr/io.h>


#define RFID_SAVES 1            // RFID tag number save once 
#define RFID_ELEMENT_SIZE 10    // 10 digit rfid number 


uint8_t rfid_data[RFID_SAVES][RFID_ELEMENT_SIZE];       // stores rfid tag number


void serial_init (void);
uint8_t serial_recv (void);
void delay (uint16_t us);
void rfid_tag_scan (void);
void open_lock(void);
int main (void);


// initialize the serial port
void serial_init(void) {

// BAUD approximate formula 16000000/16/2400-1 
#define BAUD 207   // 2400bps @ 8MHz

  UBRRH = (BAUD >> 8);  // high order bits 
  UBRRL = BAUD;         // low order bits 

  // enable tx and rx
  UCSRB = (1 << RXEN) | (1 << TXEN);
  UCSRC = (1 << UCSZ1) | (1 << UCSZ0);

  return;
}


// Wait for a character on the serial line and return it.
uint8_t serial_recv (void) {
        // wait for rx char 
        while (!(UCSRA & (1 << RXC)));

        // return the char 
        return UDR;
}


// slow it down
void delay (uint16_t us)
{
    while ( us ) us--;
}


// read rfid tag number with parallax
// device made by Grand Idea Studio
void rfid_tag_scan (void) {

        uint8_t rfid_read='n';
        uint8_t j=0;
        uint8_t k=0;

        rfid_read = serial_recv();

        if ( rfid_read == '\n' && j <= RFID_SAVES ) {

                while ( rfid_read != '\r' && k < RFID_ELEMENT_SIZE ) {
                        rfid_read = serial_recv();
                        rfid_data[j][k] = rfid_read;
                        k++;
                }
        }

        k=0;
        j++;

        return;

}


// throws deadbolt 
void open_lock(void) {
        PORTB = 0x01;
        delay(65000);
}


int main() {
        uint8_t c;

        DDRB = 0xff;    // all output 
        PORTB = 0x00;   // all outputs off 

        serial_init();

        while(1) {
                if ( serial_recv() ) {
                        open_lock();
                        PORTB = 0x00;
                }
        }

  return 0;
}