/*
 * HID.c
 *
 * Created: 14.04.2021 10:47:37
 *  Author: vstrasil
 */ 
#include "Header/HID.h"

uint8_t LED_activ = 0b00000000;
uint8_t LED_prev = 0b00000000;
uint8_t LED_rshift = 0b10000000;
uint8_t LED_lshift = 0b00001000;

uint8_t dip1 = 0;
uint8_t dip2 = 0;
uint8_t dip3 = 0;


void hid_init(void){
	PORTC.DIR = 0b11111000;
	PORTD.DIR = 0b00000000;
	
	PORTD.PIN4CTRL = (PORT_OPC_PULLDOWN_gc|PORT_ISC_RISING_gc);
	PORTD.PIN5CTRL = (PORT_OPC_PULLUP_gc|PORT_ISC_RISING_gc);
	PORTC.PIN2CTRL = (PORT_OPC_PULLUP_gc|PORT_ISC_RISING_gc);
	PORTC.PIN1CTRL = (PORT_OPC_PULLUP_gc|PORT_ISC_RISING_gc);
	PORTC.PIN0CTRL = (PORT_OPC_PULLUP_gc|PORT_ISC_RISING_gc);
}

void led_on(uint8_t aLED){
	LED_activ = LED_prev | aLED;
	PORTC.OUT = LED_activ;
	LED_prev = LED_activ;
}

void led_off(uint8_t aLED){
	LED_activ = LED_prev & ~aLED;
	PORTC.OUT = LED_activ;
	LED_prev = LED_activ;
}

uint8_t button(uint8_t aBUTTON){
	if (PORTD.IN & aBUTTON)
	{
		return 1;
	} 
	else
	{
		return 0;
	}
}

int dip(){
	if (PORTC.IN & DIP1)
	{
		dip1 = 0;
	}
	else
	{
		dip1 = 1;
	}
	if (PORTC.IN & DIP2)
	{
		dip2 = 0;
	}
	else
	{
		dip2 = 2;
	}
	
	if (PORTC.IN & DIP3)
	{
		dip3 = 0;
	}
	else
	{
		dip3 = 4;
	}
	
	return dip1 + dip2 + dip3;
	
}

void clock_init(){
	OSC.CTRL |=  OSC_RC32MEN_bm | OSC_RC32KEN_bm;  
	while (!(OSC.STATUS & OSC_RC32KRDY_bm ));        
	while (!(OSC.STATUS & OSC_RC32MRDY_bm ));        
	DFLLRC32M.CTRL = DFLL_ENABLE_bm ;              
	CCP = CCP_IOREG_gc;                                 
	CLK.CTRL = CLK_SCLKSEL_RC32M_gc;            
	OSC.CTRL &= ~OSC_RC2MEN_bm;       
}
void timer_init(){
	TCC0.CTRLB = TC_WGMODE_SS_gc;


	TCC0.CTRLA = TC_CLKSEL_DIV4_gc; 

	TCC0.PER   = 8000;

	TCC0.INTCTRLA = TC_OVFINTLVL_LO_gc;

	//////////////////////////////////////////////////////

	TCD0.CTRLB = TC_WGMODE_NORMAL_gc;

	TCD0.CTRLA = TC_CLKSEL_EVCH0_gc;

	TCD0.PER   = 60000;

	TCD0.CTRLD = TC_EVACT_CAPT_gc | TC0_EVDLY_bm | 0X08;
	EVSYS.CH0MUX = EVSYS_CHMUX_TCC0_OVF_gc;

}
long timer_act(){
		return TCD0.CNT;
}
