⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ad1.c

📁 16单片机AD转换一般有连续转换和中断转换两种
💻 C
字号:
#include <iom16v.h>
#include <macros.h>
//#include <math.h>
#include <float.h>

#define uchar unsigned char
#define uint unsigned int
#define F_cpu 7372800

uchar Table[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};//0到9显示
uchar Data[]={0,0,0,0};
uchar time_1ms_ok=0;

/*-----------------------------------------------------------------
    延时程序计算方法
	计数个数j = 延时时间/6*晶振频率 - 1
-----------------------------------------------------------------*/
void Delay_ms(uint i)
{
 	uint j;
	while(i--)
	{
	 	j = 1228;//7.3728mhz 1ms延时
	    while(j--);
	}
}
//
void Display(unsigned int v)
{
 Data[0]=v/1000;
 v=v%1000;
 Data[1]=v/100;
 v=v%100;
 Data[2]=v/10;
 v=v%10;
 Data[3]=v;
 
 //位选高电平有效PD2-A,PD3-B,PD4-C,PD5-D;段选高电平有效PB0~6-a~b
 PORTD=0x04;//送个位
 PORTB=Table[Data[3]];
 Delay_ms(5);//延时5ms
 
 PORTD=0x08;//送十位
 PORTB=Table[Data[2]];
 Delay_ms(5);
 
 PORTD=0x10;//送百位
 PORTB=Table[Data[1]];
 Delay_ms(5);
 
 PORTD=0x20;//送千位
 PORTB=Table[Data[0]];
 Delay_ms(5);
}

//Timer0比较匹配中断服务
#pragma interrupt_handler timer0_comp_isr:20
void timer0_comp_isr(void)
{
 time_1ms_ok=1;
}

///ADC转换完成中断
#pragma interrupt_handler adc_isr:15
void adc_isr(void)
{
 uint adc_data,adc_v,temp;
 adc_data=ADCL;
 temp=ADCH;
 adc_data=(temp<<8)|adc_data;
 adc_v=adc_data*4000/1024;//输出电压放大1000倍
 Display(adc_v);
}

//系统主程序
void main (void)
{
 DDRA=0x00;
 PORTA=0x00;//AD采样端口要定义为输入,且不能使能内部上拉电阻
 //七段数码管全部点亮
 DDRB=0xff;
 PORTB=0xff;
 DDRD=0xff;
 PORTD=0xff;
 Delay_ms(1000);
 
 //T/C0初始化
 TCCR0=0x0D;//内部时钟,1024分频(7372800/1024=7.2KHz),CTC模式
 TCNT0=0x00;
 OCR0=0x07;//OCR0=7,7/7.2KHz=1ms
 TIMSK=0x02;//使能T/C0比较中断
 
 //ADC初始化
 ADMUX=0x40;//参考电压源AVCC,ADC0单端输入
 SFIOR&=0x1f;
 SFIOR|=0x60;//T/C0比较匹配触发源
 ADCSRA=(1<<ADEN)|(1<<ADATE)|(1<<ADIE)|(1<<ADPS2)|(1<<ADPS1)|(0<<ADPS0);
 //ADC允许,自动触发转换,ADC转换中断允许,ADCclk=115.2kHz
 
 SEI();
 
 while(1)
 {
  /*if(time_1ms_ok)
  {
   time_1ms_ok=0;
  }*/
 }
} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -