Table of Contents

Temperature Verification System for CPD (Raspi)

Initial Raspberry Pi Setup

See chapter on Initial Raspberry Pi Setup

OS for RPI

Download the Raspbian/Lite image from https://www.raspberrypi.org/downloads/raspbian/

Download the Win32 Disk Imager program from http://sourceforge.net/projects/win32diskimager/

Start Win32 Disk Imager and select the downloaded Raspbian image (.img file) with the “Image File” selector. Choose the drive letter where the SD card is and click “Write”.

Imager will ask for confirmation to overwrite. Select “Yes”. Wait for the confirmation and click “OK”, then close Disk Imager and remove the SD card.

Basic Raspberry Pi Setup

Insert the SD card into the Raspberry Pi (connect the keyboard and display before connecting the power).

The Raspberry Pi will boot and ask for a username and password.

By default, they are:

username: pi

password: raspberry

After booting, you can enter the configuration with:

sudo raspi-config

In the configuration:

  1. Change password/username if needed
  2. Configure boot to console, smb option 1, console.
  3. Adjust/check time/language/keyboard settings.
  4. In the interfacing options, select P2 - SSH enable
  5. Open advanced options → Expand filesystem

Finally, go to “Finish” and reboot the Raspberry Pi with:

sudo reboot

PC Connection (SSH)

From Windows, you can use PuTTY: http://www.chiark.greenend.org.uk/~sgtatham/putty….

To find the Raspberry Pi's IP, you can use:

ifconfig

Sensor Wiring

Install DHT22 Libraries

Update the Raspberry Pi:

sudo apt-get update
 
sudo apt-get upgrade

Install Adafruit Python code, necessary for reading the DHT22 sensor. It also allows checking if everything is set up correctly.

First, install the compiler and Python library:

sudo apt-get install build-essential python-dev python-openssl

Navigate to the directory where you want to install the Adafruit code, by default /home/.

cd /home/pi

You may need to install Git if it's not included by default:

sudo apt-get install git

Clone the git repository:

git clone https://github.com/adafruit/Adafruit_Python_DHT.g...

Go to the corresponding directory:

cd Adafruit_Python_DHT

And finally, install the Adafruit library. Type the following and press enter:

sudo python setup.py install

DHT22 Test

Navigate to the Adafruit_Python_DHT directory and then to the examples directory. Enter the following and press enter.

cd /home/pi/Adafruit_Python_DHT/examples

Test the operation with:

sudo ./AdafruitDHT.py sensortype GPIO

In the case of the wiring from the text:

sudo ./AdafruitDHT.py 22 4

If everything is correct, the sensor reading will appear.

MySQL Configuration for Storing Temperature Data

Install MySQL/MariaDB and the necessary plugins:

sudo apt-get install mysql-server python-mysqldb

Enter the SQL console:

sudo mysql -u root -p -h localhost

Press Enter for the password (empty), and we will enter the MariaDB console.

On the console:

First, create a database called temperatures:

CREATE DATABASE temperatures;

Select the created database:

USE temperatures;

Create a user and grant access to the database to this user:

CREATE USER 'logger'@'localhost' IDENTIFIED BY 'password';
 
GRANT ALL PRIVILEGES ON temperatures.* TO 'logger'@'localhost';
 
FLUSH PRIVILEGES;

The user/privileges are created. Now, you can switch from the root user to this new user:

quit

Reconnect with the new user:

sudo mysql -u logger -p -h localhost

Enter the password created earlier.

Create two tables: `temperaturedata` to store the sensor data (date/time, sensor, temperature, humidity) and `mailsendlog` with information about emails triggered by temperature limits.

To create the tables:

USE temperatures;

Create the first table with columns for date/time, sensor, temperature, and humidity:

CREATE TABLE temperaturedata (dateandtime DATETIME, sensor VARCHAR(32), temperature DOUBLE, humidity DOUBLE);

