始终显示读到高电平,多次检查时序不知道问题出在哪里,这是我的代码
单片机源程序如下:
- #include "tempature.h"
- #include "msp430f5529_gpio.h"
- /*******************************************
- 函数名称: B20_Init
- 功 能: 复位DS18B20
- 参 数: 无
- 返回值 : 无
- ********************************************/
- void B20_Init(void)
- {
- unsigned char flag=0;
- GPIO_Init(DS18B20_PORT,DS18B20_PIN,GPO);//P6.5输出
- DS18B20_OUT = 1;//总线拉高
- DELAY_US(5);//稍微延时约5微秒
- DS18B20_OUT = 0;//总线拉低
- DELAY_US(500);//延时500微秒复位脉冲
- DS18B20_OUT = 1;//总线拉高
- DELAY_US(40); //等待40微秒
- GPIO_Init(DS18B20_PORT,DS18B20_PIN,GPI);//P6.5输入
-
- if(DS18B20_IN)//检测是否为高电平
- flag=1;
- else
- flag=0;
- DELAY_US(480);//若读到了数据线上的低电平“做延时,其延时的时间从发出的高电平算起,延时480微秒。
- GPIO_Init(DS18B20_PORT,DS18B20_PIN,GPO);
- DS18B20_OUT = 1;//将数据线再次拉高到高电平“1”后结束
- }
- /*******************************************
- 函数名称: B20_ReadByte
- 功 能: 读取一个字节的数据
- 参 数: 无
- 返回值 : data--返回的一个字节数据
- ********************************************/
- uint8_t B20_ReadByte(void)
- {
- uint8_t i,val=0;
- for(i=0;i < 8;i++) //位计数值
- {
- val>>=1; //右移,准备接受新的数据位
- GPIO_Init(DS18B20_PORT,DS18B20_PIN,GPO);
- DS18B20_OUT = 1; //拉高
- DELAY_US(2); //等待5微秒
- DS18B20_OUT = 0;//拉低,启动读数据位
- DELAY_US(2); //等待5微秒
- DS18B20_OUT = 1; //释放总线
- DELAY_US(4); //等待5微秒
- GPIO_Init(DS18B20_PORT,DS18B20_PIN,GPI);
- if(DS18B20_IN)//该位是否为高
- val|=0x80; //是就将此位置高
- GPIO_Init(DS18B20_PORT,DS18B20_PIN,GPO);
- DELAY_US(60); //等待50微秒
- }
- return val; //将读到的一个字节返回
-
-
- }
- /*******************************************
- 函数名称: B20_WriteByte
- 功 能: 写入一个字节的数据
- 参 数: data--要写入的数据
- 返回值 : 无
- ********************************************/
- void B20_WriteByte(uint8_t data)
- {
- uint8_t i;
-
- for(i=0;i<8;i++) //位计数值
- {
- GPIO_Init(DS18B20_PORT,DS18B20_PIN,GPO);
- DS18B20_OUT = 0;//拉低,启动写数据位
- DELAY_US(2); //等待1微秒
- if(data&0x01) //此位数据是否为高
- {
- DS18B20_OUT = 1;//是高则将单总线拉高
- }
- else
- {
- DS18B20_OUT = 0;//是低则将单总线拉低
- }
- DELAY_US(60); //等待50微秒
- data>>=1; //右移,为写入新的数据位做准备
- }
- DS18B20_OUT = 1;//释放总线
- }
- /*******************************************
- 函数名称: B20_Read_temp
- 功 能: 读取温度值
- 参 数: 无
- 返回值 : 温度值(单位:摄氏度)
- ********************************************/
- float B20_Read_temp(void)
-
- {
- uint8_t templ,temph;
- uint16_t temp;
- float tempature;
- Init_DS18b20();
- templ=B20_ReadByte();
- temph=B20_ReadByte();
- temp = (temph<<8)|templ;//合并为16位
- tempature = temp*0.0625;//转换为温度值
- temp = (int)(tempature*10+0.5);//精确到小数点后1位
- return temp; //返回数据
- }
- void Init_DS18b20()
- {
- B20_Init(); //复位18b20
- DELAY_MS(2);
- B20_WriteByte(0xcc); //跳过ROM
- B20_WriteByte(0x44); //启动温度转换
- }
复制代码 |