//insert gpl code headers here
//macro cycle:
//setup: intitalise, read all devices and send, wait for gps acquisition
//loop: null
//interrupt: 
//1)read in ADC's (direct port sampling)
//2)read out GPS timestamp (TIMEMARK) and position (UART or SPI)
//3)read out extra data (temp, pressure, humidity) (I2C)
//3.1)maybe read some more out of the adc's (3 samples?) direct port sampling, cycle clock
//4)apply high level trigger (threshold?) test.
//5)if test is positive then send the output to Pi over rx/tx port 1
//6)return to waiting state

//define pins for SPI
#define DATAOUT 11//MOSI
#define DATAIN  12//MISO 
#define SPICLOCK  13//sck
#define SLAVESELECT 10//ss


//opcodes
#define WREN  6
#define WRDI  4
#define RDSR  5
#define WRSR  1
#define READ  3
#define WRITE 2


byte eeprom_output_data;
byte eeprom_input_data=0;
int tempsensor =0;
int pressuresensor =0;
int humiditysensor =0;
byte clr;
int address=0;
//data buffer
char buffer [128];


int pin = 13;
volatile int state = LOW;
byte adcpt1, adcpt2, adcpt3;

//directly read ports:
//Port F (8 bits) and Port K (8 bits) and Port A (8 bits) = 24 bits total
//set into two 

void setup()
{
  pinMode(pin, OUTPUT);
  attachInterrupt(0, blink, CHANGE);
  Serial.begin(9600);

//read SPI eeprom
  address = 0; //set the address of the temp sensor here
  tempsensor = read_eeprom(address);
  address = 1; //set the address of the pressure sensor here
  pressuresensor = read_eeprom(address);
  address = 2; //set the address of the humidity sensor here
  humiditysensor = read_eeprom(address);
}

void loop()
{
  digitalWrite(pin, state);
}

void blink()
{
  state = !state;
  adcpt1= PINF;
  adcpt2= PINK;
  adcpt3= PINA;
  Serial.println("done");
    
}

char spi_transfer(volatile char data)
{
  SPDR = data;                    // Start the transmission
  while (!(SPSR & (1<<SPIF)))     // Wait the end of the transmission
  {
  };
  return SPDR;                    // return the received byte
}

byte read_eeprom(int EEPROM_address)
{
  //READ EEPROM
  int data;
  digitalWrite(SLAVESELECT,LOW);
  spi_transfer(READ); //transmit read opcode
  spi_transfer((char)(EEPROM_address>>8));   //send MSByte address first
  spi_transfer((char)(EEPROM_address));      //send LSByte address
  data = spi_transfer(0xFF); //get data byte
  digitalWrite(SLAVESELECT,HIGH); //release chip, signal end transfer
  return data;
}

