DHT11驱动程序

来源:互联网 发布:centos设置防火墙端口 编辑:程序博客网 时间:2024/06/10 18:55

自戒:

这是好久之前的一个浇花系统采用的温湿度模块,当时写它的驱动还遇到了一些问题,现在已全然想不起来了,这不是个好习惯。每一个阶段的工作学习完成之后,都应该对其进行分析、总结。要不然下次遇到同样的问题还是不知道如何处理,也根本不可能有什么进步。

记得当时遇到的主要问题是延时,忘记了怎么对MCU的时钟进行配置,因为是自定义的通信协议,其对延时自然要求很严格。现将代码贴出:

头文件:

#include "xgpio.h"#include "cookie.h"/**DHT11头文件 * 头文件对引脚及相关的接口进行了定义 */#define DHT11_Pin sD4//定义数据传输引脚void DHT11_init(void);extern void GPIO_Output(void);//将DHT11_pin引脚置为输出extern void GPIO_Input(void);//将DHT11_pin引脚置为输入extern void Delay_us(int count);//延时函数,延时时长为count us.void Delay_ms(int count);extern void Host_Start(void);//主机MCU发出一段开始信号extern unsigned char Read_One_Byte(void);//读取一个字节数据extern void DHT11_Read(unsigned char* rec);//调用一次读温湿度操作

源文件:

#include "xhw_types.h"#include "xhw_memmap.h"#include "xhw_ints.h"#include "xsysctl.h"#include "xgpio.h"#include "xcore.h"#include "xadc.h"#include "cookie.h"#include "xuart.h"#include "DHT11.h"//初始化引脚DHT11void DHT11_init() {xSysCtlPeripheralEnable(xGPIOSPinToPeripheralId(sD4));xGPIOSPinWrite(sD4, 1);}//DHT11引脚配置为输出void GPIO_Output() {xGPIOSPinTypeGPIOOutput(sD4);//xGPIOSPinTypeGPIOOutputOD(sD4);}//将DHT11_pin引脚置为输入void GPIO_Input(void) {xGPIOSPinTypeGPIOInput(sD4);}//微秒延时函数,延时时长为count us.void Delay_us(int count) {//int i = 0.8848*count;//while (i--);xSysCtlDelay(5*count);}//毫秒延时函数,延时时长为count ms.void Delay_ms(int count) {/*int i = 0;while (count--) {for (i = 0; i < 884; i++) {; //void}}*/xSysCtlDelay(count*5525);}//主机MCU发出一段开始信号void Host_Start(void) {GPIO_Output();xGPIOSPinWrite(sD4, 1);xGPIOSPinWrite(sD4, 0);Delay_ms(20); //拉低最少18msxGPIOSPinWrite(sD4, 1);Delay_us(20);}//读取一个字节数据unsigned char Read_One_Byte() {unsigned char temp = 0, i, j = 0;for (i = 0; i < 8; i++){temp <<= 1;while (0 == xGPIOSPinRead(sD4)); //等待变高电平while (1 == xGPIOSPinRead(sD4)) //计算高电平时长{Delay_us(1);j++;}if (j >= 12) //超过30us确认为1{temp = temp | 0x01;j = 0;}j = 0;}return temp;}//调用一次读温湿度操作void DHT11_Read(unsigned char* rec) {Host_Start(); //主机发送请求信号GPIO_Input(); //设置端口为输入状态if (!xGPIOSPinRead(sD4)){//xUARTCharPut(xUART0_BASE,'s');while (0 == xGPIOSPinRead(sD4)); //低电平的响应信号,80uswhile (1 == xGPIOSPinRead(sD4)); //紧接着是80us的高电平数据准备信号rec[0] = Read_One_Byte(); //湿度高8位rec[1] = Read_One_Byte(); //湿度低8位rec[2] = Read_One_Byte(); //温度高8位rec[3] = Read_One_Byte(); //温度低8位rec[4] = Read_One_Byte(); //校验和GPIO_Output();xGPIOSPinWrite(sD4, 1);//数据校验//rec[5] = rec[0]+rec[2];//校验和//xUARTCharPut(xUART0_BASE,'c');}//xUARTCharPut(xUART0_BASE,'d');Delay_ms(2000);}




0 0
原创粉丝点击