单片机 > 单片机程序设计 > 详情

pic16f877a的AD实验学习

发布时间:2023-08-10 发布时间:
|

一、主函数


//采集AD值


#include

#include "ad.h"

#include "usart.h"


__CONFIG(0xFF32);


const uchar disp[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,

0x07,0x7f,0x6f};


//延时函数

void delayms(uint x)

{

uint j,k;

for(j=x;j>0;j--)

for(k=110;k>0;k--);

}


//显示4位,低位数码管显示不正常

void display(uint x)

{

PORTD= disp[x/1000]|0x80;

PORTA= 0x10;

delayms(2);

PORTD= disp[x/100%10];

PORTA= 0x08;

delayms(4);


PORTD= disp[x/10%10];

PORTA= 0x04;

delayms(2);


PORTD= disp[x%10];

PORTA= 0x02;

delayms(2);

}




//初始化IO

void init()

{

TRISA = 0x01; //RA0 input mode

TRISC = 0xff; //RC output mode

TRISD = 0;

PORTC = 0x01;


ADCON0 = 0x41; //ADCS1:ADCS0=01,AN0,,A/D On

ADCON1 = 0x8E; //right justified,ADCS2=0,1110

delayms(10);

}


//获取AD值

uint getad()

{

uint adval;

float advalf;

GO = 1;

while(GO);

adval = ADRESH;

adval = adval<<8|ADRESL;

advalf = adval/1023.0*5.0; //转换成电压

adval = (uint)(advalf*1000); //转换成4位整型

return (adval);

}


void main()

{

uint i = 0;

uint temp;

init();

usart_init();

while(1)

{

temp = getad();

display(temp);

if(i == 100)

{

usart_tx(temp>>8);

usart_tx(temp);

i=0;

}

delayms(5);

i++;

}

}


二、usart函数


#include

#include "usart.h"


//串口初始化

void usart_init(void)

{

SPBRG = 0xC; //波特率19200

TXSTA = 0x24; //开启发送,高速模式

RCSTA = 0X90; //使能TXRX引脚,接收到CREN直到被清零

RCIE = 0X1; //使能接受中断

GIE = 0X1; //开启总中断

PEIE = 0X1; //开启串口中断

}


void interrupt usart(void)

{

if(RCIE && RCIF)

{

TXREG = RCREG; //返回接收的数据

}

}


void usart_tx(unsigned char date)

{

TXREG = date;

while(TRMT!=1);

}



『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
MSP430低功耗模式-while循环失效