PIC单片机内部模数转换器AD的使用方法
扫描二维码
随时随地手机看文章
#include
#define uchar unsigned char
#define uint unsigned int
__CONFIG(0x3B31);
const uchar table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,
0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
const uchar table1[]={0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,
0x87,0xff,0xef};
void delay(uint x);
void init();
void disp(uchar num1,uchar num2,uchar num3,uchar num4);
uint get_ad();
void main()
{
uint lednum;
uchar a1,a2,a3,a4;
init();
while(1)
{
lednum=get_ad();
a1=lednum/1000;
a2=lednum%1000/100;
a3=lednum%100/10;
a4=lednum%10;
disp(a1,a2,a3,a4);
}
}
void delay(uint x)
{
uint a,b;
for(a=x;a>0;a--)
for(b=110;b>0;b--);
}
void init()
{
TRISA=0x01;
TRISD=0;
PORTA=0;
PORTD=0;
ADCON0=0x41;
ADCON1=0x8e;
delay(10);
}
uint get_ad()
{
uint adval;
float advalf;
ADGO=1;
while(ADGO);
adval=ADRESH;//00000000 00000011
adval=adval<<8|ADRESL;//00000011 11111111
advalf=adval/1023.0*5.0;//==2.3843
adval=advalf*1000;
return (adval);
}
void disp(uchar num1,uchar num2,uchar num3,uchar num4)
{
PORTD=table1[num1];//显示第一个数码管
PORTA=0x20;//0010 0000
delay(2);
PORTD=table[num2];//显示第二个数码管
PORTA=0x10;//0001 0000
delay(2);
PORTD=table[num3];//显示第三个数码管
PORTA=0x08;//0000 1000
delay(2);
PORTD=table[num4];//显示第四个数码管
PORTA=0x04;//0000 0100
delay(2);
}