樓主仔細逐條對比就知道哪里錯了
無標題.jpg (136.21 KB, 下載次數: 54)
下載附件
2020-12-22 16:26 上傳
測試.zip
(126.4 KB, 下載次數: 27)
2020-12-22 16:26 上傳
點擊文件名下載附件
- void Delay1ms(uchar ms)
- {
- uint x,y;
- for(x=ms; x>0; x--)
- {
- for(y=124; y>0; y--);
- }
- }
- void delay_us(uchar us)
- {
- while(--us);
- }
- uchar Ds18b20Init()
- {
- bit x;
- DSPORT = 1; //將總線拉低480us~960us
- delay_us(5);
- DSPORT = 0; //然后拉高總線,如果DS18B20做出反應會將在15us~60us后總線拉低
- delay_us(200);
- delay_us(200);
- DSPORT = 1;
- delay_us(50);
- x= DSPORT;
- delay_us(25);
- return x; //初始化成功
- }
- void Ds18b20WriteByte(uchar dat)
- {
- uint j;
- for(j=8; j>0; j--)
- {
- DSPORT = 0; //每寫入一位數據之前先把總線拉低1us
- DSPORT = dat & 0x01; //然后寫入一個數據,從最低位開始
- delay_us(25);
- DSPORT = 1; //然后釋放總線,至少1us給總線恢復時間才能接著寫入第二個數值
- dat >>= 1;
- }
- delay_us(25);
- }
- uchar Ds18b20ReadByte()
- {
- uchar byte = 0;
- uint j;
- for(j=8; j>0; j--)
- {
- DSPORT = 0;
- byte >>= 1; //先將總線拉低1us
- DSPORT = 1; //然后釋放總線 //延時6us等待數據穩定
- if(DSPORT)
- byte |= 0x80;
- delay_us(25);
- }
- return byte;
- }
- void Ds18b20ChangTemp()
- {
- Ds18b20Init();
- Ds18b20WriteByte(0xcc); //跳過ROM操作命令
- Ds18b20WriteByte(0x44);
- }
- void Ds18b20ReadTempCom()
- {
- Ds18b20Init();
- Ds18b20WriteByte(0xcc); //跳過ROM操作命令
- Ds18b20WriteByte(0xbe); //發送讀取溫度命令
- }
- int Ds18b20ReadTemp()
- {
- int temp ;
- uchar tmh, tml;
- Ds18b20ChangTemp();
- Delay1ms(2); //先寫入轉換命令
- Ds18b20ReadTempCom(); //然后等待轉換完后發送讀取溫度命令
- tml = Ds18b20ReadByte(); //讀取溫度值共16位,先讀低字節
- tmh = Ds18b20ReadByte(); //再讀高字節
- temp = tmh<<8|tml;
- return temp;
- }
復制代碼
|