/*********************************************\
| FOUNTAIN CENTER CONSOLE CONTROLLER FIRMWARE |
| v.01                                        |
| Copyright 2008 Zack Anderson and RJ Ryan    |
| http://web.mit.edu/zacka/www/fountain.html  |
|                                             |
| This simple program monitors and controls   |
| the water jet valves, the relief valve, and |
| the halogen lights.                         |
|                                             |
| Serial over USB input                       |
| 1-Byte Protocol:                            |
| 5 LSBs control water valve relays &         |
| 6th bit controls halogen lights relay       |
| 2 MSBs are high for a valid signal          |
|                                             |
| The circuit has pullups on pins a0-a5 & c1  |
| Compile with the CCS C Compiler             |
\*********************************************/

#include <18F2450.h>

#define CONTROL_MASK 63 // selects the lower order six bits
#define CHECK_MASK 192 // 2 MSBs asserted
#define LED PIN_C0

#fuses HSPLL,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL5,CPUDIV1,VREGEN
#use delay(clock=48000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)

void initialize_valves() {
	output_low(PIN_B7); // turn on relief valve
	output_high(PIN_B0); // turn off all others
	output_high(PIN_B1);
	output_high(PIN_B2);
	output_high(PIN_B3);
	output_high(PIN_B4);
	output_high(PIN_B5);
}

void flashLED() {
	output_low(LED);
	delay_ms(20);
	output_high(LED);
}

void main() {
	char control_input;
	delay_ms(50);
	initialize_valves();
	delay_ms(100);
	output_high(LED); // turn off LED
	control_input = 192;

	while(1) {
		if (kbhit()) {
			control_input = ~getc();
			// test to see if valid signal is received
			if ((control_input & CHECK_MASK) == 0) {
			// assert neccessary pins on PIC
				output_b(control_input & CONTROL_MASK);
				// check if relief valve is required
				if ((~control_input & CONTROL_MASK) == 0)
					output_low(PIN_B7); // turn on rv
				else output_high(PIN_B7);
				flashLED();
			}
		}
		// operate on manual mode switches
		if (!input(PIN_A1)) {
			output_high(PIN_B7);
			output_low(PIN_B0);
			output_high(PIN_B0);
		}
		if (!input(PIN_A2)) {
			output_high(PIN_B7);
			output_low(PIN_B1);
			output_high(PIN_B1);
		}	
		if (!input(PIN_A3)) {
			output_high(PIN_B7);
			output_low(PIN_B2);
			output_high(PIN_B2);
		}
		if (!input(PIN_A4)) {
			output_high(PIN_B7);
			output_low(PIN_B3);
			output_high(PIN_B3);
		}
		if (!input(PIN_A5)) {
			output_high(PIN_B7);
			output_low(PIN_B4);
			output_high(PIN_B4);
		}	
	}
}
