// Oscilloscope firmware, Roman Pavelka, 2011
// written for atmega8

#define F_CPU 16000000
#define BAUD 1000000
//#define MYUBRR F_CPU/8/BAUD-1
#define MYUBRR 1

#include "./libs/usart.h"
#include "./libs/spi.h"

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

#define LEN 100
uint8_t data[2*LEN];

void measure(void);
void send(void);


int main (void) {
  USART_Init(MYUBRR);

  DDRB  =  0b00100100; //SCK, SS out
  PORTB =  0b00000000; // CONV low

  SPI_MasterInit();

  sei();

  while(1) {}

  return 0;

}


void measure(void) {
  uint8_t i;

  for(i=0;i<LEN;i++) {
    PORTB |= 0b00000100;
    _delay_us(4);
    PORTB &= 0b11111011; //one conversion

    data[2*i] = SPI_MasterTransmit(0x0);
    data[2*i+1] = SPI_MasterTransmit(0x0);
  }
}

void send(void) {
  uint8_t i;

  for(i=0;i<LEN;i++) {

/*    USART_Transmit_uint16(data[i]); //ASCII transfer
    USART_Transmit('\n');*/

    USART_Transmit(data[2*i]); //Binary transfer
    USART_Transmit(data[2*i+1]); 
//    USART_Transmit('\n');

  }
}


ISR(USART_RXC_vect) {
  char data; 

  data=UDR; //must be read to untrigger interupt

  if (data=='m') {
    measure();
    send();
  }
}