下面这个程序是靠T0的T/C0比较匹配中断为ADC触发源.
把ADC转换的结果显示到LED上。
以下是程序:/*
* GccApplication20.c
*
* Created: 2014-9-12 20:02:00
* Author: Administrator
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#define uchar unsigned char
#define uint unsigned int
#define ulong unsigned long
uchar tab[]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8, //共阳极LED 0~F的段码
0x80,0x90,0x88,0x83,0xC6,0xA1,0x86,0x8E};
//uchar dis_buff[4]={0,0,0,0};
uchar cnt;
uint adc_v;
uchar val1,val2,val3,val4;
uchar m,n;
uint adc_data;
void delay(uint k) //延时约0.1ms
{
for(m=0;m<k;m++)
{
for(n=0;n<114;n++);
}
}
//interrupt [TIM0_COMP] void timer0_comp_isr(void) // T/C0比较匹配中断服务
ISR(TIMER0_COMP_vect)
{
cnt=0x01;
}
//interrupt [ADC_INT] void adc_isr(void) // ADC转换完成中断服务
ISR(ADC_vect)
{
adc_data=ADCW; //读取ADC置换结果
adc_v=(ulong)adc_data*5000/1024; //换算成电压值
}
void display(void)
{
val1=adc_v/1000;
val2=(adc_v/100)%10;
val3=(adc_v/10)%10;
val4=adc_v%10;
PORTD=0x01;
PORTC=tab[val1];
//PORTC.7=0; //小数点
PORTC &=~(1<<7);
delay(10);
PORTD=0x02;
PORTC=tab[val2];
delay(10);
PORTD=0x04;
PORTC=tab[val3];
delay(10);
PORTD=0x08;
PORTC=tab[val4];
delay(10);
}
int main(void)
{
DDRA=0x00; //模拟量由PA0输入
PORTA=0x00;
DDRC=0xFF;
PORTC=0xFF; //PORTC端口与LED段码相连
DDRD=0xFF;
PORTD=0xFF;
TCCR0=0x0B; // 内部时钟,64分频(8M/64=125KHz),CTC模式
TCNT0=0x00;
OCR0=0xF9; // OCR0 = 0xF9(249),(249+1)/125=2ms
TIMSK=0x02; // 允许T/C0比较中断
ADMUX=0x40; // 参考电源AVcc、ADC7单端输入
SFIOR&=0x1F;
SFIOR|=0x60; // 选择T/C0比较匹配中断为ADC触发源
ADCSRA=0xAE; // ADC允许、自动触发转换、ADC转换中断允许、ADCclk=125Kz
//#asm("sei") // 开放全局中断
sei();
while (1)
{
if (cnt==0x01)
{
display(); // LED扫描显示
cnt=0x00;
}
}
}
|