中级会员
- 积分
- 369
- 威望
- 228
- 贡献
- 61
- 兑换币
- 20
- 注册时间
- 2009-6-25
- 在线时间
- 40 小时
|
最近做了个测温的模块,用的是DS18B20这款传感器(DG128编程),可是温度老是采集不回来,多次检查时序没有错,想请教下用过这个传感器的高手!以下是我编的程序:
#include <hidef.h> /* common defines and macros */
#include <mc9s12dg128.h> /* derivative information */
#pragma LINK_INFO DERIVATIVE "mc9s12dg128b"
void MCU_Init(void);
void Delay(unsigned int k);//k=2~65535存在一定误差(比规定值偏大)
void Delay_1us(void); //精确延时1us
void get_temp(void);
void ds18b20_Init(void);
void ds18b20_write(unsigned char command);
void ds18b20_read(void);
unsigned char tempdf,tempin;
void main(void) {
MCU_Init();
for(;;){
get_temp();
}
}
/*----------------------MCU初始化函数----------------------------*/
void MCU_Init(void){
CLKSEL &= 0x7f;
PLLCTL &= 0xbf;
SYNR = 24;
REFDV = 15; //bus clock=25MHz
PLLCTL |= (1<<6);
while((CRGFLG&0x08)==0x00);
CLKSEL |= (1<<7);
INTCR &= 0xbf;
COPCTL = 0x00;
}
/*-----------------------测温函数-------------------------------*/
void get_temp(void){
DDRA_BIT7=1; //A7为输出
DDRA_BIT6=0; //A6为输入
ds18b20_Init();
ds18b20_write(0xcc);
ds18b20_write(0x44);
Delay(500);
ds18b20_Init();
ds18b20_write(0xcc);
ds18b20_write(0xbe);
ds18b20_read();
}
/*-----------------------DS18B20初始化函数----------------------*/
void ds18b20_Init(void){
while(1){
unsigned char flag=0;
PORTA_BIT7=0;
Delay(500);
PORTA_BIT7=1;
Delay(60);
while(PORTA_BIT6==0){
Delay(250);
if(PORTA_BIT6==1){
DDRA_BIT5=1;
PORTA_BIT5=0;
flag=1;
break;
}
}
if(flag==1) {
Delay(200);
break;
}
}
}
/*-----------------------DS18B20写命令函数----------------------*/
void ds18b20_write(unsigned char command){
unsigned char i;
for(i=0;i<8;i++){
PORTA_BIT7=0;
Delay(12);
if((command & 0x01)==1) {
PORTA_BIT7=1;
}
else {
PORTA_BIT7=0;
}
Delay(45);
command=command>>1;
PORTA_BIT7=1;
Delay_1us();
}
}
/*-----------------------DS18B20读温度函数----------------------*/
void ds18b20_read(void){
unsigned char i,j=2,k,temp,templ,temph;
while(j--){
for(i=0;i<8;i++){
temp>>=1;
PORTA_BIT7=0;
Delay(2);
PORTA_BIT7=1;
Delay(5);
if(PORTA_BIT6)
temp |= 0x80;
Delay(50);
}
if(j==1)
templ=temp;
else
temph=temp;
}
if((temph & 0xf8)!=0){
DDRA_BIT4=1;
PORTA_BIT4=0;
temph=~temph;
templ=~templ;
k=templ+1;
templ=k;
if(k>255){
temph++;
}
}
tempdf=templ & 0x0f;
templ>>=4;
temph<<=4;
tempin=temph|templ;
}
/*----------------------普通延时函数----------------------------*/
void Delay(unsigned int k)
{
unsigned int j;
while(--k){
for(j=0;j<=2;j++){
}
}
}
/*----------------------精确延时1us函数-------------------------*/
void Delay_1us(void)
{
unsigned int j;
j=1;
while(--j){
}
} |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
|