DHT11/DHT22 with Raspberry Pi

How to get “%” as shown. Please help me

Did you use the format "rel_hum,p=" + str(humidity11) ? Sending that string should automatically set up the widget. If not you can try to hit the settings cog and change it there.

@adam I do not understand what you mean “rel_hum, p =” + str (humidity11)
How do I code like this? If possible you can help me!

#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266.h>
#include <Servo.h> 
Servo myServo;
#include <ESP8266WiFi.h>
#define CAYENNE_DEBUG

#include "DHT.h"
#define DHTPIN D4     
#define DHTTYPE DHT11  
DHT dht(DHTPIN, DHTTYPE);

#define TROM D8 
int PIR; 

#define khi A0
#define MQ2 MQ135


char ssid[] = "";
char wifiPassword[] = "";


char username[] = "";
char password[] = "";
char clientID[] = "";



float h,t,f,hic,hif;
void setup() {
  Serial.begin(115200);
  Cayenne.begin(username, password, clientID, ssid, wifiPassword);
  pinMode(D0,OUTPUT);
  pinMode(D1,OUTPUT);
  pinMode(D2,OUTPUT);
  pinMode(D3,OUTPUT);
  pinMode(D8,INPUT);
   pinMode(D7,OUTPUT);
 
  digitalWrite(D0,HIGH); 
  digitalWrite(D1,HIGH); 
 digitalWrite(D3,HIGH); 
 digitalWrite(D7,LOW); 
 
 
   myServo.attach(D7);
}

void loop() {
  Cayenne.loop();
 
 PIR= digitalRead(TROM);
   if (PIR == LOW) {
    Serial.println("KHÔNG CÓ TRỘM"); // Giá trị LOW khi không có chuyển động, in kết quả ra cổng Serial
  }
  else {
    Serial.println("CÓ TRỘM!"); //In kết quả lên Serial khi phát hiện chuyển động
  }
  
  delay(1000); 

  unsigned long lastMillis = 0;
  if (millis() - lastMillis > 10000) {
    lastMillis = millis();
  Cayenne.virtualWrite(8,PIR);
  Cayenne.virtualWrite(7,analogRead(khi));
  Cayenne.virtualWrite(0, h);
  Cayenne.virtualWrite(1, t);

  }
   h = dht.readHumidity();
  
  t = dht.readTemperature();
 
   f = dht.readTemperature(true);

  
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  hif = dht.computeHeatIndex(f, h);
  
  hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
  
  
  
}
CAYENNE_IN(3)
  {
    
    int currentValue=getValue.asInt();
    if(currentValue==1){
      digitalWrite(D0,LOW);
      }
      else{
       digitalWrite(D0,HIGH); 
      }       }
CAYENNE_IN(4)
  {
    
    int currentValue=getValue.asInt();
    if(currentValue==1){
      digitalWrite(D1,LOW);
      }
      else{
       digitalWrite(D1,HIGH); 
      }       }
CAYENNE_IN(5)
  {
    
    int currentValue=getValue.asInt();
    if(currentValue==1){
      digitalWrite(D2,HIGH);
      }
      else{
       digitalWrite(D2,LOW); 
      }       }
 CAYENNE_IN(6)
  {
    
    int currentValue=getValue.asInt();
    if(currentValue==1){
      digitalWrite(D3,LOW);
      }
      else{
       digitalWrite(D3,HIGH); 
      }       }
  CAYENNE_IN(9)
  {
    
    int currentValue=getValue.asInt();
    if(currentValue==1){
     
        digitalWrite(D7,HIGH);
          myServo.write(120);//cho servo ở 90 độ
    delay(2000);
      }
      else{
       digitalWrite(D7,LOW); 
         myServo.write(0);//cho servo ở 90 độ
    delay(2000);
      }       }
  1. the settings cog and change. how to do it?

what @adam gave is for raspberry pi and your code is of esp8266 with MQTT.
for getting % change this in your code :

to

Cayenne.virtualWrite(0, h, "rel_hum", "p");
1 Like

thanks @shramik_salgaonkar and @adam i have understood…but do not understand why like this.
image==>image

have a look at this Data types for Cayenne MQTT API

You may have to remove the widget first and let your code recreate it. Use the code @shramik_salgaonkar posted above Cayenne.virtualWrite(0, h, "rel_hum", "p");

1 Like

hi guys. I recently upgraded my setup from a Rpi2+WiFistick to a Rpi3.
unfortunately the Rpi3 recives far more fals Messurements from the DHT22 than the Old Setup.

Is it possible to add some Line of Code in the First post, so that certain Values get ignored?
for exsample:
every Value below 0 (humidity)
every Value above 100 (humidity)