Create the second table with columns for date/time, triggered sensor, triggered limit, and last temperature:

CREATE TABLE mailsendlog (mailsendtime DATETIME, triggedsensor VARCHAR(32), triggedlimit VARCHAR(10), lasttemperature VARCHAR(10));

You can confirm that the empty tables were created with:

SELECT * FROM mailsendlog;
SELECT * FROM temperaturedata;

If the tables exist, you will see: “Empty Set (0.00 sec)”

The database is configured, and you can exit MySQL:

quit

Restart MySQL to apply the changes:

sudo /etc/init.d/mysql restart

Temperature Logger Code

Make sure you are in the directory where you want to install the DHT22-TemperatureLogger, by default /home/pi/:

cd /home/pi

Clone the git repository:

git clone https://github.com/jjpFin/DHT22-TemperatureLogger

Go to the DHT22-TemperatureLogger directory:

cd /home/pi/DHT22-TemperatureLogger

Open `config.json` in an editor:

sudo nano config.json

Configuration list:

#mysql: Database configuration.
 
#sensors: Configuration for the sensors connected to the RPI.
 
#name: sensor name and GPIO where it is connected.
 
#SensorType: 22 for a DHT22.
 
#Temperature low and high limits to trigger alert emails.
 
#Humidity limits similarly for humidity.
 
#Threshold: activation threshold for warnings.
 
#mailInfo: Email information.
 
#Senderaddress: Email sender address.
 
#Receiveraddress: Email receiver address.
 
#Username: email username.
 
#Password: email password.
 
#subjectMessage: Email subject.
 
#subjectWarning: Reason for the email.
 
#sqlBackupDump: backup dump configuration.
 
#BackupDumpEnabled y/n indicates if SQL backup is enabled.
 
#backupDay: day for the backup. 1-7 (Monday to Sunday) 0 daily.
 
#backupHour: hour of the dump - 0-24
 
#backupDumpPath: path where the dump is saved. By default, the Backups folder.
 
#weeklyAverages: Define if weekly averages are sent.
 
#weeklyAveragesSendingEnabled: y means enabled.
 
#weekDayForSendingAverages: day of the week for averages. 1-7 (Monday to Sunday).
 
#hourOfTheDayForSendingAverages: hour of the day 0-24.
 
#useFahrenheits: y enabled, n disabled.
 
#mailSendingTimeoutInFullHours: 0-x
 
#To reduce spam. At 0, logger sends mail for each warning. Higher values limit the emails to one per hour. Used to prevent inbox from being flooded with alerts.
 
#adafruitPath: path for Adafruit_Python_DHT, by default /home/pi/Adafruit_Python_DHT/ Script AdafruitDHT.py.

Once the configurations are done, press Ctrl+x and save with “Y”. Test the DHT22-TemperatureLogger:

python DHT22logger.py

If everything is correct, the program will write to the database. To verify, enter the database:

sudo mysql -u logger -p -h localhost

Enter the corresponding password. In the MySQL console:

USE temperatures;
 
SELECT * FROM temperaturedata;

Verify that the readings are written to the database. To exit:

quit

Automatic Sensor Reading

Add a cron task:

crontab -e

Select the /bin/nano option, and the crontab will open.

Add the task to the crontab (for example, every 15 minutes):

*/15 * * * * python /home/pi/DHT22-TemperatureLogger/DHT22logger.py

Exit and save with Ctrl+x, selecting “Y” when asked.

Configure Static IP for Raspbian

To configure a static IP in Raspbian, you need to edit the file `/etc/dhcpcd.conf`:

sudo nano /etc/dhcpcd.conf

If you look at the content, you will see commented lines (starting with '#') that provide an example of static IP configuration:

# Example static IP configuration:
#interface eth0
#static ip_address=192.168.0.10/24
#static ip6_address=fd51:42f8:caae:d92e::ff/64
#static routers=192.168.0.1
#static domain_name_servers=192.168.0.1 8.8.8.8 fd51:42f8:caae:d92e::1

