/*
 * File:   main.c
 * Author: boos
 *
 * Created on December 10, 2019, 12:23 PM
 */

// CONFIG1
#pragma config FOSC = INTOSC    // Oscillator Selection Bits (INTOSC oscillator: I/O function on CLKIN pin)
#pragma config WDTE = OFF       // Watchdog Timer Enable (WDT disabled)
#pragma config PWRTE = OFF      // Power-up Timer Enable (PWRT disabled)
#pragma config MCLRE = OFF      // MCLR Pin Function Select (MCLR/VPP pin function is digital input)
#pragma config CP = OFF         // Flash Program Memory Code Protection (Program memory code protection is disabled)
#pragma config BOREN = OFF      // Brown-out Reset Enable (Brown-out Reset disabled)
#pragma config CLKOUTEN = OFF   // Clock Out Enable (CLKOUT function is disabled. I/O or oscillator function on the CLKOUT pin)
#pragma config IESO = OFF       // Internal/External Switchover Mode (Internal/External Switchover Mode is disabled)
#pragma config FCMEN = OFF      // Fail-Safe Clock Monitor Enable (Fail-Safe Clock Monitor is disabled)

// CONFIG2
#pragma config WRT = OFF        // Flash Memory Self-Write Protection (Write protection off)
#pragma config CPUDIV = NOCLKDIV// CPU System Clock Selection Bit (NO CPU system divide)
#pragma config USBLSCLK = 48MHz // USB Low SPeed Clock Selection bit (System clock expects 48 MHz, FS/LS USB CLKENs divide-by is set to 8.)
#pragma config PLLMULT = 3x     // PLL Multipler Selection Bit (3x Output Frequency Selected)
#pragma config PLLEN = ENABLED  // PLL Enable Bit (3x or 4x PLL Enabled)
#pragma config STVREN = ON      // Stack Overflow/Underflow Reset Enable (Stack Overflow or Underflow will cause a Reset)
#pragma config BORV = LO        // Brown-out Reset Voltage Selection (Brown-out Reset Voltage (Vbor), low trip point selected.)
#pragma config LPBOR = OFF      // Low-Power Brown Out Reset (Low-Power BOR is disabled)
#pragma config LVP = ON         // Low-Voltage Programming Enable (Low-voltage programming enabled)

#include <xc.h>

// method prototypes
unsigned char getRandomNumber ();

// global variables
static unsigned int rnd = 0;
static unsigned char t = 0, newValue1 = 0, newValue2 = 0, maxValue = 0, mean_values = 0, speed1 = 0, speed2 = 0, fade_delay = 0;
static unsigned char random_number1 = 0, random_number2 = 0, mode = 0; // 3

// useful abbreviation
#define JP_fast (!RA5)

void main(void) {
    
    // set internal oscillator to 4MHz
    IRCF0 = 1;
    IRCF1 = 0;
    IRCF2 = 1;
    IRCF3 = 1;
    
    // weak pull-up for jumper
    TRISA5 = 1;
    WPUA5 = 1;
    nWPUEN = 0;
    
    // TIMER0 settings
    
	// internal clock, no prescaler, interrupt on overflow
	TMR0CS = 0;
	PSA = 1;
	TMR0IE = 1;

	// enable global interrupts
	GIE = 1;
    
    // ADC settings
    
	// ADC sampling frequency per bit is F_osc/2
	ADCS0 = 0;
	ADCS1 = 0;
    ADCS2 = 0;
    
    // result alignment
    ADFM = 1;

	// RA4, RC0, RC1, RC2 ports as analog inputs
	TRISA4 = 1;
    TRISC0 = 1;
    TRISC1 = 1;
    TRISC2 = 1;
    ANSA4 = 1;
    ANSC0 = 1;
    ANSC1 = 1;
    ANSC2 = 1;
    
	// turn the ADC on
	ADON = 1;
    
    // PWM settings

    // ports
    TRISC5 = 0;
    TRISC3 = 0;
    
    // configure TIMER2
    PR2 = 0xff;
    T2CON = 0b100;
    
    // turn on PWM modules
    PWM1EN = 1; PWM1OE = 1;
    PWM2EN = 1; PWM2OE = 1;
    
    // main loop
    while (1) {
       
        // enable fast mode if the jumper
        // is connected to ground
        if (JP_fast) {
            mode = 0;
        } else {
            mode = 1;
        }
        
		// fast or slow?
		if (mode == 0) {
			maxValue = 200;  mean_values = 1;   fade_delay = 0;
		} else if (mode == 1) {
			maxValue = 250;  mean_values = 16;  fade_delay = 4;
		}

		// the actual animation
		if (newValue1 >= maxValue) {
			rnd = 0;
			for (t = 0; t < mean_values; t++) {
				rnd += getRandomNumber();
			}
			random_number1 = rnd / t;
			newValue1 = 0;
		}
		if (newValue2 >= maxValue) {
			rnd = 0;
			for (t = 0; t < mean_values; t++) {
				rnd += getRandomNumber();
			}
			random_number2 = rnd / t;
			newValue2 = 0;
		}
    
    }
    
    return;
    
}

// the interrupt service routine
void __interrupt () isr (void) {   

	if (TMR0IF) {
        
        // animation
		newValue1++;
        newValue2++;
		speed1++;
        speed2++;
		if (speed1 >= fade_delay) {
			if (PWM1DCH > random_number1) {
				PWM1DCH--;
			} else if (PWM1DCH < random_number1) {
				PWM1DCH++;
			}
			speed1 = 0;
		}
		if (speed2 >= fade_delay) {
            if (PWM2DCH > random_number2) {
				PWM2DCH--;
			} else if (PWM2DCH < random_number2) {
				PWM2DCH++;
			}
            speed2 = 0;
        }

		// reset interrupt flag
		TMR0IF = 0;

	}
    
}

// this method creates a random number between 0 and 240
unsigned char getRandomNumber () {
   
	unsigned char tmp = 0;

    // read channel AN3
    CHS0 = 1; CHS1 = 1; CHS2 = 0; GO = 1; while (GO);
	tmp = ADRESL & 1;
	
    // read channel AN4
    CHS0 = 0; CHS1 = 0; CHS2 = 1; GO = 1; while (GO);
	tmp += (ADRESL & 1) << 1;
	
    // read channel AN5
    CHS0 = 1; CHS1 = 0; CHS2 = 1; GO = 1; while (GO);
	tmp += (ADRESL & 1) << 2;
	
    // read channel AN6
    CHS0 = 0; CHS1 = 1; CHS2 = 1; GO = 1; while (GO);
	tmp += (ADRESL & 1) << 3;

    // multiply result by 16 to create a random number between 16 and 255
	return (tmp << 4);

}