[PYTHON] [Raspberry Pi] Add a thermometer and a hygrometer

Last time tried the energy-saving design of the liquid crystal display. This time we will add a thermometer and a hygrometer to monitor the temperature and humidity of the room.

The thermometer has been built in before. [Python] Obtain the room temperature from the temperature sensor with Arduino and display it on the screen (Part 1) [Python] Obtain the room temperature from the temperature sensor with Arduino and display it on the screen (Part 2)

However, an independent hygrometer was difficult. There were few materials and it was a little difficult for me, so This time I will try to lower the difficulty level a little.

There was a low-difficulty and popular temperature / humidity sensor, so I will try using it. Since the thermometer is a set, the previous thermometer will be stored and newly designed.

material

--Temperature / Humidity Sensor Module DHT11 --One 10kΩ resistor

This is the only material. Add it to the Arduino circuit you used last time. Complex designs are already built into the module, so it's easy to work with.

Circuit creation

The page that I referred to this time Temperature and Humidity Measurement Using DHT11 --Arduino --Introduction to IoT from the Basics https://iot.keicode.com/arduino/temperature-dht11.php

Screenshot_20200208[1].png

DHT11 (light blue parts) in the above figure is upside down. Please note that it will be [GND] [NC] [DATA] [VDD] from the left.

The output is the same digital 8pin as the reference page. The orange and yellow wires are 5V and GND is black. The circuit diagram was simple, but the real circuit was a little crowded.

IMG_20200208_1729.jpg

After this, I plan to add a barometer, but what will happen?

Arduino program code

#include <DHT.h>

// Initializing DHT11 sensor
const int PIN_DHT = 8;
DHT dht(PIN_DHT, DHT11);

void setup() {

  //start serial connection
  Serial.begin(9600);

  //configure pin A3 as an input and enable the internal resistor
  pinMode(A3, INPUT);

  // start DHT11 sensor
  dht.begin();

}

void loop() {

  // Whether to display in Fahrenheit
  bool isFahrenheit = false;

  // Get humidity and temperature
  float percentHumidity = dht.readHumidity();
  float temperature = dht.readTemperature(isFahrenheit);

  // Do nothing if not available
  if (isnan(percentHumidity) || isnan(temperature)) {
    return;
  }

  // Get heat index
  float heatIndex = dht.computeHeatIndex(
    temperature,
    percentHumidity,
    isFahrenheit
  );

  //read the photocell value into a variable
  int photocell = analogRead(A3);

  //print out the sensor value in csv format
  String s = "";
  s += String(temperature, 1) + ",";
  s += String(percentHumidity, 1) + ",";
  s += String(heatIndex, 1) + ",";
  s += String(photocell);
  Serial.println(s);

  //delay 2000 ms
  delay(2000);

}

Most of the added code is for working with the DHT11 library. I want to get the temperature in degrees Celsius, so I set bool isFahrenheit = false;.

Also, since the processing was complicated, I made a loop at 2 second intervals. Just in case.

It reads from a digital 8pin and outputs it in CSV format including the value of the previous illuminance sensor.

Addition of DHT library

DHT libraries can be added from the Arduino IDE's Library Manager. From the menu, select "Tools-> Manage Library".

DHT sensor library by Adafruit In the screenshot, I installed Ver.1.3.8. Screenshot_20200208[2].png

Adafruit Unified Sensor by Adafruit It is a common library. At this point, Ver.1.1.2 is installed. Screenshot_20200208[3].png

Create database, users and tables

From this time, the sensor information will be written to the database.

Since multiple serial connections cannot be made at the same time, (There may be some way, but as a cheaper way) The program that writes to the database keeps running, and other programs share information by referencing the database.

$ mysql -u root -praspberry 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.1.38-MariaDB-0+deb9u1 Raspbian 9.0

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> CREATE DATABASE sensor;
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> CREATE USER 'sensorpi'@'localhost' IDENTIFIED BY 'raspberry';
Query OK, 0 rows affected (0.01 sec)

MariaDB [(none)]> GRANT ALL PRIVILEGES ON sensor.* TO 'sensorpi'@'localhost';
Query OK, 0 rows affected (0.01 sec)

MariaDB [(none)]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

MariaDB [(none)]> USE mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
MariaDB [mysql]> SELECT user, password, plugin FROM user;
+------------+-------------------------------------------+--------+
| user       | password                                  | plugin |
+------------+-------------------------------------------+--------+
| root       | ***************************************** |        |
| phpmyadmin | ***************************************** |        |
| fxpi       | ***************************************** |        |
| sensorpi   | ***************************************** |        |
+------------+-------------------------------------------+--------+
4 rows in set (0.01 sec)

MariaDB [mysql]> QUIT;
Bye
pi@raspberrypi:~ $ mysql -u sensorpi -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 34
Server version: 10.1.38-MariaDB-0+deb9u1 Raspbian 9.0

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> USE sensor;
Database changed
MariaDB [sensor]> CREATE TABLE tbl_serval (time DATETIME,
    -> max_temperature FLOAT, avg_temperature FLOAT, min_temperature FLOAT,
    -> max_humidity FLOAT, avg_humidity FLOAT, min_humidity FLOAT,
    -> max_heatIndex FLOAT, avg_heatIndex FLOAT, min_heatIndex FLOAT,
    -> max_pressure INT, avg_pressure INT, min_pressure INT,
    -> max_photocell INT, avg_photocell INT, min_photocell INT);
Query OK, 0 rows affected (0.05 sec)
item Set value
Database sensor
user sensorpi
table tbl_serval

The structure of tbl_serval looks like this. Nulls are allowed for all columns, but we will review them soon.

serval is an abbreviation for SERial VALue.

