标题:
stm32 m3内核寄存器操作一线总线时序DS18B20源程序(详细注释)
[打印本页]
作者:
miss周
时间:
2019-5-7 19:03
标题:
stm32 m3内核寄存器操作一线总线时序DS18B20源程序(详细注释)
0.png
(4.96 KB, 下载次数: 48)
下载附件
2019-5-8 01:21 上传
单片机源程序如下:
#include "ds18b20.h"
/*
函数名称:void DS18B20_Init(void)
函数功能:DS18B20初始化
硬件链接:DQ->PB15
*/
void DS18B20_Init(void)
{
RCC->APB2ENR|=1<<3;
GPIOB->CRH&=0x0FFFFFFF;
GPIOB->CRH|=0x30000000;
GPIOB->ODR|=1<<15;
}
/*
函数名称:void DS18B20_Ret(void)
函数功能:发送复位信号
*/
void DS18B20_Ret(void)
{
Ds18B20_OutPut_Mode();
Ds18B20_Out=0;
delay_us(750);
Ds18B20_Out=1;
delay_us(15);
}
/*
函数名称:u8 DS18B20_Check(void)
函数功能:检测存在脉冲
返 回 值: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;
}
/*
函数名称:void DS18B20_WriteByte(u8 cmd)
函数功能:发送命令给Ds18B20
发送模式,拉低总线电平,60us以上低为 0,60us以上高为 1
*/
void DS18B20_WriteByte(u8 cmd)
{
u8 i=0;
Ds18B20_OutPut_Mode(); //设置为输出模式
for(i=0;i<8;i++)
{
Ds18B20_Out=0; //拉低IO口电平
delay_us(2); //两次写间隙大于 1us
Ds18B20_Out=cmd & 0x01; //指令与上 0000 0001 保留最低位 为 1 输出高 为 0 输出 0
delay_us(60); //保持IO口电平延时60 us 以上
Ds18B20_Out=1; //拉高IO口电平
cmd>>=1; //cmd指令右移一位后赋值给cmd
}
}
/*
函数名称:u8 DS18B20_ReadByte(void)
函数功能:读取数据
返 回 值:读到的数据
*/
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;
}
/*
函数名称:u16 DS18B20_Read_Temp(void)
函数功能:获取温度
返 回 值:温度值
*/
u16 DS18B20_Read_Temp(void)
{
u8 temp_H,temp_L;
u16 temp;
DS18B20_Ret(); //DS18B20发送复位信号
if(DS18B20_Check())printf("检测失败\r\n"); //检测应答
DS18B20_WriteByte(0xcc); //跳过ROM检测(64位编号)
DS18B20_WriteByte(0x44); //开始温度检测
DS18B20_Ret(); //发送复位信号
if(DS18B20_Check())printf("检测失败\r\n"); //检测应答
DS18B20_WriteByte(0xcc); //跳过ROM检测(64位编号)
DS18B20_WriteByte(0xbe); //读取暂存器数据(温度数据位于前两位)
temp_L=DS18B20_ReadByte(); //读取温度低位
temp_H=DS18B20_ReadByte(); //读取温度高位
temp=(temp_H<<8)|temp_L; //合成温度数据(高八位左移8位后 将低位数据与上)
return temp; //返回16位的温度数据
}
复制代码
所有资料51hei提供下载:
DS18B20.zip
(1.51 KB, 下载次数: 11)
2019-5-7 19:04 上传
点击文件名下载附件
下载积分: 黑币 -5
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1