我正在制作一些系统来测量环境灯,并关闭或打开电灯开关。要做到这一点,我必须使用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; }我怎么能这么做?
发布于 2015-11-17 05:45:24
假设一个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;
}https://stackoverflow.com/questions/33728188
复制相似问题