#include <stdio.h>
#include <htc.h>
#include "usart.h"

#define _XTAL_FREQ 32000000
#define REDPIN RC1
#define GREENPIN RC2
#define BLUEPIN RC3

__CONFIG(FOSC_INTOSC & WDTE_OFF & MCLRE_ON & CP_OFF & CPD_OFF & BOREN_ON & PWRTE_OFF & CLKOUTEN_OFF); // Program config word 1
__CONFIG(PLLEN_ON & STVREN_ON & BORV_HI & LVP_OFF & VCAPEN_OFF); // Program config word 2

unsigned char red, green, blue;
unsigned char tmr0_period = 0;
unsigned char c = 0;

void main(void) {
	unsigned char input;

	// OSCCON 5.3 66. o.
	OSCCON = 0b11110010; // HFINTOSC + 4xPLL = 32MHz
	
	TRISC1 = TRISC2 = TRISC3 = 0; // RC1, RC2, RC3 Output
	
	red = green = blue = 0;
	REDPIN = GREENPIN = BLUEPIN = 0;

	ADCON0bits.CHS = 0b00011101; // AD Channel: Temperature Reference
	ADON = 0; // ADC OFF
	DACEN = 0; // DAC OFF
	C1ON = C2ON = 0; // Comparator OFF
	
	INTCON = 0;	// purpose of disabling the interrupts.

	init_comms();	// set up the USART - settings defined in usart.h

	TMR0CS = 0;
	PSA = 0;
	OPTION_REGbits.PS = 0b00000111; // Prescaler: 256
	TMR0IF = 0;
	TMR0IE = 1;
	GIE = 1;
	
	while (1) {
		input = getch();
		if (input == 1) {
			// Adott szín beállítása
			red = getch();
			green = getch();
			blue = getch();
		} else if (input == 2) {
			// Automata üzzemmód
		} else if (input == 3) {
			// Hőmérséklet lekérdezés
		}
	}
}

void interrupt timer0_isr(void) {
	if (tmr0_period) {
		if (c < red) {
			REDPIN = 1;
		} else {
			REDPIN = 0;
		}
		if (c < green) {
			GREENPIN = 1;
		} else {
			GREENPIN = 0;
		}
		if (c < blue) {
			BLUEPIN = 1;
		} else {
			BLUEPIN = 0;
		}
		c++;
	}
	tmr0_period = !tmr0_period;
	TMR0IF = 0; // Megszakításjelző bit törlése
}
