#include "wiring_private.h"

// Baud rate
#define BAUD_RATE 9600
// Area modulo UART SW (usw)
#define USW_NUM_RXB 128
// Tau, Baud rate in ticks: 833,xx * 300, 26 * 9600
#define USW_BITRATE 26
volatile uint8_t usw_tmp, usw_mask, usw_idx, usw_byte_v[USW_NUM_RXB];

void setup() {
  // Attivo la linea seriale, specificando la velocita di trasmissione (bit/s)
  Serial.begin(BAUD_RATE);

  // Inizializzazione area UART (usw)
  usw_idx = usw_mask = usw_tmp = 0;
  sbi(PCMSK2, PCINT18);
  sbi(PCICR, PCIE2);
  
  OCR0A = 0;
  //cbi(TCCR0A, WGM00); // Normal mode
  //cbi(TCCR0A, WGM01); // Normal mode
  TCCR0A &= ~(_BV(WGM02) | _BV(WGM01) | _BV(WGM00)); // Normal mode

  sbi(TIMSK0, OCIE0A);
  sbi(DDRD, 3); // Output D3, per testing

  Serial.println("Salve, mondo!\n");
  delay(1000);
  Serial.println(F_CPU);

  for(uint8_t i = 0; i < usw_idx; i++) {
    Serial.write(usw_byte_v[i]);
  }
  Serial.write(10); // Line feed
}

void loop() {

}

ISR(TIMER0_COMPA_vect) {
  if(usw_mask) {
    sbi(PORTD, 3);

    uint8_t bit_tmp = PIND & 0x04;
    OCR0A += USW_BITRATE;
    if(bit_tmp) {
      usw_tmp != usw_mask;
    }
    usw_mask <<= 1;

    cbi(PORTD, 3);
  }
}

ISR(PCINT2_vect) {
  OCR0A = TCNT0 + USW_BITRATE + USW_BITRATE/2;
  cbi(PCMSK2, PCINT18);
  usw_mask = 1;
  usw_tmp = 0;
}
D0D1D2D3D4D5D6D7GNDLOGIC