Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new code for temperature/humidity with DHT11 #2

Closed
seamaster101 opened this issue Apr 2, 2020 · 15 comments
Closed

new code for temperature/humidity with DHT11 #2

seamaster101 opened this issue Apr 2, 2020 · 15 comments

Comments

@seamaster101
Copy link

seamaster101 commented Apr 2, 2020

Hi,
I looked at the code for DHT12 (I2C) that you recommend
but I'm using DHT11 and I had to modify it.
one of the disadvantages of DHT11 is that the SW is reading the data from the a pin and the sensor is very slow.
I converted the code from DHT12, but experience problems with reading the DHT11 sensor when combined with the rest of the ESPHAP code. I would presume it is because of interrupts that interfere with the reading of the sensor. Do you think there could be something done about that?

the other issue is that on the I phone I get only temperature accessory but actually reports temperature and humidity (BTW it shows 0.0 even if I put in constants rather than variables-see the rem in my code) but i'm defining 2 services, temperature and humidity
is my code doing it correct?
here is the entire code:

`
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
//#include <FS.h>
//#include <SPIFFS.h>
#define STATIC_IP_ADDR
///
#include "DHT.h"
#ifdef STATIC_IP_ADDR
IPAddress staticIP(192,168,0,91);
IPAddress gateway(192,168,0,1);
IPAddress subnet(255,255,255,0);
#endif

#include "coredecls.h"
#define DHTTYPE DHT11
#define DHTPIN 2
DHT dht(DHTPIN, DHTTYPE, 12); // 11 works fine for ESP8266

const char* ssid = "SHAW-62CD10";
const char* password = "251169025293";
float hum;
float temp;

unsigned long previousMillis = 0; // will store last temp was read
const long interval = 4000;

extern "C"{
#include "homeintegration.h"
}
#include "homekitintegrationcpp.h"

String pair_file_name="/pair.dat";

//**********************
void init_hap_storage(){

Serial.print("init_hap_storage");

File fsDAT=SPIFFS.open(pair_file_name, "r");
if(!fsDAT){
Serial.println("Failed to read pair.dat");
return;
}
int size=hap_get_storage_size_ex();
char* buf=new char[size];
memset(buf,0xff,size);
int readed=fsDAT.readBytes(buf,size);
Serial.print("Readed bytes ->");
Serial.println(readed);
hap_init_storage_ex(buf,size);
fsDAT.close();
delete []buf;

}
//*****************

//****************
void storage_changed(char * szstorage,int bufsize){

SPIFFS.remove(pair_file_name);
File fsDAT=SPIFFS.open(pair_file_name, "w+");
if(!fsDAT){
Serial.println("Failed to open pair.dat");
return;
}
fsDAT.write((uint8_t*)szstorage, bufsize);

fsDAT.close();
}
//********************
homekit_service_t* hapservice={0};
homekit_service_t* temperature;
homekit_service_t* humidity;

//////////////////////////////////
void setup() {
disable_extra4k_at_link_time();
Serial.begin(115200);
delay(3000);
Format();

 if (!SPIFFS.begin()) {
  Serial.print("SPIFFS Mount failed");
 }

Serial.print("Attempting connection to: ");
Serial.println(ssid);

WiFi.mode(WIFI_STA);
WiFi.begin((char*)ssid, (char*)password);

#ifdef STATIC_IP_ADDR
WiFi.config(staticIP, gateway, subnet);
#endif
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
WiFi.begin(ssid, password);
}
Serial.println("");
Serial.println("WiFi connected!");
#ifdef STATIC_IP_ADDR
Serial.print("Static IP address: ");
#else
Serial.print("Dinamic IP address: ");
#endif

Serial.println(WiFi.localIP());

/// now will setup homekit device

//this is for custom storaage usage
// In given example we are using \pair.dat   file in our spiffs system
//see implementation below
Serial.print("Free heap: ");
Serial.println(system_get_free_heap_size());


init_hap_storage();

set_callback_storage_change(storage_changed);

/// We will use for this example only one accessory (possible to use a several on the same esp)
//Our accessory type is light bulb , apple interface will proper show that
hap_setbase_accessorytype(homekit_accessory_category_thermostat);
/// init base properties
hap_initbase_accessory_service("Environment Sensor","SeaMaster","258521521","DHT11_ESP8266","1.0");

//we will add only one light bulb service and keep pointer for nest using

temperature = hap_add_temperature_service("Temperature");
humidity =   hap_add_humidity_service("Humidity");

//and finally init HAP

hap_init_homekit_server();   

}

////////////////////////////////

void loop() {

hap_homekit_loop();
delay(10);
unsigned long currentMillis = millis();

if (currentMillis - previousMillis >= interval) {
// save the last time you read the sensor
previousMillis = currentMillis;

// Reading temperature for humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
hum = dht.readHumidity();          // Read humidity (percent)
temp = dht.readTemperature(false);     // Read temperature as Fahrenheit

Serial.println(temp); // Check if any reads failed and exit early (to try again).
if (isnan(hum) || isnan(temp)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
}
homekit_characteristic_t * ch= homekit_service_characteristic_by_type(temperature, HOMEKIT_CHARACTERISTIC_CURRENT_TEMPERATURE);
ch->value.float_value=temp;
homekit_characteristic_notify(ch,ch->value);
delay(10);
homekit_characteristic_t * ch2= homekit_service_characteristic_by_type(humidity, HOMEKIT_CHARACTERISTIC_CURRENT_RELATIVE_HUMIDITY);
ch2->value.float_value=hum;
homekit_characteristic_notify(ch2,ch2->value);

delay(10);
}

void Format(){
// Next lines have to be done ONLY ONCE!!!!!When SPIFFS is formatted ONCE you can comment these lines out!!
Serial.println("Please wait 30 secs for SPIFFS to be formatted");
SPIFFS.format();
Serial.println("Spiffs formatted");
}`

