#include "main.hpp"
#include "delay.h"
#include "deviceSetup.h"
#include "usart.h"
#include "ascii.h"
#include "timer.h"

void timer_test(timerNo_t timer, pinNo_t pin)
{
	
	timerInitCounter(timer, 4000, 999, downCounting); 
	timerSart(timer);

	for(int i = 0; i < 10 ; i++)
	{
		while(!timerGetUpdateInterrupt(timer));
		timerClearUpdateInterrupt(timer);
		pinToggle(pin);
	}
		pinWrite(pin,0);
}

void timer_capture_compare_test(timerNo_t timer)
{
	uint16_t i = 0;
	timerInitCounter(timer, 100, 99, downCounting); 
	// We use pin PA3 (Arduino header A2)
	//timerInitOutputCompare(timer, toggle, 4, pinA3, 2,0, 300);
	timerInitOutputCompare(timer, pwm_normal, 2, pinB3, 2,0, 900);
	timerSart(timer);

	while(1){
		delayMs(200);
		timerSetCounterCompareValue(timer, 2, i);
		i += 10;
		if(i>99) i = 0;
	}
}


int main(int argc, char *argv[])
{
	uint8_t i = 0;
	// making array with all available timers	
	timerNo_t timers[MAX_TIMER_CHANNEL_COUNT] = {timer_1, timer_2, timer_3, timer_14, timer_16, timer_17}; 


	delayInitMs(8000000, 1000); // Clock Freq and Divider for ARM library 

	
	pinConfig(pinB3, output, pushPull, def_res, def_speed);
	pinConfig(pinA0, input, def_stage, pullDown, def_speed);	
	
	setupInit(); // This is the sescond call of System init the assebly start code is calling it before the main.	
	usartInit(	usart2, 
				pinA2, 
				pinA15,
				115200,
				eight, 
				NO_PARITY_CTRL,
				noFlowControl); 

	//clears screen and send the wellcome messgae
	print_Usart(usart2, ASCII_clear); 
	print_Usart(usart2, const_cast<char *>("Wellcome to our KED project\n\r")); 
	

	//blinks 10 times to indicate the sicsessfull init if the device
	for(i = 0 ; i < 10 ; i++)
	{
		delayMs(100); 
		pinToggle(pinB3);
		delayMs(100); 
	}
	
	pinWrite(pinB3,0);


	timer_capture_compare_test(timer_2);
	print_Usart(usart2, const_cast<char *>("All is working fine \r\n")); 

	while(1)
	{
	}
	
	return 1;
}


