/*
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#define DEBUG 0
#define LDR_COUNT 6

int calibrationValue = 0;
int LDR[LDR_COUNT];

void updateLdrsValues(){
	int i;
	for( i = 0; i < LDR_COUNT; i++ ){
		LDR[i] = analogRead( i );
	}
}

void calibrateLdrs(){
	int i;
	int aux = 0;
	updateLdrsValues();
	for( i = 0; i < LDR_COUNT; i++ ){
		aux += LDR[i];
	}
	calibrationValue = aux / LDR_COUNT + 50;
}

void setup(){
	Serial.begin( 9600 );
	calibrateLdrs();
}

byte encodeData(){
	byte info = B0;
	int i;
	updateLdrsValues();
	for( i = 0; i < LDR_COUNT; i++ ){
		if( LDR[i] < calibrationValue ){
			info = info | ( B1 << i );
		}
	}
	return info;
}

void showData(){
	Serial.print( "----------\nCalibration: " );
	Serial.println( calibrationValue );
	Serial.print( "LDRs values: | " );
	int i;
	for( i = 0; i < LDR_COUNT; i++ ){
		Serial.print( LDR[i] );
		Serial.print( " | " );
	}
	Serial.print( "\nByte: " );
	Serial.println( encodeData(), DEC );
}

void loop(){
	if( DEBUG )
		showData();
	else
		Serial.write( encodeData() );
	delay( 500 );
}