2015년 7월 23일 목요일

[5th Week] DHT11 Temperature & Humidity Sensor

One of sensors I selected for my testing is temperature sensor. DHT11 includes temperature sensor, and humidity sensor.
Here's DHT11 board. Originally, it is just blue unit on the top with 4 pins, and it should be connected with resistor. However, this consists resistor in its board, and has only 3 pins except useless pin.
I connected it to Arduino board, and pin connection is like this.
(Arduino <-> DHT11)
5V <-> + (VCC)
GND <-> - (GND)
DIGITAL 2 <-> DATA

From now on, I can check data from sensor on Arduino with this code below. We can use DHT11 library for Arduino. It could be easily found in the website.

#include <DHT11.h>
int pin=2;
DHT11 dht11(pin); 
void setup()
{
   Serial.begin(9600);
  while (!Serial) {
      ; // wait for serial port to connect. Needed for Leonardo only
    }
}

void loop()
{
  int err;
  float temp, humi;
  if((err=dht11.read(humi, temp))==0)
  {
    Serial.println("*DHT11*");
    Serial.print("temperature: ");
    Serial.println(temp);
    Serial.print("humidity: ");
    Serial.println(humi);
  }
  else
  {
    Serial.println();
    Serial.print("Error No :");
    Serial.print(err);
    Serial.println();    
  }
  delay(1000); //delay for reread
}

With this, data is sent to RPi through serial connection. For capturing data on RPi, this python code can work.

import sys
import serial

port = "/dev/ttyACM0"

serialFromArduino = serial.Serial(port, 9600)
serialFromArduino.flushInput()

def getSensorData():

    print('*DHT11*')
    input1 = serialFromArduino.readline()
    print(input1)
    tem = input1.split()[1]
    input2 = serialFromArduino.readline()
    print(input2)
    hum = input2.split()[1]
    return (float(tem), float(hum))

def main():

    print('starting...')

    while True:

        if(serialFromArduino.inWaiting() > 0):
            if(serialFromArduino.readline().find('*') != -1):
                tem, hum = getSensorData()
            
if __name__ == '__main__':
    main()

Result looks like this.

댓글 없음:

댓글 쓰기