nerdegutta.no
RPi - DHT22 and mySQL
26.11.23
Programming
This program read a DHT22 sensor. Then it get the hostname and the external IP address, and lastly adds the info to an external database.
# IMPORTS
import Adafruit_DHT
import time
import socket
import re
from datetime import datetime
from urllib.request import urlopen
import requests
# DECLARATIONS
now = datetime.now()
sensor_type = 22
sensor_pin = 4
timestamp = now.strftime("%Y-%m-%d-%H:%M:%S")
# FUNCTIONS
# This function reads the humidity and temperature. The data is stored in global variables
def read_temp_hum():
global humidity
global temperature
# Read the sensor
humidity, temperature = Adafruit_DHT.read_retry(sensor_type, sensor_pin)
time.sleep(2)
while True:
if humidity is not None and temperature is not None:
print ("Data from sensor are OK. Humidity= {0:0.1f}% Temperature= {1:0.1f} *C".format(humidity, temperature))
break
else:
print ("Error getting data from sensor.")
break
# Function that gets the systems host name.
def get_hostname():
global local_hostname
local_hostname = socket.gethostname()
print ("Hostname: "+local_hostname)
# Function that get the external IP-adress
def get_external_ip_address():
global external_ip
url = "http://checkip.dyndns.org" # This site return one line of text.
my_request = urlopen(url).read() # Read the URL
res = re.findall(b'd{1,3}', my_request) # Search and findall integers in my_request
my_ip_list = list(map(int, res)) # Clean up the list
my_ip = str(my_ip_list)[1:-1] # Remove the square brackets
temp_ip = my_ip.replace(",", ".") # Replace comma with periods
external_ip = temp_ip.replace(" ", "") # Replace with none-space
print ("External IP: " +external_ip) # Print the External IP address as xxx.xxx.xxx.xxx
# Function to gather all the global variables and sending them to the server
def send_data():
output = "http://apk.nerdegutta.org:90/temperature/add_temp.php?temp="+str(temperature) \
+"&humi="+str(humidity)+"&time="+str(timestamp)+"&sensor="+str(local_hostname) \
+"&ip="+str(external_ip)
print (output)
html = urlopen(output).read()
# Main function of the program
def main():
read_temp_hum()
get_hostname()
get_external_ip_address()
send_data()
if __name__ == "__main__":
main()