Column name Mold NULL Description
time DATETIME Tolerance Recording time
max_temperature FLOAT Tolerance Temperature (maximum)
avg_temperature FLOAT Tolerance Temperature (average)
min_temperature FLOAT Tolerance Temperature (minimum)
max_humidity FLOAT Tolerance Humidity (maximum)
avg_humidity FLOAT Tolerance Humidity (average)
min_humidity FLOAT Tolerance Humidity (minimum)
max_heatIndex FLOAT Tolerance Feeling temperature (maximum)
avg_heatIndex FLOAT Tolerance Feeling temperature (average)
min_heatIndex FLOAT Tolerance Feeling temperature (minimum)
max_pressure INT Tolerance Atmospheric pressure (maximum)
avg_pressure INT Tolerance Atmospheric pressure (average)
min_pressure INT Tolerance Atmospheric pressure (minimum)
max_photocell INT Tolerance Illuminance (maximum)
avg_photocell INT Tolerance Illuminance (average)
min_photocell INT Tolerance Illuminance (minimum)

Python program code

I've fixed it here and there, so just an overview. For changes, if you are interested, GitHub (mySensor) & GitHub (Desktop Clock) Take a look at DesktopClock / commit / 437884c6f55cee7693addb0726ccf4ae81c04269).

--Receives sensor information (CSV format) every 2 seconds and divides --Calculate the maximum, average, and minimum values in 1 minute --Write to database --Changed the table clock program (DesktopClock) side from serial connection to DB connection --Get the latest value from the DB every minute and display it on the screen

Screenshot_20200208[4].png It will be completed soon.

Small story

I had a mechanism to turn off the backlight when the illuminance was 50 or less. After this change, even if the room was darkened, it did not disappear immediately, and after a while it turned off, and the reaction slowed down. Restarting the Python program will fix it, but after a short while it will recur.

As a result of investigating Iloilo, it seems that the cause was the receive buffer.

main.py


#Flush the receive buffer
self.ser.flushInput()

If you don't do this, you will not be able to synchronize with the serial connection. It seems that the range of delay increases with the passage of time.

I don't think it's a good idea, but it's probably because the delay has disappeared.

Recommended Posts

[Raspberry Pi] Add a thermometer and a hygrometer
Make a thermometer with Raspberry Pi and make it viewable with a browser Part 4
Make a thermometer with Raspberry Pi and make it visible on the browser Part 3
Create a color sensor using a Raspberry Pi and a camera
Create a web surveillance camera with Raspberry Pi and OpenCV
Create a partition and then install the Raspberry Pi OS
MQTT on Raspberry Pi and Mac
Using a webcam with Raspberry Pi
Make a simple CO2 incubator using Raspberry PI and CO2 sensor (MH-Z14A)
Christmas classic (?) Lighting a Christmas tree with Raspberry Pi and Philips Hue
Make a Kanji display compass with Raspberry Pi and Sense Hat
Pet monitoring with Rekognition and Raspberry pi
Build a Tensorflow environment with Raspberry Pi [2020]
Launch docker.plone and add a custom template
Make a wash-drying timer with a Raspberry Pi
Operate an oscilloscope with a Raspberry Pi
Create a car meter with raspberry pi
Make a wireless LAN Ethernet converter and simple router with Raspberry Pi
Raspberry Pi 3 x Julius (reading file and grammar file)
Build a Django environment on Raspberry Pi (MySQL)
Try using a QR code on a Raspberry Pi
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a Web server --2 PHP introduction
Cross-compiling Raspberry Pi and building a remote debugging development environment with VS Code
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a Web server ―― 1. Apache introduction
Raspberry Pi backup
MQTT RC car with Arduino and Raspberry Pi
Creating a temperature control system with Raspberry Pi and ESP32 (3) Recipient Python file
Easy connection between Raspberry Pi and AWS IoT
[For beginners] I made a motion sensor with Raspberry Pi and notified LINE!
Create a visitor notification system using Raspberry Pi
Get temperature and humidity with DHT11 and Raspberry Pi
Raspberry Pi and AWS IoT connection program example
Build a distributed environment with Raspberry PI series (Part 3: Install and configure dnsmasq)
Build a Python development environment on Raspberry Pi
Draw a weakness graph in Python and save it in various formats (Raspberry Pi, macOS)
Control music playback on a smartphone connected to Raspberry Pi 3 and bluetooth with AVRCP
Build a server on Linux and local network with Raspberry Pi NextCloud and desktop sharing
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a web server --3. Use MySQL
Record temperature and humidity with systemd on Raspberry Pi
Machine learning with Raspberry Pi 4 and Coral USB Accelerator
Detect mask wearing status with OpenCV and Raspberry Pi
Measure temperature and humidity with Raspberry Pi3 and visualize with Ambient
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Installation of Docker on Raspberry Pi and L Chika
Install pyenv on Raspberry Pi and version control Python
Getting Started with Yocto Project with Raspberry Pi 4 and WSL2
Troubleshoot with installing OpenCV on Raspberry Pi and capturing
A memorandum when making a surveillance camera with Raspberry Pi
Use raspberry Pi and Julius (speech recognition). ③ Dictionary creation
What is Raspberry Pi?
GPGPU with Raspberry Pi
Easily make a TweetBot that notifies you of temperature and humidity with Raspberry Pi + DHT11.
pigpio on Raspberry pi
Raspberry Pi video camera
Raspberry Pi Bad Knowledge
Let's do Raspberry Pi?
A story about trying to use cron on a Raspberry Pi and getting stuck in space
DigitalSignage with Raspberry Pi
Raspberry Pi 4 setup memo
Cython on Raspberry Pi
Raspberry Pi system monitoring