Building a humidity sensor

HTU21 sensors can be aquired at

For this sensor we need the pigpiod functionality. So lets start by having that being enabled automatically on boot.

sudo nano /etc/init.d/pigpiod


Then add this code to the file, save and execute these commands.

cd /etc/init.d/
sudo chmod 755 pigpiod
sudo update-rc.d pigpiod defaults
sudo update-rc.d pigpiod enable


After a reboot pigpiod should be running.

Now lets attach the sensor using 4 wires.

  • VIN goes to pin 1
  • GND goes to pin 9
  • SCL goes to pin 5
  • SDA goes to pin 3

Next step is to read the sensor output using a script. Dalexgray provides an excellent library/driver on GitHUb. Place both and in your preferred folder. Run the script by executing:

sudo python


The output should be somewhat similar to:

sending reset...
The temperature is 9.917942 C.
The humidity is 63.360241 percent.


Congratulations. You are now reading humidity and temperature using your Raspberry Pi

Assuming you have set up your Pi as a LAMP server, you can use this script I have created for saving humidity and temperature every second to your database.

Following your success you might wanna make sure that data is automatically sent to your DB even if the Raspberry Pi has been rebooted

An easy way to do that is by creating a shell script that checks if the python script is running, and if not, just start it

sudo nano


Paste this to your new file and save it:

if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
echo "$service is running!!!"
sudo python /home/pi/
Next you want to make sure that the script can be executed
sudo chmod +x


crontab -e

Add this line and save:

* * * * * /home/pi/ > /dev/null 2>&1