Hardware Reference
In-Depth Information
Scripting the Sensors
Now that you can read the sensors you may want a way to log the values or just to monitor them from a terminal
screen. As you can see, the commands I gave you to read the two sensors are a little unfriendly to keep typing all the
time. To solve this issue I will give you a little script that can read the DHT11 or the DS1820B. This script will poll the
sensor at your given interval in seconds. The script has two modes of operation.
•
You can run the script in monitor mode; this will just print the value of the sensor to the
terminal.
•
The other mode that the script supports is writing the value of the sensor to a log file.
In Listing 3-1 below you can see the code. The script has a few small assumptions. It assumes that the sensors are
connected to the GPIO pins you used in this chapter and that the
Adafruit_DHT
binary file is in the same directory as
the script itself.
Listing 3-1.
A Script to Read/Log the Sensors
#!/bin/bash
# Description : A simple bash script to monitor or log the temp sensors
# Author : Brendan Horan
SLEEP=$2
LOG=$3
function ds1820_mon {
echo Polling DS1820 every $SLEEP seconds.
for (( ; ; ))
do
echo Temperature is :
cat /sys/bus/w1/devices/10-0008027e34ca/w1_slave | grep t= | cut -c 30-31
sleep $SLEEP
done
}
function dht11_mon {
echo Polling DHT11 every $SLEEP seconds.
for (( ; ; ))
do
echo Temperature and humidity is :
./Adafruit_DHT 11 17 | grep Temp | tr "," "\n"
sleep $SLEEP
done
}
function ds1820_log {
echo Logging DS1820 to file every $SLEEP seconds. >> $LOG
for (( ; ; ))
do
echo Temperature is : >> $LOG
cat /sys/bus/w1/devices/10-0008027e34ca/w1_slave | grep t= | cut -c 30-31 >> $LOG
sleep $SLEEP
done
}
function dht11_log {
echo Logging DHT11 to file every $SLEEP seconds. >> $LOG
for (( ; ; ))