every Value below -40 (temperature)
every Velue above 80 (temperature)

Normaly i would not care about such a thing but as you cann see, the fals readings make it hard to read the graph:
graph-H

graph-D

My initial though it that you might want to check your wiring, but here is the code that will do what you want:

import paho.mqtt.client as mqtt
import time
import sys
import Adafruit_DHT

time.sleep(30) #Sleep to allow wireless to connect before starting MQTT

username = "MQTT Username From Dashboard"
password = "MQTT Passsword From Dashboard"
clientid = "MQTT Client ID From Dashboard"

mqttc = mqtt.Client(client_id=clientid)
mqttc.username_pw_set(username, password=password)
mqttc.connect("mqtt.mydevices.com", port=1883, keepalive=60)
mqttc.loop_start()

topic_dht11_temp = "v1/" + username + "/things/" + clientid + "/data/1"
topic_dht11_humidity = "v1/" + username + "/things/" + clientid + "/data/2"
topic_dht22_temp = "v1/" + username + "/things/" + clientid + "/data/3"
topic_dht22_humidity = "v1/" + username + "/things/" + clientid + "/data/4"

while True:
    try:
        humidity11, temp11 = Adafruit_DHT.read_retry(11, 17) #11 is the sensor type, 17 is the GPIO pin number (not physical pin number)
        humidity22, temp22 = Adafruit_DHT.read_retry(22, 18) #22 is the sensor type, 18 is the GPIO pin number (not physical pin number)
        
        if temp11 is not None and temp11 > -40 and temp11 < 80:
            temp11 = "temp,c=" + str(temp11)
            mqttc.publish(topic_dht11_temp, payload=temp11, retain=True)
        if humidity11 is not None and humidity11 > 0 and humidity11 < 100:
            humidity11 = "rel_hum,p=" + str(humidity11)
            mqttc.publish(topic_dht11_humidity, payload=humidity11, retain=True)
        if temp22 is not None and temp22 > -40 and temp22 < 80:
            temp22 = "temp,c=" + str(temp22)
            mqttc.publish(topic_dht22_temp, payload=temp22, retain=True)
        if humidity22 is not None and humidity22 > 0 and humidity22 < 100:
            humidity22 = "rel_hum,p=" + str(humidity22)
            mqttc.publish(topic_dht22_humidity, payload=humidity22, retain=True)
        time.sleep(5)
    except (EOFError, SystemExit, KeyboardInterrupt):
        mqttc.disconnect()
        sys.exit()
1 Like

Any luck with that code @doerek?

hi @adam

Thanks for the added code snippet. :+1:

With the added code the graph looks much cleaner.
graph-D-New

but for some reason, the temperature has not gotten any updates…since the 1st December.
And i dont know why…i gonna check the Cables & connections again.

but due to the fact, that the cable is only 1,5m long and the added code is quite simple…
i dont think that any of this is the reason.

unfortunaly i dont have any Freetime this weekend. but again…thanks for the Workaround/Fix
much appreciated :v:

Could be that none of the values are falling in the range of > -40 and < 80. You can add some print statements in there to see if this is actually the case.

Hello,

Could you post a copy of your crontab file, for some reason when I enter your suggested commands, it does not restart the python code. I have to do it manually.

Your text

Add the python file to your crontab (???) with sudo crontab -e then type in @reboot python /home/pi/python/tempsensor.py & and save. Reboot and you should see the values populate on your MQTT dashboard.

Having your script will save me some time.

Everything else works fine besides the “weird spikes”.

Thanks

Second question, how come the tempsensor.py code stops when I close the terminal window. This should be a permanent process that I can only kill by command or reboot. any suggestions to improve the code? Thanks

@reboot python /home/pi/python/tempsensor.py & is the contents of my crontab (in regards to this script anyway)

If you are running tempsensor.py in a terminal window then yes I would expect to see this behavior. It should only be ran in a terminal window for testing to make sure everything works. There are a lot of way to run this script that it will run on its own, but the crontab solution is the easiest. If you don’t want to use crontab for whatever reason check out screen or pm2

Thank Adam.

I will try this from CLI and with crontab.

Thanks will try this from CLI and crontab again.

If the script is not running on reboot double check that it is located in /home/pi/python/tempsensor.py and also this path will be case sensitive.

Im sure im just struggling with raspian :wink: but no even in your prescribed directory, the result is the same, when the tempsensor is executed, it goes on line on the cayenne page, all is well, but it hangs my window so when I close it, then cayenne goes to offline mode. So the code only works on an active terminal window. its the same things in CLI mode. I think the code loop while true should not be waiting for a SystemExit or KeyboardInterrupt. Or may be im wrong. Thanks