C516单片机调用DS18B20温度传感器代码问题,跟着b站上学习的单片机,在温度传感器碰到了瓶颈,访问温度返回的数据一直显示255看到本论坛有相关的帖子说是时序问题,我就用软件又重新生成了一遍相关的延时
结果还是不行,然后又屡着视频代码一遍遍的看还是不行
希望大佬可以帮忙看看是那边错的
下面附上代码
单总线的代码
- #include <REGX52.H>
- sbit OneWire_DQ=P3^7;
- unsigned char OneWire_Init()
- {
- unsigned char i,r;
- OneWire_DQ=1;
- OneWire_DQ=0;
- i = 247;while (–i);//延时500us 229
- OneWire_DQ=1;
- i = 32;while (–i);//延迟70us 31
- i=OneWire_DQ;
- i = 247;while (–i);//延时500us 229
- return r;
- }
- void OneWire_Write(unsigned char Bit)
- {
- unsigned char i;
- OneWire_DQ=0;
- i = 4;while (–i);//延迟10us 3
- OneWire_DQ=Bit;
- i = 25;while (–i);//延迟60us 4(60)
- OneWire_DQ=1;
- }
- unsigned char OneWire_Read()
- {
- unsigned char i;
- unsigned char Bit;
- OneWire_DQ=0;
- i = 2;while (–i);//延迟5us
- OneWire_DQ=1;
- i = 2;while (–i);//延迟5us (9us)
- Bit=OneWire_DQ;
- i = 24;while (–i);//延迟50us 24
- return Bit;
- }
- void OneWire_SendByte(unsigned char Data)
- {
- unsigned char i;
- for(i=0;i<8;i++)
- {
- OneWire_Write(Data&(0x01<<i));
- }
- }
- unsigned char OneWire_ReadByte()
- {
- unsigned char i;
- unsigned char Byte=0x00;
- for(i=0;i<8;i++)
- {
- if(OneWire_Read()){Byte|=(0x01<<i);}
- }
- return Byte;
- }
复制代码
返回数据的代码
- #include <REGX52.H>
- #include “OneWire.h”
- #include “LCD1602.h”
- void Delay1ms() //@12.000MHz
- {
- unsigned char i, j;
- i = 1;
- j = 110;
- do
- {
- while (–j);
- } while (–i);
- }
- void DS18B20_ConvertT()
- {
- OneWire_Init();
- Delay1ms();
- OneWire_Write(0xCC);
- OneWire_Write(0x44);
- }
- float DS18B20_Read()
- {
- unsigned char TLSB,TMSB;
- int temp;
- float T;
- OneWire_Init();
- Delay1ms();
- OneWire_Write(0xCC);
- OneWire_Write(0xBE);
- TLSB=OneWire_ReadByte();
- TMSB=OneWire_ReadByte();// 用的LCD1602显示的数据
- LCD_ShowNum(1,1,TMSB,8);//
- LCD_ShowNum(1,9,TLSB,8);
- temp=(TMSB<<8)|TLSB;
- T=temp/16.0;
- return T;
- }
复制代码