DHT testprogram

Dependencies:   mbed

Files at this revision

API Documentation at this revision

Comitter:
Wimpie
Date:
Tue Jul 10 13:11:23 2012 +0000
Commit message:

Changed in this revision

DHT/DHT.cpp Show annotated file Show diff for this revision Revisions of this file
DHT/DHT.h Show annotated file Show diff for this revision Revisions of this file
Debug/DebugTrace.cpp Show annotated file Show diff for this revision Revisions of this file
Debug/DebugTrace.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/DHT/DHT.cpp	Tue Jul 10 13:11:23 2012 +0000
@@ -0,0 +1,233 @@
+/*
+ *  DHT Library for  Digital-output Humidity and Temperature sensors
+ *
+ *  Works with DHT11, DHT22
+ *             SEN11301P,  Grove - Temperature&Humidity Sensor     (Seeed Studio)
+ *             SEN51035P,  Grove - Temperature&Humidity Sensor Pro (Seeed Studio)
+ *             AM2302   ,  temperature-humidity sensor
+ *             HM2303   ,  Digital-output humidity and temperature sensor
+ *
+ *  Copyright (C) Wim De Roeve
+ *                based on DHT22 sensor library by HO WING KIT
+ *                Arduino DHT11 library 
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documnetation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to  whom the Software is
+ * furished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include "DHT.h"
+
+#define DHT_DATA_BIT_COUNT 41
+
+DHT::DHT(PinName pin,int DHTtype) {
+    _pin = pin;
+    _DHTtype = DHTtype;
+    _firsttime=true;
+}
+
+DHT::~DHT() {
+}
+
+int DHT::readData() {
+    int i, j, retryCount,b;
+    unsigned int bitTimes[DHT_DATA_BIT_COUNT];
+
+    eError err = ERROR_NONE;
+    time_t currentTime = time(NULL);
+
+    DigitalInOut DHT_io(_pin);
+
+    for (i = 0; i < DHT_DATA_BIT_COUNT; i++) {
+        bitTimes[i] = 0;
+    }
+
+    if (!_firsttime) {
+        if (int(currentTime - _lastReadTime) < 2) {
+            err = ERROR_NO_PATIENCE;
+            return err;
+        }
+    } else {
+        _firsttime=false;
+        _lastReadTime=currentTime;
+    }
+    retryCount = 0;
+
+    do {
+        if (retryCount > 125) {
+            err = BUS_BUSY;
+            return err;
+        }
+        retryCount ++;
+        wait_us(2);
+    } while ((DHT_io==0));
+
+
+    DHT_io.output();
+    DHT_io = 0;
+    wait_ms(18);
+    DHT_io = 1;
+    wait_us(40);
+    DHT_io.input();
+
+    retryCount = 0;
+    do {
+        if (retryCount > 40)  {
+            err = ERROR_NOT_PRESENT;
+            return err;
+        }
+        retryCount++;
+        wait_us(1);
+    } while ((DHT_io==1));
+
+    if (err != ERROR_NONE) {
+        return err;
+    }
+
+    wait_us(80);
+
+    for (i = 0; i < 5; i++) {
+        for (j = 0; j < 8; j++) {
+
+            retryCount = 0;
+            do {
+                if (retryCount > 75)  {
+                    err = ERROR_DATA_TIMEOUT;
+                    return err;
+                }
+                retryCount++;
+                wait_us(1);
+            } while (DHT_io == 0);
+            wait_us(40);
+            bitTimes[i*8+j]=DHT_io;
+
+            int count = 0;
+            while (DHT_io == 1 && count < 100) {
+                wait_us(1);
+                count++;
+            }
+        }
+    }
+    DHT_io.output();
+    DHT_io = 1;
+    for (i = 0; i < 5; i++) {
+        b=0;
+        for (j=0; j<8; j++) {
+            if (bitTimes[i*8+j+1] > 0) {
+                b |= ( 1 << (7-j));
+            }
+        }
+        DHT_data[i]=b;
+    }
+
+    if (DHT_data[4] == ((DHT_data[0] + DHT_data[1] + DHT_data[2] + DHT_data[3]) & 0xFF)) {
+        _lastReadTime = currentTime;
+        _lastTemperature=CalcTemperature();
+        _lastHumidity=CalcHumidity();
+
+    } else {
+        err = ERROR_CHECKSUM;
+    }
+
+    return err;
+
+}
+
+float DHT::CalcTemperature() {
+    int v;
+
+    switch (_DHTtype) {
+        case DHT11:
+            v = DHT_data[2];
+            return float(v);
+        case DHT22:
+            v = DHT_data[2] & 0x7F;
+            v *= 256;
+            v += DHT_data[3];
+            v /= 10;
+            if (DHT_data[2] & 0x80)
+                v *= -1;
+            return float(v);
+    }
+    return 0;
+}
+
+float DHT::ReadHumidity() {
+    return _lastHumidity;
+}
+
+float DHT::ConvertCelciustoFarenheit(float celsius) {
+    return celsius * 9 / 5 + 32;
+}
+
+float DHT::ConvertCelciustoKelvin(float celsius) {
+    return celsius + 273.15;
+}
+
+// dewPoint function NOAA
+// reference: http://wahiduddin.net/calc/density_algorithms.htm
+float DHT::CalcdewPoint(float celsius, float humidity) {
+    float A0= 373.15/(273.15 + celsius);
+    float 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);
+    float VP = pow(10, SUM-3) * humidity;
+    float 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
+float DHT::CalcdewPointFast(float celsius, float humidity)
+{
+        float a = 17.271;
+        float b = 237.7;
+        float temp = (a * celsius) / (b + celsius) + log(humidity/100);
+        float Td = (b * temp) / (a - temp);
+        return Td;
+}
+
+float DHT::ReadTemperature(eScale Scale) {
+    if (Scale == FARENHEIT)
+        return ConvertCelciustoFarenheit(_lastTemperature);
+    else if (Scale == KELVIN)
+        return ConvertCelciustoKelvin(_lastTemperature);
+    else
+        return _lastTemperature;
+}
+
+float DHT::CalcHumidity() {
+    int v;
+
+    switch (_DHTtype) {
+        case DHT11:
+            v = DHT_data[0];
+            return float(v);
+        case DHT22:
+            v = DHT_data[0];
+            v *= 256;
+            v += DHT_data[1];
+            v /= 10;
+            return float(v);
+    }
+    return 0;
+}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/DHT/DHT.h	Tue Jul 10 13:11:23 2012 +0000
@@ -0,0 +1,94 @@
+/* 
+ *  DHT Library for  Digital-output Humidity and Temperature sensors 
+ *  
+ *  Works with DHT11, DHT21, DHT22
+ *             SEN11301P,  Grove - Temperature&Humidity Sensor     (Seeed Studio)
+ *             SEN51035P,  Grove - Temperature&Humidity Sensor Pro (Seeed Studio)
+ *             AM2302   ,  temperature-humidity sensor    
+ *             RHT01,RHT02, RHT03    ,  Humidity and Temperature Sensor         (Sparkfun)
+ *
+ *  Copyright (C) Wim De Roeve
+ *                based on DHT22 sensor library by HO WING KIT
+ *                Arduino DHT11 library
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documnetation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to  whom the Software is
+ * furished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef MBED_DHT_H
+#define MBED_DHT_H
+
+#include "mbed.h"
+
+enum eType{
+        DHT11     = 11,
+        SEN11301P = 11,
+        RHT01     = 11,
+        DHT22     = 22,
+        AM2302    = 22,
+        SEN51035P = 22,
+        RHT02     = 22,
+        RHT03     = 22
+    } ;
+
+enum eError {
+    ERROR_NONE = 0,
+    BUS_BUSY =1,
+    ERROR_NOT_PRESENT =2 ,
+    ERROR_ACK_TOO_LONG =3 ,
+    ERROR_SYNC_TIMEOUT = 4,
+    ERROR_DATA_TIMEOUT =5 ,
+    ERROR_CHECKSUM = 6,
+    ERROR_NO_PATIENCE =7
+} ;
+
+typedef enum {
+    CELCIUS =0 ,
+    FARENHEIT =1,
+    KELVIN=2
+} eScale;
+
+
+class DHT {
+
+public:
+
+    DHT(PinName pin,int DHTtype);
+    ~DHT();
+    int readData(void);
+    float ReadHumidity(void);
+    float ReadTemperature(eScale Scale);
+    float CalcdewPoint(float celsius, float humidity);
+    float CalcdewPointFast(float celsius, float humidity);
+
+private:
+    time_t  _lastReadTime;
+    float _lastTemperature;
+    float _lastHumidity;
+    PinName _pin;
+    bool _firsttime;
+    int _DHTtype;
+    int DHT_data[6];
+    float CalcTemperature();
+    float CalcHumidity();
+    float ConvertCelciustoFarenheit(float);
+    float ConvertCelciustoKelvin(float);
+
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Debug/DebugTrace.cpp	Tue Jul 10 13:11:23 2012 +0000
@@ -0,0 +1,138 @@
+/*
+* DebugTrace. Allows dumping debug messages/values to serial or
+* to file.
+*
+* Copyright (C) <2009> Petras Saduikis <petras@petras.co.uk>
+*
+* This file is part of DebugTrace.
+*
+* DebugTrace is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+*
+* DebugTrace is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with DebugTrace.  If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "DebugTrace.h"
+#include <mbed.h>
+#include <stdarg.h>
+//#include <string.h>
+
+Serial logSerial(USBTX, USBRX);
+//LocalFileSystem local("local");
+
+//const char* FILE_PATH = "/sd/";
+//const char* EXTN = ".bak";
+
+DebugTrace::DebugTrace(eLog on, eLogTarget mode)://, const char* fileName, int maxSize) :
+        enabled(on), logMode(mode) { //, maxFileSize(maxSize), currentFileSize(0), logFileStatus(0)
+    /*
+    // allocate memory for file name strings
+       int str_size = (strlen(fileName) + strlen(FILE_PATH) + strlen(EXTN) + 1) * sizeof(char);
+       logFile = (char*)malloc(str_size);
+       logFileBackup = (char*)malloc(str_size);
+
+       // add path to log file name
+       strcpy(logFile, FILE_PATH);
+       strcat(logFile, fileName);
+
+       // create backup file name
+       strcpy(logFileBackup, logFile);
+       strcpy(logFileBackup, strtok(logFileBackup, "."));
+       strcat(logFileBackup, EXTN);*/
+  //  logSerial.baud(115200);
+}
+
+
+DebugTrace::~DebugTrace() {
+    // dust to dust, ashes to ashes
+    /*if (logFile != NULL) free(logFile);
+    if (logFileBackup != NULL) free(logFileBackup);*/
+}
+
+void DebugTrace::clear() {
+    // don't care about whether these fail
+    /*remove(logFile);
+    remove(logFileBackup);*/
+}
+
+void DebugTrace::backupLog() {
+    // delete previous backup file
+    /*if (remove(logFileBackup))
+    {
+        // standard copy stuff
+        char ch;
+        FILE* to = fopen(logFileBackup, "wb");
+        if (NULL != to)
+        {
+            FILE* from = fopen(logFile, "rb");
+            if (NULL != from)
+            {
+                while(!feof(from))
+                {
+                    ch = fgetc(from);
+                    if (ferror(from)) break;
+
+                    if(!feof(from)) fputc(ch, to);
+                    if (ferror(to)) break;
+                }
+            }
+
+            if (NULL != from) fclose(from);
+            if (NULL != to) fclose(to);
+        }
+    }
+
+    // now delete the log file, so we are ready to start again
+    // even if backup creation failed - the show must go on!
+    logFileStatus = remove(logFile);*/
+}
+
+void DebugTrace::traceOut(const char* fmt, ...) {
+    if (enabled) {
+        va_list ap;            // argument list pointer
+        va_start(ap, fmt);
+
+        if (TO_SERIAL == logMode) {
+            vfprintf(logSerial, fmt, ap);
+           
+        } else { // TO_FILE
+            /*vfprintf(logSerial, fmt, ap);
+               if (0 == logFileStatus)    // otherwise we failed to remove a full log file
+               {
+                   // Write data to file. Note the file size may go over limit
+                   // as we check total size afterwards, using the size written to file.
+                   // This is not a big issue, as this mechanism is only here
+                   // to stop the file growing unchecked. Just remember log file sizes may
+                   // be some what over (as apposed to some what under), so don't push it
+                   // with the max file size.
+                   FILE* fp = fopen(logFile, "a");
+                   if (NULL == fp)
+                   {
+                       va_end(ap);
+                       return;
+                   }
+                   int size_written = vfprintf(fp, fmt, ap);
+                   fclose(fp);
+
+                   // check if we are over the max file size
+                   // if so backup file and start again
+                   currentFileSize += size_written;
+                   if (currentFileSize >= maxFileSize)
+                   {
+                       backupLog();
+                       currentFileSize = 0;
+                   }
+               }*/
+        }
+
+        va_end(ap);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Debug/DebugTrace.h	Tue Jul 10 13:11:23 2012 +0000
@@ -0,0 +1,51 @@
+/*
+* DebugTrace. Allows dumping debug messages/values to serial or
+* to file.
+*
+* Copyright (C) <2009> Petras Saduikis <petras@petras.co.uk>
+*
+* This file is part of DebugTrace.
+*
+* DebugTrace is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation, either version 3 of the License, or
+* (at your option) any later version.
+* 
+* DebugTrace is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with DebugTrace.  If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef SNATCH59_DEBUGTRACE_H
+#define SNATCH59_DEBUGTRACE_H
+
+enum eLog {OFF, ON};
+enum eLogTarget {TO_SERIAL, TO_FILE};
+
+class DebugTrace
+{
+public:
+   
+    DebugTrace(eLog on, eLogTarget mode);//, const char* fileName = "debuglog.txt", const int maxSize = 4194304);
+    ~DebugTrace();
+  //  char message[80];
+    void clear();
+    void traceOut(const char* fmt, ...);
+    
+private:
+    eLog enabled;
+    eLogTarget logMode;
+  /*  int maxFileSize;
+    int currentFileSize;
+    char* logFile;
+    char* logFileBackup;
+    int logFileStatus;            // if things go wrong, don't write any more data to file*/
+    
+    void backupLog();
+};
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Tue Jul 10 13:11:23 2012 +0000
@@ -0,0 +1,28 @@
+#include "mbed.h"
+#include "DHT.h"
+
+DigitalOut myled(LED1);
+
+DHT sensor(p23,SEN11301P); // Use the SEN11301P sensor
+
+int main() {
+    int err;
+    printf("\r\nDHT Test program");
+    printf("\r\n******************\r\n");
+    wait(1); // wait 1 second for device stable status
+    while (1) {
+        myled = 1;
+        err = sensor.readData();
+        if (err == 0) {
+            printf("Temperature is %4.2f C \r\n",sensor.ReadTemperature(CELCIUS));
+            printf("Temperature is %4.2f F \r\n",sensor.ReadTemperature(FARENHEIT));
+            printf("Temperature is %4.2f K \r\n",sensor.ReadTemperature(KELVIN));
+            printf("Humidity is %4.2f \r\n",sensor.ReadHumidity());
+            printf("Dew point is %4.2f  \r\n",sensor.CalcdewPoint(sensor.ReadTemperature(CELCIUS), sensor.ReadHumidity()));
+            printf("Dew point (fast) is %4.2f  \r\n",sensor.CalcdewPointFast(sensor.ReadTemperature(CELCIUS), sensor.ReadHumidity()));
+        } else
+            printf("\r\nErr %i \n",err);
+        myled = 0;
+        wait(5);
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed.bld	Tue Jul 10 13:11:23 2012 +0000
@@ -0,0 +1,1 @@
+http://mbed.org/users/mbed_official/code/mbed/builds/737756e0b479