WGLabz
Published © Apache-2.0

DHT12 Sensor with Linkit Smart 7688 Duo using Python

DHT12(I2C) Sensor Interfacing with Linkit Smart 7688 Duo using Python/Arduino and PySerial Library

IntermediateProtip2 hours1
DHT12 Sensor with Linkit Smart 7688 Duo using Python

Things used in this project

Hardware components

Seeed Linkit Smart 7688 Duo
×1
DHT12
×1

Story

Read more

Schematics

Connection Diagram

Code

Arduino Code

C/C++
#include <Wire.h>
#include <ArduinoJson.h>

char data[5];
void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  Serial1.begin(9600);
}
float temperature = 0.0;
float humidity = 0;
StaticJsonDocument < 200 > jsonData;
char inData = '0';
void loop() {
  if (Serial1.available() > 0) {
    inData = (char) Serial1.read();
    //    Serial1.println(inData);
  }
  if (inData == '1') {
    inData = '0';
    Wire.beginTransmission(0x5c);
    Wire.write(0);
    if (Wire.endTransmission() != 0) {
      //Error
    }
    Wire.requestFrom(0x5c, (uint8_t) 5);
    for (uint8_t i = 0; i < 5; ++i) {
      data[i] = Wire.read();
    }

    if (data[4] == (data[0] + data[1] + data[2] + data[3])) {
      humidity = (data[0] + (float) data[1] / 10);

      byte scaleValue = data[3] & B01111111; // 
      byte signValue = data[3] & B10000000; // Fetch sign of the tempperature value 1: Negative; 0: Positive

      temperature = (data[2] + (float) scaleValue / 10); // ((data[2] & 0x7F)*256 + data[3]);
      temperature = signValue ? -temperature : temperature;

      //    Serial1.print("Temperature: ");
      //    Serial1.println(temperature);
      //    Serial1.print("Humidity: ");
      //    sprintf(jsonData, "{\"TEMP\":%.2f,\"HUM\":%.2f}",temperature,humidity);
      jsonData["TEMP"] = temperature;
      jsonData["HUM"] = humidity;
      //      sprintf(jsonData, "%.2f",temperature);
      serializeJson(jsonData, Serial1);
      //Serial1.println(jsonData);
    } else {
      Serial1.println("Checksum/ Communication Error");
    }
  }
}

Python Script

Python
import serial,io,time,json

#Initalize the serial port
ser = serial.Serial('/dev/ttyS0',9600,timeout=1)
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))

# Loop forever to send command to Arduino and read values from it.
degree = u"\N{DEGREE SIGN}"
while 1:
    ser.write(b'1')
    time.sleep(2)
    if ser.inWaiting() > 0:
        serial_data = sio.readline()
    
    json_data = json.loads(serial_data)
    print("Temperature: "+str(json_data['TEMP'])+degree.encode('utf-8')+"C")
    print("Humidity: "+str(json_data['HUM'])+" %RH")
    time.sleep(5)

Credits

WGLabz

WGLabz

13 projects • 21 followers
Blogger/ Tinkerer and Smart Home Enthusiast. I have always loved to play around technology includeing Embedded System to server programming.

Comments

Add projectSign up / Login