#ifndef _MEGA32A_INCLUDED_
#include <mega32a.h>
#endif

#ifndef _MATH_INCLUDED_
#include <math.h>
#endif

#ifndef _DELAY_INCLUDED_
#include <delay.h>
#endif

#ifndef _MEGA_LIGHT_INCLUDED_
#define _MEGA_LIGHT_INCLUDED_
#endif

#pragma used+

int _LDR_N__;
int _FIRST__;
int _LAST__;
unsigned int adc_data[8];



// Voltage Reference: AREF pin
#define ADC_VREF_TYPE ((0<<REFS1) | (0<<REFS0) | (0<<ADLAR))

// ADC interrupt service routine
// with auto input scanning
interrupt [ADC_INT] void adc_isr(void)
{
static unsigned char input_index=0;
// Read the AD conversion result
adc_data[input_index]=ADCW;
// Select next ADC input
if (++input_index > (_LAST__-_FIRST__))
   input_index=0;
ADMUX=(_FIRST__ | ADC_VREF_TYPE)+input_index;
// Delay needed for the stabilization of the ADC input voltage
delay_us(10);
// Start the AD conversion
ADCSRA|=(1<<ADSC);
}

int LDR_init(unsigned int _N,unsigned int _FIRST_PIN,unsigned int _LAST_PIN)
{
if(_N>8)return 1;
if(_FIRST_PIN>8)return 1;
if(_LAST_PIN>8)return 1;

_LDR_N__=_N;
_FIRST__=_FIRST_PIN-1;
_LAST__=_LAST_PIN-1;

// ADC initialization
// ADC Clock frequency: 125.000 kHz
// ADC Voltage Reference: AREF pin
// ADC Auto Trigger Source: Free Running
ADMUX=_FIRST__ | ADC_VREF_TYPE;
ADCSRA=(1<<ADEN) | (1<<ADSC) | (1<<ADATE) | (0<<ADIF) | (1<<ADIE) | (1<<ADPS2) | (1<<ADPS1) | (0<<ADPS0);
SFIOR=(0<<ADTS2) | (0<<ADTS1) | (0<<ADTS0);

// Global enable interrupts
#asm("sei")

return 0;
}

float LDR_res(int _LDR_NUMBER_)
{
 float adcvolt,res,light;

 if(_LDR_NUMBER_>_LDR_N__)return 1;  
 
 switch(_LDR_NUMBER_) 
 {
  case 1:{adcvolt=(adc_data[0]*5.0)/1023.0;res=(10*(5-adcvolt))/adcvolt;light=pow(10,(2.12-log10(res))/0.78); return light; }
  case 2:{adcvolt=(adc_data[1]*5.0)/1023.0;res=(10*(5-adcvolt))/adcvolt;light=pow(10,(2.12-log10(res))/0.78); return light; }
  case 3:{adcvolt=(adc_data[2]*5.0)/1023.0;res=(10*(5-adcvolt))/adcvolt;light=pow(10,(2.12-log10(res))/0.78); return light; }
  case 4:{adcvolt=(adc_data[3]*5.0)/1023.0;res=(10*(5-adcvolt))/adcvolt;light=pow(10,(2.12-log10(res))/0.78); return light; }
  case 5:{adcvolt=(adc_data[4]*5.0)/1023.0;res=(10*(5-adcvolt))/adcvolt;light=pow(10,(2.12-log10(res))/0.78); return light; }
  case 6:{adcvolt=(adc_data[5]*5.0)/1023.0;res=(10*(5-adcvolt))/adcvolt;light=pow(10,(2.12-log10(res))/0.78); return light; }
  case 7:{adcvolt=(adc_data[6]*5.0)/1023.0;res=(10*(5-adcvolt))/adcvolt;light=pow(10,(2.12-log10(res))/0.78); return light; }
  case 8:{adcvolt=(adc_data[7]*5.0)/1023.0;res=(10*(5-adcvolt))/adcvolt;light=pow(10,(2.12-log10(res))/0.78); return light; }
 }
}

#pragma used-
