/* Der Magnetfelder Detektor V0.99 */
/*Copyright (c) 2009 by James Delaney

    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/>.
*/

#include "stdlib.h" 


#include <avr/io.h>
#include <avr/interrupt.h>
#ifndef F_CPU
// define cpu clock speed if not defined
#define F_CPU 1000000
#endif
#include <util/delay.h>
volatile int theCount;
volatile int theTemp;

// remeber ledOff and on are backward because of uln2803
void ledOff(unsigned char pos)
{
	if (pos>4)
	{
		PORTB &= ~_BV(7-pos);
	}
	else
	{
		if (pos==4) { pos=7; }
		PORTA &= ~_BV(pos);
	}
}
void ledOn(unsigned char pos)
{
	if (pos>4)
	{
		PORTB |= _BV(7-pos);
	}
	else
	{
		if (pos==4) { pos=7; }
		PORTA |= _BV(pos);
	}
}
void ledToggle(unsigned char pos)
{
	if (pos>4)
	{
		PORTB ^= _BV(7-pos);
		//PORTB = 0b00000001;
	}
	else
	{
		if (pos==4) { pos=7; }
		PORTA ^= _BV(pos);
	}
}
void allOff()
{
	int lop;
	for (lop=0; lop<8; lop++)
	{
		ledOff(lop);
	}
}


int main (void)
{

	int normalValue=0;
	int scaleValue=0;
	int x,lop;
	theCount=0;
	DDRA =  0b10001111;  // 1 = output 0=input
	DDRB =  0b00000111;

	/////////76543210
	ADMUX= 0b00000100;
	ADCSRB=0b00000000;
	ADCSRA=0b00000011;

    ADCSRA |= (1 << ADEN);
	_delay_ms(500);
	ADCSRA |= (1 << ADSC);  // Start A2D Conversions
	while ((ADCSRA & (1 << ADSC))) {}
	normalValue=ADCW;

	for (x=0; x<8; x++)
	{
		ledOn(x);
		_delay_ms(100);
		ADCSRA |= (1 << ADSC);  // Start A2D Conversions
		while ((ADCSRA & (1 << ADSC))) {}
		theTemp=ADCW;		
		normalValue=(normalValue+theTemp)/2;
		ledOff(x);
	}

   for(;;)  // Loop Forever
   {
		//_delay_ms(100);
		ADCSRA |= (1 << ADSC);  // Start A2D Conversions
		while ((ADCSRA & (1 << ADSC))) {}
		theTemp=ADCW;

		if ( (theTemp>normalValue+64) || (theTemp<normalValue-32) )
		{
			if (theTemp>normalValue)
			{
				for (lop=0; lop<8; lop++)
				{
					if (lop > ((theTemp-normalValue)/32) ) ledOff(lop); // south
					else {ledOn(lop); }
				}
			}
			if (theTemp<normalValue)
			{
				for (lop=0; lop<8; lop++)
				{
					if ( lop > ((theTemp)/160) ) ledOn(lop); // north
					else {ledOff(lop); }
				}
			}
		}
		else { allOff(); }
   }
}

