DHT 22 не показывает минусовую температуру
- Войдите на сайт для отправки комментариев
Пт, 04/01/2013 - 15:03
Здравствуйте! У меня есть такая проблема: DHT 22 не показывает минусовую температуру. Решение, взятое отсюда http://forum.amperka.ru/threads/dht-22-%D0%BD%D0%B5-%D0%BF%D0%BE%D0%BA%D0%B0%D0%B7%D1%8B%D0%B2%D0%B0%D0%B5%D1%82-%D0%BC%D0%B8%D0%BD%D1%83%D1%81%D0%BE%D0%B2%D1%83%D1%8E-%D1%82%D0%B5%D0%BC%D0%BF%D0%B5%D1%80%D0%B0%D1%82%D1%83%D1%80%D1%83.921/ не помогло(((
файл .cpp библиотеки тут:
#ifndef DHT11_H
#include "dht22.h"
//######### Initialization and Pin Structures ###################
dht22::dht22()
{
attach(2);//this is the default pin
}
dht22::dht22(int pin)
{
attach(pin);
}
//this will allow the bus of an instance of this library to be changed
dht22::dht22(int pin, VersalinoBUS myBUS)
{
attach(pin, myBUS);
}
void dht22::attach(int pin, VersalinoBUS myBUS)
{
_sensorPin = pin;
_myBUS = myBUS;
_BUSenabled = true;
}
void dht22::attach(int pin)
{
_sensorPin = pin;
_BUSenabled = false;
}
//This will return the VersalinoBUS currently assigned to the instance of this library
VersalinoBUS dht22::getBUS()
{
return _myBUS;
}
void dht22::removeBUS()
{
_BUSenabled=false;
}
void dht22::setBUS(VersalinoBUS myBUS)
{
_myBUS = myBUS;
_BUSenabled=true;
}
//##################################################################
//##########################read DHT11##############################
// returnvalues:
// 0 : OK
// -1 : checksum error
// -2 : timeout
int dht22::read()
{
if(_BUSenabled)
return read(_myBUS.PINS[_sensorPin]);//if a BUS is attached then read using the Versalino Library
else
return read(_sensorPin);//reads from attached sensorPin (attach command must be run first or this will use the default pin 2)
}
int dht22::read(int pin, VersalinoBUS myBUS)
{
return read(myBUS.PINS[pin]);//read from a pin on a VersalinoBUS using the Versalino Library
}
int dht22::read(int pin)
{
// BUFFER TO RECEIVE
uint8_t bits[5];
uint8_t cnt = 7;
uint8_t idx = 0;
// EMPTY BUFFER
for (int i=0; i< 5; i++) bits[i] = 0;
// REQUEST SAMPLE
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(18);
digitalWrite(pin, HIGH);
delayMicroseconds(40);
pinMode(pin, INPUT);
// ACKNOWLEDGE or TIMEOUT
unsigned int loopCnt = 10000;
while(digitalRead(pin) == LOW)
if (loopCnt-- == 0) return -2;
loopCnt = 10000;
while(digitalRead(pin) == HIGH)
if (loopCnt-- == 0) return -2;
// READ OUTPUT - 40 BITS => 5 BYTES or TIMEOUT
for (int i=0; i<40; i++)
{
loopCnt = 10000;
while(digitalRead(pin) == LOW)
if (loopCnt-- == 0) return -2;
unsigned long t = micros();
loopCnt = 10000;
while(digitalRead(pin) == HIGH)
if (loopCnt-- == 0) return -2;
if ((micros() - t) > 40) bits[idx] |= (1 << cnt);
if (cnt == 0) // next byte?
{
cnt = 7; // restart at MSB
idx++; // next byte!
}
else cnt--;
}
// WRITE TO RIGHT VARS
humidity = word(bits[0], bits[1]) * 0.1;//calculates and stores the humidity
uint8_t sign = 1;
if (bits[2] & 0x80) // negative temperature
{
bits[2] = bits[2] & 0x7F;//negative temp adjustments
sign = -1;
}
temperature = sign * word(bits[2], bits[3]) * 0.1;//temp calculation and storage, change na -0.1
uint8_t sum = bits[0] + bits[1] + bits[2] + bits[3];//sum values
if (bits[4] != sum) return -1;//failed checksum
return 0;//great success!
}
//##################################################################
//###############UNIT CONVERSIONS & CALCULATIONS####################
double dht22::celcius()
{
read();//make sure the temp has been read
return temperature;
}
//Celsius to Fahrenheit conversion
double dht22::fahrenheit(double dCelsius)
{
return 1.8 * dCelsius + 32;
}
double dht22::fahrenheit()
{
read();//make sure the temp has been read
return fahrenheit(temperature);
}
//Celsius to Kelvin conversion
double dht22::kelvin(double dCelsius)
{
return dCelsius + 273.15;
}
double dht22::kelvin()
{
read();
return kelvin(temperature);
}
// dewPoint function NOAA
// reference: http://wahiduddin.net/calc/density_algorithms.htm
double dht22::dewPoint()
{
read();//make sure the temp has been read
double A0= 373.15/(273.15 + temperature);
double SUM = -7.90298 * (A0-1);
SUM += 5.02808 * log10(A0);
SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
SUM += log10(1013.246);
double VP = pow(10, SUM-3) * humidity;
double T = log(VP/0.61078); // temp var
return (241.88 * T) / (17.558-T);
}
// delta max = 0.6544 wrt dewPoint()
// 5x faster than dewPoint()
// reference: http://en.wikipedia.org/wiki/Dew_point
double dht22::dewPointFast()
{
read();//make sure the temp has been read
double a = 17.271;
double b = 237.7;
double temp = (a * temperature) / (b + temperature) + log((double) humidity/100);
double Td = (b * temp) / (a - temp);
return Td;
}
//###############################################################
#endif // DHT22_H
собственно сам скретч
#include <dht22.h>
dht22 DHT22;
void setup()
{
DHT22.attach(7);
Serial.begin(9600);
Serial.println("DHT22 TEST PROGRAM ");
Serial.print("LIBRARY VERSION: ");
Serial.println(DHT22LIB_VERSION);
}
void loop()
{
Serial.println("\n");
int chk = DHT22.read();
// Serial.print("Read sensor: ");
switch (chk)
{
case 0: Serial.println("OK"); break;
case -1: Serial.println("Checksum error"); break;
case -2: Serial.println("Time out error"); break;
default: Serial.println("Unknown error"); break;
}
Serial.print("Humidity (%): ");
Serial.println((float)DHT22.humidity, 2);
Serial.print("Temperature (°C): ");
Serial.println((float)DHT22.temperature, 2);
delay(2000);
}
Вопрос, что здесь не так???
А попробуйте другую либу:
http://playground.arduino.cc/Main/DHTLib/
как с ней себя поведет?
вот данные по https://github.com/ringerc/Arduino-DHT22 с http://playground.arduino.cc/Main/DHTLib/
то что у меня было при использовании начальной библиотеки
датчиков у меня 3- на всех одинаковые результаты...
Хм... очень похоже что где-то в безнаковый тип происходит ошибочная конвертация... но не видно на беглый вгляд где.
А вот еще одна библа
https://github.com/adafruit/DHT-sensor-library
Вот тут человек тоже жаловался на глюки с отрицаловом, и эта библиотека вроде помогла.
Это либы такие кривые, ищите даташит и в нем описание протокола и как правильно считать температуру.
Обычно это 2 байта, минус определяется первым битом первого байта, первый байт это целые градусы, а второй то что после точки, причем когда минус второй байт ведет себя точно также как и при плюсе, то есть например: +1.3 и -1.7 при этих температурах во втором байте одно и тоже.
Вроде работает) Спасибо!!!
А скажите пожалуйсто, два DHT22 на один arduino пин можно вешать подобно ds18b20 или нет?
Думаю нет.
Со стандартными либами - точно нет. Пойдите от обратного.... а как вы их отличать будете? Никаких адресов при вызове функций - не видно.
Есть конечно призрачный шанс нарыть что нибудь в даташите и самому библиотеку писать... но сомневаюсь. По крайней мере я никаких упоминаний беглым взгядом там не увидел.
P.S. Самое смешное, что внутри этих DHT22 - использется ds18b20
Почему то не работает DHT 22 и ик приемник в паре. как только включается приемник показаний с дотчика DHT 22 нет.
//DFRobot.com #include <Wire.h> #include <LiquidCrystal_I2C.h> #include "DHT.h" #include <IRremote.h> #define DHTPIN 2 // what pin we're connected to // Uncomment whatever type you're using! //#define DHTTYPE DHT11 // DHT 11 #define DHTTYPE DHT22 // DHT 22 (AM2302) //#define DHTTYPE DHT21 // DHT 21 (AM2301) // Connect pin 1 (on the left) of the sensor to +5V // Connect pin 2 of the sensor to whatever your DHTPIN is // Connect pin 4 (on the right) of the sensor to GROUND // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor DHT dht(DHTPIN, DHTTYPE); LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display int RECV_PIN = 11; //вход ИК приемника IRrecv irrecv(RECV_PIN); decode_results results; int a=0; // переменная переключения режима, при нажатии кнопки она принимает значение +1 void setup() { irrecv.enableIRIn(); // включить приемниk pinMode(13, OUTPUT); lcd.init(); // initialize the lcd // Print a message to the LCD. lcd.backlight(); // lcd.print("Hello, world!"); dht.begin(); } void loop() { if (irrecv.decode(&results)) { delay(300); // задержка перед выполнением определения кнопок, чтобы избежать быстрое двойное нажатие if (results.value == 0xFFA25D) {a=a+1;} // обработка нажитя клавиши, здесь переменная принимает значение +1 if (a==1){digitalWrite(13, HIGH);} else {digitalWrite(13, LOW); a=0;} // действие после нажатия кнопки, если переменная стала равна 1 то { // delay(50); //пауза между повторами // } // irrecv.resume(); // // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float h = dht.readHumidity(); float t = dht.readTemperature(); lcd.begin(20, 4); lcd.print("Humidity: "); lcd.setCursor(11, 0); lcd.print(h); lcd.setCursor(0, 1); lcd.print("Temp: "); lcd.setCursor(11, 1); lcd.print(t); }}Ошибка