#include "main.h"
#include "spi.h"
#include "muxer.h"

uint8_t foo;
uint16_t bar;
uint16_t timertmp;
uint16_t temperatures[4];


void baz() {
  foo++;
}

/* pinout
 * - i2c:
 *		C5
 *		C4
 * - multiplexer:
 *		C3: inhibit
 *		C0-C2: muxer select
 *
 *
 * amp 0 is on muxer channel 2
 */

void hardinit() {
  /* initializes the hardware */

  // enable softtimer isr
  TCCR1A = _BV(WGM10);
  TCCR1B = _BV(WGM12) | _BV(CS11); // clk/8 prescaler, 4kHz PWM-freq.
  TIMSK1 |= _BV(TOIE1);

  spi_init();

  muxer_init();
  // mpcadc_init(0xdeadbeef);

  sei();
}

void softinit() {
	// TODO: to prevent evil random access and stuff?
	temperatures[0] = 0;
	temperatures[1] = 0;
	temperatures[2] = 0;
	temperatures[3] = 0;
	
	//test values
	foo = 0x87;
	bar= 0xfafa;

}


int __attribute__((noreturn)) main(void) {
  hardinit();
  softinit();

  for(;;){
    
    SOFTTIMER(1,500) {
		// do_stuff();
		// muxer_set(some-next-channel);
		// if(mcpadc_has_new_data()) {
		//    temperatures[some-next-channel] = mpcadc_get_data();
		// }
    }

  }
}



ISR(TIMER1_OVF_vect,ISR_NOBLOCK){
    timertmp=timer1_acc;
    timertmp++;

    /* the ATOMIC is acutally only needed if timer1_acc is never read from an ISR, which
     * is probably the case.
     * ATOMIC_FORCEON: the ISR_NOBLOCK sets sei() a few cycles before.
     */
    ATOMIC_BLOCK(ATOMIC_FORCEON){ 
        timer1_acc=timertmp;
    }

}
