24bit高精度A/D转换器通信代码,MCU采用PIC16F877,读到的AD值传送到超级终端显示:
/************************************************************************************/
/* 程式名:LTC2400讀寫代碼 */
/* */
/* 晶振: 20M CPU型號: PIC16F877A */
/* */
/* 作者: Randy 日期: 2010-08-27 */
/* */
/************************************************************************************/
#include <pic.h>
#include <stdio.h>
__CONFIG(0X3732);
#define ADC_SDO RC4
#define ADC_SCK RC3
#define ADC_CS RC5
const unsigned char hz[]="輸入電壓是:";
const unsigned char de[]="V";
//unsigned int tmp[4]={0};
static bank1 unsigned long data,dianya;
static bank1 unsigned long voltage;
double x[5];
int t=0,zz;
static bank1 char m[9];
static bank1 unsigned long yushu[9];
//------------------------延時--------------------------------//
void delay_1ms(unsigned int x)
{
unsigned a,b;
for(a=5*x;a>0;a--)
for(b=110;b>0;b--);
}
/*從SPI總線上讀入32bit*/
unsigned long read_ADC(void)
{
char k;
unsigned long n=0;
ADC_CS = 1;
ADC_SCK= 0;
ADC_CS = 0;
for(k=0; k<32; k++)
{
n << = 1;
ADC_SCK = 1;
n |= ADC_SDO;
ADC_SCK = 0;
}
ADC_CS = 1;
if((n & 0x20000000) ==0) //判讀輸入是否為負
t=1;
else
t=0;
n&=0x01fffffff; // maskout sign bit
n>>=4; // get 24-bit conversion result
return n;
}
/* 5-point average */
double filter_ADC(void)
{
double L=0;
int i;
for(i=0;i<5;i++) //5次平均
{
x=read_ADC();
if(t==1) //輸入為負處理
{
L+=0;
}
else if(t==0)
L+ = x;
delay_1ms(170); //200ms延時等待轉換結束
}
return L/5; //5次平均
}
//-----------MCU初始化-----------//
void initial ()
{
TRISC=0X10;
SPBRG=0X81; //20MHz設置串列傳輸速率為9600BPS
TXSTA=0X24; //使能串口發送,選擇高速串列傳輸速率
RCSTA=0X90; //使能串口工作2,連續接收
}
void send()
{
//int baiwan,shiwan,wan,qian,bai,shi,ge;
int z;
unsigned long tmp;
int i;
m[0]=voltage/16777216+0X30; //整數部分
for(i=1;i<9;i++) //取8位小數
{
yushu[0]=voltage%16777216;
m=yushu[i-1]/1677721.6+0X30;
yushu=10*yushu[i-1]%16777216;
}
for(z=0;z<11;z+=2) //發送漢字
{
delay_1ms(3);
while(TXIF)
{
TXREG=hz[z];
TXREG=hz[z+1];
}
}
delay_1ms(3);
TXREG=m[0]; //輸出整數部分
delay_1ms(3);
TXREG=0X2E; //輸出小數點
delay_1ms(3);
TXREG=m[1];
TXREG=m[2];
delay_1ms(3);
TXREG=m[3];
TXREG=m[4];
delay_1ms(3);
TXREG=m[5];
TXREG=m[6];
delay_1ms(3);
TXREG=m[7];
TXREG=m[8];
delay_1ms(3);
while(TXIF)
TXREG=de[0];
TXREG=de[1]; //輸出"V"
delay_1ms(3); //下次輸出需要延時
TXREG=0X0D;
TXREG=0X0A; //輸出換行
}
main()
{
initial ();
while(1)
{
data = (unsigned long)filter_ADC();
voltage =data*5;
//dianya=(long)voltage;
send();
}
}
用户1760798 2015-8-21 10:39