STC12C5A60S2 AD转换C语言示例程序(ADC查询方式)
扫描二维码
随时随地手机看文章
STC12C5A60S2 C语言示例程序(ADC查询方式)
#include"reg51.h"
#include"intrins.h"
#defineFOSC18432000L
#defineBAUD9600
typedefunsignedcharBYTE;
typedefunsignedintWORD;
/*DeclareSFRassociatedwiththeADC*/
sfrADC_CONTR=0xBC;//ADCcontrolregister
sfrADC_RES=0xBD;//ADChigh8-bitresultregister
sfrADC_LOW2=0xBE;//ADClow2-bitresultregister
sfrP1ASF=0x9D;//P1secondaryfunctioncontrolregister
/*DefineADCoperationconstforADC_CONTR*/
#defineADC_POWER0x80//ADCpowercontrolbit
#defineADC_FLAG0x10//ADCcompleteflag
#defineADC_START0x08//ADCstartcontrolbit
#defineADC_SPEEDLL0x00//420cLOCks
#defineADC_SPEEDL0x20//280clocks
#defineADC_SPEEDH0x40//140clocks
#defineADC_SPEEDHH0x60//70clocks
voidInitUART();
voidInitADC();
voidSendData(BYTEdat);
BYTEGetADCResult(BYTEch);
voidDelay(WORDn);
voidShowResult(BYTEch);
voidmain()
{
InitUart();//InitUART,usetoshowADCresult
InitADC();//InitADCsfr
while(1)
{
ShowResult(0);//ShowChannel0
ShowResult(1);//ShowChannel1
ShowResult(2);//ShowChannel2
ShowResult(3);//ShowChannel3
ShowResult(4);//ShowChannel4
ShowResult(5);//ShowChannel5
ShowResult(6);//ShowChannel6
ShowResult(7);//ShowChannel7
}
}
/*----------------------------
SendADCresulttoUART
----------------------------*/
voidShowResult(BYTEch)
{
SendData(ch);//ShowChannelNO.
SendData(GetADCResult(ch));//ShowADChigh8-bitresult
//ifyouwantshow10-bitresult,uncommentnextline
//SendData(ADC_LOW2);//ShowADClow2-bitresult
}
/*----------------------------
GetADCresult
----------------------------*/
BYTEGetADCResult(BYTEch)
{
ADC_CONTR=ADC_POWER|ADC_SPEEDLL|ch|ADC_START;
_nop_();//Mustwaitbeforeinquiry
_nop_();
_nop_();
_nop_();
while(!(ADC_CONTR&ADC_FLAG));//Waitcompleteflag
ADC_CONTR&=~ADC_FLAG;//CloseADC
returnADC_RES;//ReturnADCresult
}
/*----------------------------
InitialUART
----------------------------*/
voidInitUart()
{
SCON=0x5a;//8bitdata,noparitybit
TMOD=0x20;//T1as8-bitautoreload
TH1=TL1=-(FOSC/12/32/BAUD);//SetUartbaudrate
TR1=1;//T1startrunning
}
/*----------------------------
InitialADCsfr
----------------------------*/
voidInitADC()
{
P1ASF=0xff;//Open8channelsADCfunction
ADC_RES=0;//Clearpreviousresult
ADC_CONTR=ADC_POWER|ADC_SPEEDLL;
Delay(2);//ADCpower-onanddelay
}
/*----------------------------
SendonebytedatatoPC
Input:dat(UARTdata)
Output:-
----------------------------*/
voidSendData(BYTEdat)
{
while(!TI);//Waitforthepreviousdataissent
TI=0;//ClearTIflag
SBUF=dat;//Sendcurrentdata
}
/*----------------------------
SOFtwaredelayfunction
----------------------------*/
voidDelay(WORDn)
{
WORDx;
while(n--)
{
x=5000;
while(x--);
}
}