leo121_3006061 发表于 2016-12-5 12:17:27

[STM32F042 NucLeo] Mbed+DHT11温湿度

正好手头上有个DHT11温湿度传感器,在Mbed下初步试着用了一下,代码相当简单
include "mbed.h"

//------------------------------------
// Hyperterminal configuration
// 115200 bauds, 8-bit data, no parity
//------------------------------------

Serial pc(SERIAL_TX, SERIAL_RX);
DigitalOut myled(LED1);


DigitalInOut data_pin(A0); // Activate digital in as dht11 Pin

Timer tmr; //initialize timer
uint64_t adat; // 64 bit variable for temporary data
int i;

void dht_read(void) {
    data_pin.output(); // Set A0 as output
    // Initialize measurement > 18 ms low
    data_pin = 0;
    wait_ms(20);
    // After high and release the pin switch input mode
    data_pin = 1;
    data_pin.input();
    // Wait until the end of 80 us low
    while(!data_pin.read()) {}
    // Wait until end of 80 us high
    while(data_pin.read()) {}
    // 40 bit, 40 read out cycle
    for(i=0; i<40; i++) {
      adat = adat << 1; // Shift for new number
      tmr.stop(); // Stop timer if runs
      tmr.reset();// Reset timer
      // Wait until pin
      while(!data_pin.read()) {}         
      tmr.start();            
      while(data_pin.read()) {}
      // If DHT11 HIGH longer than 40 micro seconds (hopefully 70 us)
      if(tmr.read_us() > 40) {
            // bit is 1
            adat++;
      }
    }
}

int main() {
    pc.printf("Hello World !\r\n");
    pc.baud(115200);

   pc.printf("Read the DHT11 temperature and humidity sensor!\r\n"); //Welcome message
    while(1) {
         

            adat = 0;
            myled = !myled; // LED is ON/OFF
            dht_read(); // Call the function
            // Send result through UART result
            pc.printf("Humidity: ");
            pc.printf("%d", (adat& 0x000000ff00000000) >> 32); // Humidity
            pc.printf("\n\r"); // Send a new line and carriage return.
             pc.printf("Temperature: ");
            pc.printf("%d", (adat & 0x0000000000ff0000) >> 16 ); // Temperature
            pc.printf("\n\r");
            pc.printf("Checksum: ");
            pc.printf("%d", adat & 0x00000000000000ff); // Checksum.
            pc.printf("\n\r");
            wait(2); // Wait 2 sec till continue.

      
    }
}


yhyeefocus 发表于 2016-12-5 13:00:16

看贴回帖   

jackten 发表于 2016-12-5 13:31:37

谢谢分享            

limale 发表于 2016-12-6 09:44:15

谢谢分享

leo121_3006061 发表于 2016-12-6 16:17:44

谢谢各位支持:handshake

zero99 发表于 2016-12-19 16:28:15

感谢分享,这个板块之前关注少了

leo121_3006061 发表于 2016-12-19 22:29:41

zero99 发表于 2016-12-19 16:28
感谢分享,这个板块之前关注少了

谢谢鼓励:handshake

damiaa 发表于 2016-12-30 11:39:21

感谢分享

zly_1980 发表于 2016-12-30 15:39:30

学习中学习中

shuolang126 发表于 2017-1-2 09:00:15

看起来是是简单一些,底层初始化驱动基本都省去了!
页: [1] 2
查看完整版本: [STM32F042 NucLeo] Mbed+DHT11温湿度