@Yurik72
Copy link
Owner

Yurik72 commented Apr 3, 2020 via email

@seamaster101
Copy link
Author

seamaster101 commented Apr 3, 2020 via email

@Yurik72
Copy link
Owner

Yurik72 commented Apr 4, 2020 via email

Yurik72 added a commit that referenced this issue Apr 6, 2020
@Yurik72
Copy link
Owner

Yurik72 commented Apr 6, 2020

Step by step,
Zero values to Apple:
In your sketch at the begin please define
#define HOMEKIT_SHORT_APPLE_UUIDS

EspHap library for ESP8266 uses short UUIDs, but sketch still used long, therefore code
HOMEKIT_CHARACTERISTIC_CURRENT_TEMPERATURE);
ch->value.float_value=temp;
homekit_characteristic_notify(ch,ch->value);
is not works and characteristic not found

@Yurik72
Copy link
Owner

Yurik72 commented Apr 6, 2020

Second , how to create two icons
first device/icons is a temperature, code
hap_setbase_accessorytype(homekit_accessory_category_thermostat);
hap_initbase_accessory_service("Environment Sensor","SeaMaster","258521521","DHT11_ESP8266","1.0");
temperature = hap_add_temperature_service("Temperature");

Than you need add second device/icons and code

humidity=hap_add_hum_as_accessory(homekit_accessory_category_thermostat,"Humidity");

//This will add second device/icons only with humidity
The rest code is OK.

P.S. You should use the latest version of ESP hap

@Yurik72 Yurik72 closed this as completed Apr 6, 2020
@seamaster101
Copy link
Author

seamaster101 commented Apr 6, 2020 via email

@seamaster101
Copy link
Author

Please ignore "Third and maybe... "
this one was resolved by using library with interrupt for DHT11. Now reeds the temperature and humidity OK, but only have the setup screen for humidity, and does not show humidity Icon. this is back too the second issue.
please provide example if you could for one service with 2 accessories.

there is also another thing that I don't understand:
if I enable
format();
it logs ok on the network, but I need to reconnect to apple HomeKit on every restart as it looses the configuration data.
if I I disable the
//format();
my esp8266 will not connect to the network and it is serial is outputing only "................." every time I restart. I'm not sure how I suppose to use the format(); function

@Yurik72
Copy link
Owner

Yurik72 commented Apr 7, 2020

Two icons: I have provided example yesterday
There is a new function in the library
humidity=hap_add_hum_as_accessory(homekit_accessory_category_thermostat,"Humidity");

Therefore you need to get latest version to resolve compilation error

About format, in My original example there is no function format. If you formatting SPIFFS every start , you are loosing pairing data. In my instruction i mentioned about format only when pairing not sucess.

@seamaster101
Copy link
Author


IMG_8577
IMG_8576
IMG_8578

@seamaster101
Copy link
Author

seamaster101 commented Apr 7, 2020

