import Adafruit_DHT
import time
DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4
#while loop is there because sometime it does not get the temp.
while True:
humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
if humidity is not None and temperature is not None:
print("Temp={0:0.1f}C Humidity={1:0.1f}%".format(temperature, humidity))
else:
print("Sensor failure. Check wiring.");
time.sleep(1);
run:
python3 temp.py
For DHT22 sensor:
temp-dht22.py
import Adafruit_DHT
import time
DHT_SENSOR = Adafruit_DHT.DHT22
DHT_PIN = 4
humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
if humidity is not None and temperature is not None:
#print("Temp={0:0.1f}C Humidity={1:0.1f}%".format(temperature, humidity))
print("{0},{1}".format(temperature, humidity))
Note : This does not work because IO pins does not enough power to run fan.
fan.py
import RPi.GPIO as GPIO
from time import sleep
import sys
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW)
if sys.argv[1] == "on":
GPIO.output(8, GPIO.HIGH)
print("on")
else:
GPIO.output(8, GPIO.LOW)
print("off")
Dockerfile
FROM python:slim-buster
WORKDIR /fan
RUN apt update && \
apt install python-rpi.gpio python3-rpi.gpio -y
COPY fan.py .
Docker build
docker build -t fan .
Docker run command switch on
docker run -it --device /dev/gpiomem fan python2 fan.py on
Docker run command switch off
docker run -it --device /dev/gpiomem fan python2 fan.py off
fan.sh
#!/bin/bash
cpu=$(</sys/class/thermal/thermal_zone0/temp)
cpu_temp=$(echo "$cpu/1000" | /usr/bin/bc)
echo $cpu_temp
if(("cpu_temp" >= "65"))
then
echo "more 65 on fan"
docker run -it --device /dev/gpiomem fan python2 fan.py on
else
echo "less 65 off fan"
docker run -it --device /dev/gpiomem fan python2 fan.py off
fi