AVR 模数转换 Atmega32

AVR Analog to digital conversion Atmega32

我正在制作一些系统来测量环境光并关闭或打开电灯开关。为此,我必须使用 Atmega 微控制器。光测量是使用 LDR 完成的。 LDR 始终输出模拟值,我必须使用 AVR 的 ADC 功能将其转换为数字值。我对微控制器编程只有一点了解。我写了一些代码,但我不知道如何使用 AVR 打开继电器开关。

这是我的代码

#ifndef F_CPU
#define F_CPU 8000000UL
#endif

#include <avr/io.h>
#include <stdlib.h>
#include <avr/interrupt.h>


int main(void)
{

    ADCSRA |= 1<<ADPS2;
    ADMUX |= 1<<ADLAR;
    ADCSRA |= 1<<ADIE;
    ADCSRA |= 1<<ADEN;
    sei();
    ADCSRA |= 1<<ADSC;
    while(1)
    {


    }
}   

ISR(ADC_vect)
{

    char adcres[4];
    itoa (ADCH, adcres, 10);

    PORTC=0x01; // Turn ON relay switch

    ADCSRA |= 1<<ADSC;
}

我想使用附加的 LDR 测量模拟值并将其转换为数字值。然后在一些每个定义的数字继电器应该打开并且

我需要这样的东西

lux = ldr_digital_value

if (lux > 5 )
   { PORTC=0x00; }
else
   { PORTC=0x01; }

我该怎么做?

假设一个ATmega8(avrs之间有一些差异)

#ifndef F_CPU
#define F_CPU 8000000UL
#endif

#include <avr/io.h>
#include <stdlib.h>
#include <avr/interrupt.h>

volatile unsigned char lux=0; // the trick is the volatile.

int main(void)
{

    ADCSRA = 1<<ADPS2; //slowest clock, ok
    ADMUX  = 1<<ADLAR; // you want 8 bit only? also channel 0 selected and external VREF.
    // I suggest you to use Internal AVCC or internal 2.56V ref at first
    ADCSRA |= 1<<ADIE; // with interrupts wow!
    ADCSRA |= 1<<ADEN; // enable!
    sei();
    ADCSRA |= 1<<ADSC; // start first convertion
    while(1)
    {
         if (lux > 5 ) //please choose an appropiate value.
            { PORTC=0x00; }
         else
            { PORTC=0x01; }

    }
}   

ISR(ADC_vect)
{    
    lux =ADCH;    
    ADCSRA |= 1<<ADSC;
}