Better but still not properly displayed:
1st image above is I get Humidity, but just the setup screen for it.

2nd image I got the temperature properly but by itself - no humidity icon and symbol

3rd image is accessory from another sketch that used HomeBridge and it is displaying temperature and humidity on one accessory and that is what I was hoping to accomplish but without the need of Homebridge. it appears we are close, but not quite there yet...

4th image is from my "Home" screen. Note that the "Humidity" icon is actually a temperature icon and shows always "updating".
Serial Monitor has constant stream rushing the that says something like:
`

HomeKit: [Client 1073692820] Got characteristic 1.10 change event
HomeKit: [Client 1073693444] Got characteristic 1.10 change event
HomeKit: [Client 1073692820] Got characteristic 2.10 change event
HomeKit: [Client 1073693444] Got characteristic 2.10 change event
HomeKit: [Client 1073692820] Got characteristic 1.10 change event
HomeKit: [Client 1073693444] Got characteristic 1.10 change event
HomeKit: [Client 1073692820] Got characteristic 2.10 change event
etc, etc. that continues for a while and then I get this repeating:!!! HomeKit: [Client 1073692820] error_in_write_data is true, abort write data
!!! HomeKit: [Client 1073692820] error_in_write_data is true, abort write data
!!! HomeKit: [Client 1073692820] error_in_write_data is true, abort write data
HomeKit: [Client 1073692820] Got characteristic 1.10 change event
HomeKit: [Client 1073693444] Got characteristic 1.10 change event
HomeKit: [Client 1073692820] Got characteristic 2.10 change event
HomeKit: [Client 1073693444] Got characteristic 2.10 change event
!!! HomeKit: [Client 1073692820] error_in_write_data is true, abort write data
!!! HomeKit: [Client 1073692820] error_in_write_data is true, abort write data
!!! HomeKit: [Client 1073692820] error_in_write_data is true, abort write data
`

On the picture below notice that Default Room Humidity always show "Updating..."
maybe that has something to do with this write data error?

IMG_8579

the serial monitor stream was so fast that overloaded the application and I had to forcibly quit it and reload it.

@Yurik72
Copy link
Owner

Yurik72 commented Apr 7, 2020

About icon
It depends from the accessory type,
I have suggested - homekit_accessory_category_thermostat
humidity=hap_add_hum_as_accessory(homekit_accessory_category_thermostat,"Humidity");

Probably you need
humidity=hap_add_hum_as_accessory(homekit_accessory_category_humidifier ,"Humidity");

As well you can edit icon on Apple to define category
Full enumerable is
typedef enum {
homekit_accessory_category_other = 1,
homekit_accessory_category_bridge = 2,
homekit_accessory_category_fan = 3,
homekit_accessory_category_garage = 4,
homekit_accessory_category_lightbulb = 5,
homekit_accessory_category_door_lock = 6,
homekit_accessory_category_outlet = 7,
homekit_accessory_category_switch = 8,
homekit_accessory_category_thermostat = 9,
homekit_accessory_category_sensor = 10,
homekit_accessory_category_security_system = 11,
homekit_accessory_category_door = 12,
homekit_accessory_category_window = 13,
homekit_accessory_category_window_covering = 14,
homekit_accessory_category_programmable_switch = 15,
homekit_accessory_category_range_extender = 16,
homekit_accessory_category_ip_camera = 17,
homekit_accessory_category_video_door_bell = 18,
homekit_accessory_category_air_purifier = 19,
homekit_accessory_category_heater = 20,
homekit_accessory_category_air_conditioner = 21,
homekit_accessory_category_humidifier = 22,
homekit_accessory_category_dehumidifier = 23,
homekit_accessory_category_apple_tv = 24,
homekit_accessory_category_speaker = 26,
homekit_accessory_category_airport = 27,
homekit_accessory_category_sprinkler = 28,
homekit_accessory_category_faucet = 29,
homekit_accessory_category_shower_head = 30,
homekit_accessory_category_television = 31,
homekit_accessory_category_target_controller = 32,
} homekit_accessory_category_t;

"Updating.." means apple did not receive characheristic, i need a full logs to help
In my case i have tested Apple within a few devices without problem. Not Temperthure + Humidity combination, but definetelly question is not about combination, something else If you will fall again, probably to help i need your full sketch ,

@seamaster101
Copy link
Author

seamaster101 commented Apr 8, 2020

