我正在制作一些测量环境光并关闭或打开灯开关的系统。为此,我必须使用 Atmega 微 Controller 。光测量是使用 LDR 完成的。 LDR 始终输出模拟值,我必须使用 AVR 的 ADC 功能将其转换为数字值。我对微 Controller 编程了解甚少。我写了一些代码,但我不知道如何使用 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;
}
关于c - AVR 模数转换 Atmega32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33728188/