ThinkSpeak

ThingSpeak Account Configuration

Register at https://thingspeak.com. If you don't have a previous account with MathWorks, ThingSpeak will redirect you, with the option to use the same email to register at: https://www.mathworks.com.

Create a new channel in your profile and add two field charts (Temperature and Humidity). Get the “Write API Key” for the created channel, which will be used to configure the ThingSpeak connection script and data submission.

Python Script for Sending Data to ThingSpeak ts.py

    import sys
    import urllib2
    import RPi.GPIO as GPIO
    import Adafruit_DHT
    # Write API Key ThingSpeak.com
    miWriteAPIKey = "XXXXXXXXXXXXXXXX"
    # GPIO number for DHT22 sensor connection to RaspberryPi
    raspiNumGPIO = "X"
    def getSensorData():
       RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, raspiNumGPIO)
       return (str(RH), str(T))
    def main():
       print 'Starting...'
       baseURL = 'https://api.thingspeak.com/update?api_key=%s' % miWriteAPIKey
       while True:
           try:
               RH, T = getSensorData()
               f = urllib2.urlopen(baseURL + "&field1=%s&field2=%s" % (RH, T))
               print f.read()
               f.close()
               sleep(5)
           except:
               print 'Done.'
               break
    if __name__ == '__main__':
    main()

Changes to the Basic Code

In `miWriteAPIKey`, input the Write API Key for the corresponding account at thingspeak.

miWriteAPIKey = "XXXXXXXXXXXXXXXX"

Change:

f = urllib2.urlopen(baseURL + "&field2=%s&field1=%s" % (RH, T))

The order has been switched so the temperature appears first, as it is the most important data.

Automate Data Sending

Add a cron task:

crontab -e

Select the /bin/nano option, and the crontab will open.

Add the task to the crontab (for example, every 15 minutes):

*/15 * * * * python /home/pi/Adafruit_Python_DHT/DHT22-TemperatureLogger/ts.py

Exit and save with Ctrl+x, selecting “Y” when asked.

ThingSpeak Channels

Sending Alert Emails with ThingSpeak

MATLAB Analysis to Send Emails

alert_body = 'This is the text that will be emailed';
alert_subject = 'This will be the subject of the email';
alert_api_key = 'YOUR_API_KEY_FROM_STEP_1';
alert_url= "https://api.thingspeak.com/alerts/send";
jsonmessage = sprintf(['{"subject": "%s", "body": "%s"}'], alert_subject,alert_body);
options = weboptions("HeaderFields", {'Thingspeak-Alerts-API-Key', alert_api_key; 'Content-Type','application/json'});
result = webwrite(alert_url, jsonmessage, options);

React App

React works with MATLAB® Analysis to take actions when the channel data meets certain conditions.

Define Reactions to Channel Data

Select Apps>React

  1. Click “New React”
  2. Select Options

The data that meets the conditions triggers a callback, either an HTTP request or an email.

History of Alerts

After running the app, go to the Dashboard>Activity. It will show the last sent emails or actions that have been triggered.

Definir Reaccions a les dades del canal

Seleccionar Apps>React

  1. Click a “New React”
  2. Seleccionar Opcions

condition no Data Check

Al apartat condition hi ha la posibilitat de activar no data check, condicio per reaccionar en cas de que no es rebin dades procedents del sensor.Es pot configurar que si es compleix aquesta condicio s´activi el modul react corresponent.

sql

CREATE TABLE temperaturedata (dateandtime DATETIME, sensor VARCHAR(32), temperature DOUBLE, humidity DOUBLE);
CREATE TABLE mailsendlog (mailsendtime DATETIME, triggedsensor VARCHAR(32), triggedlimit VARCHAR(10), lasttemperature VARCHAR(10));

referencies