nRF52840开发板现在可供参考的例子只有SDK中的实例,而且实例也很少,在SDK中有一个温度数据采集的实例,但是采集的是芯片温度;twi也提供了一个通过I2C获取温度传感器数据的例子,但是温度传感器是LM75B,我手头上没有这个传感器,而且这两个例子都是通过while(true)实现一个死循环来不断地采集温度,这样如果需要集成其他功能的话会导致程序无法正常运行下去,所以决定使用app_timer来定时获取DHT11温湿度传感器的数据。
1.定义DHT11.h
#ifndef __DHT11_H__
#define __DHT11_H__
#include <stdint.h>
#define DATA_PIN NRF_GPIO_PIN_MAP(1,7) //设定P1.07为温度传感器out接口
#define PIN_DATA_OUT (nrf_gpio_cfg_output(DATA_PIN));
#define PIN_DATA_IN (nrf_gpio_cfg_input(DATA_PIN,NRF_GPIO_PIN_PULLUP));
#define PIN_DATA_SET (nrf_gpio_pin_set(DATA_PIN)); //DATA_PINê?3???μ???
#define PIN_DATA_CLEAR (nrf_gpio_pin_clear(DATA_PIN));
#define DHT11_SUCCESS NRF_SUCCESS
#define DHT11_DATA_ERR 0xFD
#define DHT11_NACK 0xFE
typedef struct
{
uint8_t h_int;
uint8_t h_deci;
uint8_t t_int;
uint8_t t_deci;
uint8_t check_sum;
}DHT11_Data_t;
uint32_t Read_DHT11(DHT11_Data_t *DHT11_Data);
#endif
我用的是Segger Embeded Studio,所以需要将新建的dht11.h的文件放入工程的同一文件夹下,或者在#include的时候写明dht11.h文件的路径。
2.main.c中完成DHT11驱动定义、数据采集的功能
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include "nrf.h"
#include "nrf_delay.h"
#include "nrf_temp.h"
#include "app_error.h"
#include "bsp.h"
#include "dht11.h"
#include "app_timer.h"
#include "nrf_drv_clock.h"
///** @brief Function for main application entry.
// */
//
DHT11_Data_t DHT11_Data;
APP_TIMER_DEF(m_repeated_timer_id);
/**@brief Timeout handler for the repeated timer.
*/
static void lfclk_request(void)
{
ret_code_t err_code = nrf_drv_clock_init();
APP_ERROR_CHECK(err_code);
nrf_drv_clock_lfclk_request(NULL);
}
static uint32_t waitfor_state(bool pin_state)
{
uint8_t delay_us = 100;
do
{
if(nrf_gpio_pin_read(DATA_PIN)==pin_state)
{
return DHT11_SUCCESS;
}
nrf_delay_us(1);
delay_us--;
}while(delay_us);
return DHT11_NACK;
}
static uint8_t Read_Byte(void)
{
u