標(biāo)題:
stm32 m3內(nèi)核寄存器操作一線總線時(shí)序DS18B20源程序(詳細(xì)注釋)
[打印本頁(yè)]
作者:
miss周
時(shí)間:
2019-5-7 19:03
標(biāo)題:
stm32 m3內(nèi)核寄存器操作一線總線時(shí)序DS18B20源程序(詳細(xì)注釋)
0.png
(4.96 KB, 下載次數(shù): 48)
下載附件
2019-5-8 01:21 上傳
單片機(jī)源程序如下:
#include "ds18b20.h"
/*
函數(shù)名稱(chēng):void DS18B20_Init(void)
函數(shù)功能:DS18B20初始化
硬件鏈接:DQ->PB15
*/
void DS18B20_Init(void)
{
RCC->APB2ENR|=1<<3;
GPIOB->CRH&=0x0FFFFFFF;
GPIOB->CRH|=0x30000000;
GPIOB->ODR|=1<<15;
}
/*
函數(shù)名稱(chēng):void DS18B20_Ret(void)
函數(shù)功能:發(fā)送復(fù)位信號(hào)
*/
void DS18B20_Ret(void)
{
Ds18B20_OutPut_Mode();
Ds18B20_Out=0;
delay_us(750);
Ds18B20_Out=1;
delay_us(15);
}
/*
函數(shù)名稱(chēng):u8 DS18B20_Check(void)
函數(shù)功能:檢測(cè)存在脈沖
返 回 值:0代表存在 1代表不存在
*/
u8 DS18B20_Check(void)
{
u32 i=0;
Ds18B20_InPut_Mode();
while(Ds18B20_In && i<60)
{
i++;
delay_us(1);
}
if(i>=60)return 1;
i=0;
while(!Ds18B20_In && i<240)
{
i++;
delay_us(1);
}
if(i>=240)return 1;
return 0;
}
/*
函數(shù)名稱(chēng):void DS18B20_WriteByte(u8 cmd)
函數(shù)功能:發(fā)送命令給Ds18B20
發(fā)送模式,拉低總線電平,60us以上低為 0,60us以上高為 1
*/
void DS18B20_WriteByte(u8 cmd)
{
u8 i=0;
Ds18B20_OutPut_Mode(); //設(shè)置為輸出模式
for(i=0;i<8;i++)
{
Ds18B20_Out=0; //拉低IO口電平
delay_us(2); //兩次寫(xiě)間隙大于 1us
Ds18B20_Out=cmd & 0x01; //指令與上 0000 0001 保留最低位 為 1 輸出高 為 0 輸出 0
delay_us(60); //保持IO口電平延時(shí)60 us 以上
Ds18B20_Out=1; //拉高IO口電平
cmd>>=1; //cmd指令右移一位后賦值給cmd
}
}
/*
函數(shù)名稱(chēng):u8 DS18B20_ReadByte(void)
函數(shù)功能:讀取數(shù)據(jù)
返 回 值:讀到的數(shù)據(jù)
*/
u8 DS18B20_ReadByte(void)
{
u8 i,data=0;
for(i=0;i<8;i++)
{
Ds18B20_OutPut_Mode();
Ds18B20_Out=0;
delay_us(2);
Ds18B20_InPut_Mode();
delay_us(8);
data>>=1;
if(Ds18B20_In==1)data|=0x80;
delay_us(60);
Ds18B20_Out=1;
}
return data;
}
/*
函數(shù)名稱(chēng):u16 DS18B20_Read_Temp(void)
函數(shù)功能:獲取溫度
返 回 值:溫度值
*/
u16 DS18B20_Read_Temp(void)
{
u8 temp_H,temp_L;
u16 temp;
DS18B20_Ret(); //DS18B20發(fā)送復(fù)位信號(hào)
if(DS18B20_Check())printf("檢測(cè)失敗\r\n"); //檢測(cè)應(yīng)答
DS18B20_WriteByte(0xcc); //跳過(guò)ROM檢測(cè)(64位編號(hào))
DS18B20_WriteByte(0x44); //開(kāi)始溫度檢測(cè)
DS18B20_Ret(); //發(fā)送復(fù)位信號(hào)
if(DS18B20_Check())printf("檢測(cè)失敗\r\n"); //檢測(cè)應(yīng)答
DS18B20_WriteByte(0xcc); //跳過(guò)ROM檢測(cè)(64位編號(hào))
DS18B20_WriteByte(0xbe); //讀取暫存器數(shù)據(jù)(溫度數(shù)據(jù)位于前兩位)
temp_L=DS18B20_ReadByte(); //讀取溫度低位
temp_H=DS18B20_ReadByte(); //讀取溫度高位
temp=(temp_H<<8)|temp_L; //合成溫度數(shù)據(jù)(高八位左移8位后 將低位數(shù)據(jù)與上)
return temp; //返回16位的溫度數(shù)據(jù)
}
復(fù)制代碼
所有資料51hei提供下載:
DS18B20.zip
(1.51 KB, 下載次數(shù): 11)
2019-5-7 19:04 上傳
點(diǎn)擊文件名下載附件
下載積分: 黑幣 -5
歡迎光臨 (http://www.torrancerestoration.com/bbs/)
Powered by Discuz! X3.1