Raspberry PI temperature to InfluxDB

We’ll need to enable a virtual environment. Make sure you have venv installed:

sudo apt install python3.11-venv

Navigate to project directory and creante a virtual enviromnent:

source .venv/bin/activate

Install libraries for influxdb and DS18B20 sensor:

pip install influxdb-client w1thermsensor

In my case I want a python script that runs every X minutes and sends the reading to influxdb.
Below is an example:

from w1thermsensor import W1ThermSensor
from w1thermsensor.errors import NoSensorFoundError
from influxdb_client import InfluxDBClient, Point, WritePrecision
from influxdb_client.client.write_api import WriteOptions
import time

INFLUXDB_URL = "replaceme"
INFLUXDB_TOKEN = "replaceme"
INFLUXDB_ORG = "Home"
INFLUXDB_BUCKET = "weather"

client = InfluxDBClient(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG)
write_api = client.write_api(write_options=WriteOptions(batch_size=1))

# Initialize the DS18B20 sensor
try:
    sensor = W1ThermSensor()
except NoSensorFoundError as e:
    print("Sensor not connected")
    exit(1)

# Read temperature from the sensor
temperature = sensor.get_temperature()

# Prepare the data point
point = Point("temperature") \
    .tag("location", "exterior-1") \
    .field("temperature", temperature) \
    .time(time.time_ns(), WritePrecision.NS)

write_api.write(INFLUXDB_BUCKET, INFLUXDB_ORG, point)
print(f"Temperature data sent to InfluxDB: {temperature:.2f}°C")

client.close()

Next let’s configure this script to run every 15 mins using crontab:

crontab -e

And add this:

*/15 * * * * echo "$(date) - Getting temperature" >> /home/marian/projects/temperature/script.log && /home/marian/projects/temperature/.venv/bin/python /home/marian/projects/temperature/influx-temp.py >> /home/marian/projects/temperature/script.log 2>&1

By using python from venv you don’t need to activate it first.