Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Measure humidity and temperature with a Raspberry Pi, save the result as a csv file and send a Telegram message
### Measure Temperature and Humidity very 30 secs and save it csv file
# code
### Create a Telegram Bot
# - create a bot by texting to BotFather `/newbot` and receive a token
# - go to ``
# - send a text to your bot
# - the JSON on `` will update and you get the `chat_id`
# send a message to chat: ``
# link: [Creating a Telegram bot for personal notifications](
### run on a remote Pi
# run forever in background: nohup python3 /home/pi/spielen/feuchtesensor/ -i 300 >> nohup.out 2>&1 &
# kill process:
# kill $(ps aux | grep python | grep | awk '{print $2}')
### code:
import Adafruit_DHT
import os
import time
import requests
import argparse
# define constants:
# which sensor? here: DHT11
# which GPIO Pin?
# path of csv file
FILE = "measurements.csv"
# telegram
TOKEN = "your_telegram_token"
CHAT_ID = "your_telegram_chat_id"
# initiate argument parser
parser = argparse.ArgumentParser(description="This script measures humidity and temperature and sends a telegram message, when humidity is > 60%.")
# add long an short argument
parser.add_argument("-i", "--intervall", help="interval in which measurement is performed", type=int)
# read arguments from the command line
args = parser.parse_args()
# open csv file
# and if there is none (st_size == 0), then create one
f = open(FILE, 'a+')
if os.stat(FILE).st_size == 0:
# measure humidity and temperature
# save results to csv file
# and if humidity is > 60%, send a message to telegram
while True:
humidity, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
if humidity is not None and temperature is not None:
f.write('{0},{1},{2:0.1f},{3:0.1f}\r\n'.format(time.strftime('%m/%d/%y'), time.strftime('%H:%M:%SS'), temperature, humidity))
print("Luftfeuchtigkeit = {0}, temperatur = {1}".format(humidity, temperature))
if humidity > 60:
# newline: %0D%0A
message_title = "*Bitte+lüften!*%0D%0ADie+Luftfeuchtigkeit+beträgt+{0}%".format(humidity)
send_text = '' + TOKEN + '/sendMessage?chat_id=' + CHAT_ID + '&parse_mode=Markdown&text=' + message_title
print("humidity < 60%: {0}%".format(humidity))
print("Failed to retrieve data from humidity sensor")
Copy link

dineshraj375 commented Apr 6, 2021

how to add on codes if its diplaying the same info on a lcd?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment