STC12C5A60S2單片機(jī)的10位AD轉(zhuǎn)換程序
#include"stc12c5a.h" //頭文件在STC公司主頁(yè)上下載
#include"stdio.h"
#include"intrins.h"
//------------------------------------------------------------------------------
void AD_init();
void serial_init();
void delay(unsigned int a);
float AD_work(unsigned char channel);
unsigned int AD_get(unsigned char channel);
//------------------------------------------------------------------------------
void main()
{
AD_init(); //A/D轉(zhuǎn)換初始化
serial_init(); //串口初始化
while(1)
{
unsigned char i;
for(i=0;i<8;i++) //循環(huán)發(fā)送P1.0-P1.7的轉(zhuǎn)換數(shù)值
{
TI=1; //使用printf函數(shù)前須先將發(fā)送標(biāo)志位TI置1
printf("The P1.%bd voltage is %f",i,AD_work(i));
TI=0;
delay(1000); //延時(shí)約1s
}
}
}
//------------------------------------------------------------------------------
unsigned int AD_get(unsigned char channel)
{
ADC_CONTR=0x88|channel; //開啟AD轉(zhuǎn)換1000 1000 即POWER SPEED1 SPEED0 ADC_FLAG ADC_START CHS2 CHS1 CHS0
_nop_(); _nop_(); _nop_(); _nop_();//要經(jīng)過4個(gè)CPU時(shí)鐘的延時(shí),其值才能夠保證被設(shè)置進(jìn)ADC_CONTR寄存器
while(!(ADC_CONTR&0x10)); //等待轉(zhuǎn)換完成
ADC_CONTR&=0xe7; //關(guān)閉AD轉(zhuǎn)換,ADC_FLAG位由軟件清0
return(ADC_RES*4+ADC_RESL); //返回AD轉(zhuǎn)換完成的10位數(shù)據(jù)(16進(jìn)制)
}
//------------------------------------------------------------------------------
float AD_work(unsigned char channel)
{
float AD_val; //定義處理后的數(shù)值A(chǔ)D_val為浮點(diǎn)數(shù)
unsigned char i;
for(i=0;i<100;i++)
AD_val+=AD_get(channel); //轉(zhuǎn)換100次求平均值(提高精度)
AD_val/=100;
AD_val=(AD_val*5)/1024; //AD的參考電壓是單片機(jī)上的5v,所以乘5即為實(shí)際電壓值
return AD_val;
}
//------------------------------------------------------------------------------
void delay(unsigned int a) //延時(shí)約1ms
{
unsigned int i;
while (--a!=0)
for(i=600;i>0;i--); //1T單片機(jī)i=600,若是12T單片機(jī)i=125
}
//------------------------------------------------------------------------------
void serial_init()
{
TMOD=0x20;
TH1=0xfd;
TL1=0xfd; //設(shè)置9600波特率
SCON=0x50; //串口方式1,允許接收
TR1=1;
}
//------------------------------------------------------------------------------
void AD_init()
{
P1ASF=0xff; //P1口全部作為模擬功能AD使用
ADC_RES=0; //清零轉(zhuǎn)換結(jié)果寄存器高8位
ADC_RESL=0; //清零轉(zhuǎn)換結(jié)果寄存器低2位
ADC_CONTR=0x80;//開啟AD電源
delay(2); //等待1ms,讓AD電源穩(wěn)定
}
/*
評(píng)論