/**
  Generated Main Source File

  Company:
    Microchip Technology Inc.

  File Name:
    main.c

  Summary:
    This is the main file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs

  Description:
    This header file provides implementations for driver APIs for all modules selected in the GUI.
    Generation Information :
        Product Revision  :  PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.77
        Device            :  PIC18F25Q10
        Driver Version    :  2.00
*/

/*
    (c) 2018 Microchip Technology Inc. and its subsidiaries. 
    
    Subject to your compliance with these terms, you may use Microchip software and any 
    derivatives exclusively with Microchip products. It is your responsibility to comply with third party 
    license terms applicable to your use of third party software (including open source software) that 
    may accompany Microchip software.
    
    THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER 
    EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY 
    IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS 
    FOR A PARTICULAR PURPOSE.
    
    IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, 
    INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND 
    WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP 
    HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO 
    THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL 
    CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT 
    OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS 
    SOFTWARE.
*/

#include <pic18.h>
#include "mcc_generated_files/mcc.h"

#define _XTAL_FREQ 32768UL

/*
                         Main application
 */

uint8_t debounce(volatile uint8_t *port, uint8_t mask)
{
	uint8_t ret = 1;
	for (uint8_t i = 0; i < 20; i++)
	{
		if(*port & mask){
			ret = 0;
			break;
		}
		__delay_ms(1);
	}
	return ret;
}

void set_xtal_mode()
{
	uint8_t mode_byte = DATAEE_ReadByte(0x00);
	// Set appropriate XTAL mode
	if((SOSCPWR) && !(mode_byte & 0x01))
	{
		SOSCPWR = 0;
	}
	if(!(SOSCPWR) && (mode_byte & 0x01))
	{
		SOSCPWR = 1;
	}
}

void set_LED_mode()
{
	// Set LED according to setting
	if (SOSCPWR)
	{
		led_pin_SetLow();
	}else{
		led_pin_SetHigh();
	}
}

void poll_btn_press()
{
	if(debounce(&PORTB, _PORTB_RB3_MASK))
	{
		uint8_t mode_byte = DATAEE_ReadByte(0x00);
		mode_byte ^= 0x01;
		DATAEE_WriteByte(0x00, mode_byte);
		while(!RB3);
	}
}

void select_32k_xosc()
{
	// SOSC is not already set and is ready
	if(!((OSCCON2 & _OSCCON2_COSC_MASK) == 0x40))
	{
		// Set SOSC as new oscillator
		OSCCON1 = 0x40;
	}
}

void main(void)
{
    // Initialize the device
    SYSTEM_Initialize();
	

    while (1)
    {
		set_xtal_mode();
		set_LED_mode();
		poll_btn_press();
		select_32k_xosc();
    }
}
/**
 End of File
*/