//stty -F /dev/ttyUSB0 clocal cread -crtscts cs8 -cstopb hup -parenb parodd -brkint -icrnl ignbrk -igncr ignpar imaxbel -inlcr inpck -istrip -iuclc -ixany ixoff -ixon bs0 cr0 ff0 nl0 -ocrnl -ofdel -ofill -olcuc -onlcr -onlret onocr -opost tab0 vt0 -crterase crtkill -ctlecho -echo -echok -echonl -echoprt -icanon -iexten -isig -noflsh -tostop -xcase time 5 min 1 38400


#define F_CPU 16000000UL

#include <avr/io.h>
#include <util/delay.h>
#include <avr/sfr_defs.h>
#include <avr/interrupt.h>

#define sbi(port, bit) (port) |= (1 << (bit))
#define cbi(port, bit) (port) &= ~(1 << (bit))

volatile uint32_t intrcount = 0;

void print (char *string){
  while (*string) {
  loop_until_bit_is_set(UCSR0A, UDRE0);
  UDR0 = *string;
  string++;
  }
  return;
}

#define BAUDRATE 38400UL
#define BAUD_PRESCALE (((F_CPU / (BAUDRATE * 16UL))) - 1)

void initUART(void){

   UCSR0B = (1 << RXEN0) | (1 << TXEN0);   // Turn on the transmission and reception circuitry
   UCSR0C = (1 << UCSZ00) | (1 << UCSZ01); // Use 8-bit character sizes

   UBRR0H = (BAUD_PRESCALE >> 8); // Load upper 8-bits of the baud rate value into the high byte of the UBRR register
   UBRR0L = BAUD_PRESCALE; // Load lower 8-bits of the baud rate value into the low byte of the UBRR register

}

void led(int light){
    if (light) sbi(PORTB, PB5);
    else cbi(PORTB, PB5);
}

void uart_putchar(char c) {
  loop_until_bit_is_set(UCSR0A, UDRE0);
  UDR0 = c;
}


void print_uint32_dec (uint32_t i) {
  unsigned long int divisor = 1000000000L;
  if (!i){
      uart_putchar('0');
      return;
  }
  do {
    if (divisor <= i) {
      uart_putchar('0' + i/divisor%10);
    }
    divisor/=10;
  } while (divisor);
}

ISR(TIMER0_OVF_vect){

    TCNT0 = 233; /* 16e6 / 64 / 24 = 10869.6 interrupts per second. */

    intrcount++;

    if (intrcount%2){
        sbi(PORTB, PB0);
        cbi(PORTB, PB1);
    }
    else {
        sbi(PORTB, PB1);
        cbi(PORTB, PB0);
    }

}

void init(void){
    sbi(DDRB, PB5); /* LED */

    cbi(DDRB,  PB0); /* dust sensor input */
    sbi(PORTB, PB0); /* activate pullup resistor */

    initUART();

    TCCR0B = 3; /* Clock/64 */
    sbi(TIMSK0, TOIE0); /*enable interrupt from timer 0*/
    sei();
    initUART();
}


uint8_t particle(void){
    return bit_is_set(PINB, PB0);
}

int main (void){
    uint32_t a, b = 0, c = 0;
    uint8_t i = 0;
    init();

    while(1){
        i++;
        c = b;
        while(!particle());
        a = intrcount;
        while(particle());
        b = intrcount;
        print_uint32_dec(b-c);
        print(" ");
        print_uint32_dec(a-c);
        print("\n");
        led(particle());
    }
    return 0;
}