Thank you for following up!
I wrote little user input routine in the setup(); to deal with the formatting if the painting fails.
this is resolved now.
what needs to be addressed is showing the two readings under one accessory as in the picture I showed you with the DHT11 and HomeBridge. and of course most importantly is the excessive chatter over the serial monitor with these messages flying too fast and bugging it down. clear indication that something is not right...

Here is my sketch:


`//ESP8266 with DHT11 sketch
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
//#include <FS.h>
//#include <SPIFFS.h>
#define STATIC_IP_ADDR

///---DHT11-----///
#include "PietteTech_DHT.h" // Uncommend if building using CLI
#define DHTTYPE DHT11 // Sensor type DHT11/21/22/AM2301/AM2302
#define DHTPIN 2 // Digital pin for communications
#define PIN 0 // Digital pin for re-format
//declaration
void dht_wrapper(); // must be declared before the lib initialization
///---DHT11 stop-----///

#ifdef STATIC_IP_ADDR
IPAddress staticIP(192,168,0,91);
IPAddress gateway(192,168,0,1);
IPAddress subnet(255,255,255,0);
#endif
#define HOMEKIT_SHORT_APPLE_UUIDS
#include "coredecls.h"

const char* ssid = "XXXXXXXX";
const char* password = "XXXXXXXX";
float hum;
float temp;

const long userdelay = 3000; //delay for user input when tarting to format the SPIFFS
unsigned long previousMillis = 0;
unsigned long prevMillis = 0;
const long interval = 15000;
unsigned long currentMillis = 0;
unsigned long currMillis = 0;

extern "C"{
#include "homeintegration.h"
}
#include "homekitintegrationcpp.h"

String pair_file_name="/pair.dat";
///---DHT11-----///
// Lib instantiate
PietteTech_DHT DHT(DHTPIN, DHTTYPE, dht_wrapper);
int n; // counter
///---DHT11 stop-----///

//**********************
void init_hap_storage(){
Serial.print("init_hap_storage");
File fsDAT=SPIFFS.open(pair_file_name, "r");
if(!fsDAT){
Serial.println("Failed to read pair.dat");
return;
}
int size=hap_get_storage_size_ex();
char* buf=new char[size];
memset(buf,0xff,size);
int readed=fsDAT.readBytes(buf,size);
Serial.print("Readed bytes ->");
Serial.println(readed);
hap_init_storage_ex(buf,size);
fsDAT.close();
delete []buf;
}
//*****************

//****************
void storage_changed(char * szstorage,int bufsize){
SPIFFS.remove(pair_file_name);
File fsDAT=SPIFFS.open(pair_file_name, "w+");
if(!fsDAT){
Serial.println("Failed to open pair.dat");
return;
}
fsDAT.write((uint8_t*)szstorage, bufsize);
fsDAT.close();
}
//********************
//homekit_service_t* hapservice={0};
homekit_service_t* temperature;
homekit_service_t* humidity;
//********************

//////////////////////////////////
void setup() {
disable_extra4k_at_link_time();
Serial.begin(74880);
delay(100);

//Enble format only when pairing fails
prevMillis=millis();
currMillis = prevMillis + userdelay;

//ask for user input
Serial.println("Should I format the SPIFFS? "); //it should wait for userdelay/1000 seconds for user input

while (currMillis >= prevMillis && (digitalRead(PIN) == HIGH) ){
prevMillis = millis();

delay(1000);
Serial.println(round((userdelay-prevMillis)/1000));
if (currMillis <= prevMillis) {
Serial.println("5 seconds are over");
delay (100);
break;
}
else{ if (digitalRead(PIN) == LOW){
Serial.println("Formating...");
Format();
delay (100);
break;
}
}
}

//
if (!SPIFFS.begin()) {
Serial.print("SPIFFS Mount failed");
} else {
Serial.println("SPIFFS Mount OK");
}
Serial.print("Attempting connection to: ");
Serial.println(ssid);
delay(10);
WiFi.mode(WIFI_STA);
delay(10);
/// Working every time ESP8266 WIFI initialization
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("Not connected");
WiFi.begin((char*)ssid, (char*)password);
} else {
Serial.println("Connected");
}
#ifdef STATIC_IP_ADDR
WiFi.config(staticIP, gateway, subnet);
#endif
Serial.println("");
Serial.println("WiFi connected!");
#ifdef STATIC_IP_ADDR
Serial.print("Static IP address: ");
#else
Serial.print("Dinamic IP address: ");
#endif
Serial.println(WiFi.localIP());
Serial.print("WiFi Status: ");
Serial.println(WiFi.status());

///---Setup homekit device---///
//this is for custom storage usage
// In given example we are using \pair.dat file in our spiffs system
//see implementation below
Serial.print("Free heap: ");
Serial.println(system_get_free_heap_size());
init_hap_storage();
set_callback_storage_change(storage_changed);
///---Adding Accessory---///
/// We will use for this example only one accessory (possible to use a several on the same esp)
//Our accessory type is thermostat, ???apple interface will proper show that???
// hap_setbase_accessorytype(homekit_accessory_category_thermostat); //old definition replaced by the line below
hap_setbase_accessorytype(homekit_accessory_category_humidifier);
///--- init base properties---///
hap_initbase_accessory_service("Environment Sensor","SeaMaster","258521521","DHT11_ESP8266","1.0");
// we will add ??temprature service and humifity accessory?? and keep pointer for nest using
temperature = hap_add_temperature_service("Temperature");
//humidity = hap_add_humidity_service("Humidity"); //old definition replaced by the line below
humidity=hap_add_hum_as_accessory(homekit_accessory_category_humidifier ,"Humidity");

///---Setup homekit device stop---///

///---initialize HAP---///

hap_init_homekit_server();

///---initialize HAP stop---///

///---End of setup()---///
}

///---DHT11 interrupt callback---///

void ICACHE_RAM_ATTR dht_wrapper() {
DHT.isrCallback();

}
///---DHT11 interrupt callback stop---///

///////////////////////////////

void loop() {

///---Reading the DHT11 sensor---///
// Reading temperature for humidity takes about 250 milliseconds!
// this sensor should not be polled more often then 2 sec apart
unsigned long currentMillis = millis();
int result = DHT.acquireAndWait(0);
if (currentMillis - previousMillis >= interval) {
// save the last time you read the sensor
previousMillis = currentMillis;
temp = DHT.getCelsius(); // Read temperature as Celsius
hum = DHT.getHumidity(); // Read humidity (percent)
Serial.print("Temperature: ");
Serial.println(temp); // Check if any reads failed and exit early (to try again).
Serial.print("Humidity: ");
Serial.println(hum); // Check if any reads failed and exit early (to try again).
if (isnan(hum) || isnan(temp)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
}

hap_homekit_loop(); //what does this exactly do?????
delay(10);

homekit_characteristic_t * ch1= homekit_service_characteristic_by_type(temperature, HOMEKIT_CHARACTERISTIC_CURRENT_TEMPERATURE);
ch1->value.float_value=temp;
homekit_characteristic_notify(ch1,ch1->value);
delay(10);

homekit_characteristic_t * ch2= homekit_service_characteristic_by_type(humidity, HOMEKIT_CHARACTERISTIC_CURRENT_RELATIVE_HUMIDITY);
ch2->value.float_value=hum;
homekit_characteristic_notify(ch2,ch2->value);
delay(10);

///--- end of the main loop ---///
}

///--- Formating function ---///
void Format(){
// Next lines have to be done ONLY ONCE!!!!!When SPIFFS is formatted ONCE you can comment these lines out!!
Serial.println("Please wait 30 secs for SPIFFS to be formatted");
SPIFFS.format();
Serial.println("Spiffs formatted");
}`


@seamaster101
Copy link
Author

Hi,
Any luck looking through my code to see why displaying humidity is not correct?

After playing around for a while, I could not make it show properly even if it is the only service/accessory in the sketch and even if I hardcoded the hum var to let's say 55% . It always shows "Updating..." even when it reads the correct data from the sensor. yet it shows the proper number in the setup screen. Could it be a problem with this specific CHARACTERISTIC somewhere in the library, or I'm dong it wrong all together?

@oxbown
Copy link
Contributor

oxbown commented Apr 17, 2020

#7 I think I´ve got the bug that makes humidity sensors showing the incorrect icon and "updating" status...

@Yurik72
Copy link
Owner

Yurik72 commented Apr 17, 2020

Yes, I found a mistake, #7 one of the problem,
Second problem: primary property must be set to true for Humidity and Temperature sensors

And finally , if you made pairing and after that added new accessory in the code. Better to clear all pairing again..

I have tested my device with BME280 and it shows temp and humidity perfectly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants