#include <avr/io.h>
#include <stdio.h>
#include <avr/sleep.h>
#include <util/delay.h>

#define led1_bm PIN3_bm
#define led2_bm PIN4_bm
#define pulse_per 2000

//PULSE_LO = PD0
//PULSE_HI = PE0

int main(void) {
  OSC.CTRL = OSC_RC32MEN_bm; // enable 32MHz clock
  while (!(OSC.STATUS & OSC_RC32MRDY_bm)); // wait for clock to be ready
  CCP = CCP_IOREG_gc; // enable protected register change
  CLK.CTRL = CLK_SCLKSEL_RC32M_gc; // switch to 32MHz clock
   
  //turn on led
  //PORTA.DIRSET = led1_bm | led2_bm;
  //PORTA.OUTSET = led1_bm;
  //PORTA.OUTSET = led2_bm;

  _delay_ms(20); //give the power supply time to come up before starting pulses

  //oscillate a lot

  //set up pulses for high side gate driver
  PORTE.DIRSET = PIN0_bm;  //set PE0 to output
  TCE0.PER = pulse_per; //set pulse frequency: 32MHz / 64 / 10000 = 50 Hz
  TCE0.CTRLB = ( TCE0.CTRLB & ~TC0_WGMODE_gm ) | TC_WGMODE_SS_gc; //single slope mode
  TCE0.CTRLB = ( TCE0.CTRLB & ~TC0_CCAEN_bm ) | TC0_CCAEN_bm; //set to output compare mode on channel C
  TCE0.CCABUF = 50;  //for now, just pulse for 50 cycles (2us each) = 100 us on time
  TCE0.CTRLA = ( TCE0.CTRLA & ~TC0_CLKSEL_gm ) | TC_CLKSEL_DIV64_gc;  //set clock divider and start
  PORTE.PIN0CTRL |= PORT_INVEN_bm; //set inverted output

  //set up pulses for low side gate driver
  PORTD.DIRSET = PIN0_bm;  //set PE0 to output
  TCD0.PER = pulse_per; //set pulse frequency: 32MHz / 64 / 10000 = 50 Hz
  TCD0.CTRLB = ( TCD0.CTRLB & ~TC0_WGMODE_gm ) | TC_WGMODE_SS_gc; //single slope mode
  TCD0.CTRLB = ( TCD0.CTRLB & ~TC0_CCAEN_bm ) | TC0_CCAEN_bm; //set to output compare mode on channel C
  TCD0.CCABUF = 50;  //for now, just pulse for 50 cycles (2us each) = 100 us on time
  TCD0.CNT = pulse_per/2; //set up 5000 cycle delay from other time = (10ms)
  TCD0.CTRLA = ( TCD0.CTRLA & ~TC0_CLKSEL_gm ) | TC_CLKSEL_DIV64_gc;  //set clock divider and start
}