Fio Main

//Fiber Optic Chandelier Main Board
//Written by Bill Heaster
//http://ApexLogic.net

//////////
//Define variables
//////////


//pwm pins that control the mosfets
const int blue = 9;
const int green = 10;
const int red  = 11;

//using an array to hold the data for the pwm
int colors [] ={0,0,0};
int colorsOld [] ={0,0,0};

//serial byte in
int inByte = 0;

//this will trigger the auto cycle 
bool cycle = false;
bool startup = true;

//time keeping
long startTime = 0;
long interval = 100000;

void setup()
{
	//Set pinmode for mosfets
	pinMode(blue, OUTPUT);
	pinMode(green, OUTPUT);
	pinMode(red,OUTPUT);
	
	//begin xbee connection
	Serial.begin(9600);
	
}

//Saves the current packet into a temp array for later comparrison
void pushColor()
{
	for(int cnt=0; cnt<2; cnt++)
	{
		colorsOld[cnt] = colors[cnt];
	}
}


bool newData()
{	
	int tick = 0;
	for(int cnt =0; cnt<2; cnt++)
	{
		if(colorsOld[cnt] == colors[cnt])
		{
			tick++;
		}
	}
	//if all the colors have not been changed
	if(tick == 3)
	{
		return false;
	}
	else
	{
		return true;
	}
	
}

bool timeOut()
{
	unsigned long current = millis();
	
	if(current - startTime > interval)
	{
		startTime = millis();
		return true;
	}		
	else
	return false;
}

void cycleColors()
{
	
	//an array that we will manipulate to change colors
	int cycle[] = {0,0,0};	
	float frequency = .3;
	
	//using a sine wave to cycle through the colors. 
	for (int i = 0; i < 32; ++i)
	{
	        cycle[0] = sin(frequency*i + 0) * 127 + 128;
		cycle[1] = sin(frequency*i + 2) * 127 + 128;
		cycle[2] = sin(frequency*i + 4) * 127 + 128;

		analogWrite(red, cycle[0]);
		analogWrite(blue, cycle[1]);
		analogWrite(green, cycle[2]);
		delay(250);
	}
		
}

void loop()
{	
		//while there is serial data on the line
		while (Serial.available()>0)
		{
			inByte = Serial.read();
			
			//if we are at the beginning of a packet		
			if(inByte == '#')
			{	
				//fill the array with the received bytes
				for(int cnt = 0; cnt <2; cnt++)
				{	
					colors[cnt] = Serial.read();				
				}
				
				//take the received data and use it to set the PWM wave
				analogWrite(red, colors[0]);
				analogWrite(green, colors[1]);
				analogWrite(blue, colors[2]);
				
				if(startup ==true)
				{	
					//if we have received at least one good packet we can turn startup mode off
					startup =false;					
									
				}
				//set the current readings into the "old" array
				pushColor();
			}
			
			//Now we will check to see if the data is old or not
			if(startup == false) 
			{
				//if it is old tell the controller to stop sending data. start color cycle.
				if(newData()== false)
				{	
					if(timeOut() ==  true)
					{					
      					   Serial.print('A');
      					   cycleColors();
					}
				}
			}
			
		}//endwhile
	
	
}

Leave a Reply