PIC16F877A單片機(jī)-AD轉(zhuǎn)換經(jīng)典C程序
#include
#define HC595_SER RB7
#define HC595_SCK RB6
#define HC595_RCK RB5
#define key_164_data RB3
#define key_164_clk RB2
#define key_com1 RB1
#define key_com0 RB0
#define TURE 1
bit key_finish; //定義位變量,這是PICmate仿真軟件環(huán)境的特有的地方 unsigned int sample_key;
unsigned int sample_keyBuf[2];
unsigned int key_value;
unsigned char key_row_sel;
unsigned char key_number;//鍵號(hào)
unsigned int T100ms;
unsigned char disbuf[8];
unsigned int ad_data;
int a[4];
const unsigned char seven_seg[16]=
{0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
//----------------------------------------------
void disbuf_update(void)
{
disbuf[7]=seven_seg[a[3]];
disbuf[6]=seven_seg[a[2]];
disbuf[5]=seven_seg[a[1]];
disbuf[4]=seven_seg[a[0]];
disbuf[3]=seven_seg[0];
disbuf[2]=seven_seg[0];
disbuf[1]=seven_seg[0];
disbuf[0]=seven_seg[0];
}
//----------------------------------------------
//發(fā)送一個(gè)字節(jié)
void s_pData(unsigned char key) //形參key對(duì)應(yīng)著實(shí)參disbuf[i]
{
unsigned char i;
for(i=0;i<8;i++)
{
if(0x80&(key< HC595_SER=1;
else HC595_SER=0;
HC595_SCK=0;
HC595_SCK=1;
}
}
//----------------------------------------------
//----------------------------------------------
void display (void)
{
unsigned char i;
for(i=0;i<8;i++)
s_pData(disbuf[i]);
HC595_RCK=0;
HC595_RCK=1;
}
//----------------------------------------------
void start_ad_change (void) //開始A/D轉(zhuǎn)化
{
ADCON1=0x80;
ADCON0=0x48;
ADON=1;
ADIF=0;
asm("nop");
asm("nop");
asm("nop");
asm("nop");
asm("nop");
asm("nop");
asm("nop");
asm("nop");
ADGO=1;
while(ADIF==0);
ADIF=0;
ad_data =ADRESL;
ad_data |=(unsigned int)(ADRESH<<8); //強(qiáng)制ADRESH的8位放在ad_data的高八位
ADON=0;
}
void two_change_ten(void) //二進(jìn)制轉(zhuǎn)十進(jìn)制
{
int s=0,i;
for(i=0;i<=15;i++)
{if(0x0001&(ad_data>>i))
s=s+pow(2,i);
}
a[0]=s%10;
a[1]=(s/10)%10;
a[2]=(s/100)%10;
a[3]=s/1000;
}
//主程序
int main(void)
{
PORTB=0;
TRISB=0x03;
PORTA=0;
TRISA=0x02;
while(1)
{
start_ad_change();
two_change_ten();
disbuf_update();
display();
}
}
//----------------------------------------------
評(píng)論