/* -----------------------------------------------------------------------
 * Title:    Analog read example (Analog input change led brightness)
 * Author:   Samuel St-Aubin (samuel.st-aubin@sympatico.ca)
 * Date:     12.12.2007
 * Hardware: ATtiny13v
 * Software: WinAVR 20060421
 * -----------------------------------------------------------------------*/
 
#define F_CPU 9600000               // Define software reference clock for delay duration
 
#include <avr/io.h>
#include <util/delay.h>
 
#define LED PB2                     // Define led ext output pin on PB2

int i;                              // 8 bits integer

unsigned int analogRead() {
  unsigned int low, high;
  
  ADCSRA |= (1 << ADEN);          // Analog-Digital enable bit
  ADCSRA |= (1 << ADSC);          // Discard first conversion

  while (ADCSRA & (1 << ADSC));  // wait until conversion is done

  ADCSRA |= (1 << ADSC);         // start single conversion

  while (ADCSRA & (1 << ADSC))  // wait until conversion is done

  ADCSRA &= ~(1<<ADEN);             // shut down the ADC

  //----------Show ADCH Byte in Led variable brightness indicator---------
	low = ADCL;
  high = ADCH;
  
  return (high << 8) | low;
}

int value;
int last_value;

#define THRESHOLD 2

unsigned int motion() {
  int motion;
  value = analogRead();
  motion = value - last_value;
  if (motion < 0)
    motion = -motion;
  last_value = value;
  return (unsigned int) motion;
}

void analogInit() {
  // Analog read initialization.
  ADCSRA |= (1 << ADEN) |          // Analog-Digital enable bit
            (1 << ADPS1) |         // set prescaler to 8    (clock / 8)
            (1 << ADPS0);          // set prescaler to 8    (clock / 8)

  ADMUX |= // (1 << ADLAR) |         // AD result store in (more significant bit in ADCH)
            (1 << MUX1);           // Choose AD input AD2 (BP 4)
}

int main(void)
{
  unsigned int m;
  analogInit();

  DDRB |= (1 << LED);              // Set output direction on LED
    
  PORTB &= ~(1 << LED);
  
  motion(); // call one time to initialize the values
  
  for (;;)
  {
      m = motion();
      if (m > THRESHOLD) {
          PORTB |= (1 << LED);
          _delay_ms(250);
      }
      PORTB &= ~(1 << LED);
  }
  
  return 0;
}
