0
0
Raspberry Piprogramming~7 mins

InfluxDB for time-series data in Raspberry Pi

Choose your learning style9 modes available
Introduction

InfluxDB helps you store and analyze data that changes over time, like temperature or sensor readings. It makes it easy to track and understand trends.

You want to record temperature changes from a sensor every minute.
You need to monitor how much electricity your home uses throughout the day.
You want to track the speed of a motor over time to find problems.
You want to save and analyze data from weather stations on your Raspberry Pi.
Syntax
Raspberry Pi
from influxdb_client import InfluxDBClient, Point, WritePrecision

client = InfluxDBClient(url="http://localhost:8086", token="your-token", org="your-org")
write_api = client.write_api()

point = Point("measurement_name") \
    .tag("tag_key", "tag_value") \
    .field("field_key", field_value) \
    .time(time_value, WritePrecision.NS)

write_api.write(bucket="your-bucket", org="your-org", record=point)

You create a Point to represent one data entry with tags and fields.

Tags are like labels (text), fields are the actual data (numbers or text).

Examples
This example records a temperature value with a location tag and current time.
Raspberry Pi
from datetime import datetime

point = Point("temperature") \
    .tag("location", "living_room") \
    .field("value", 23.5) \
    .time(datetime.utcnow(), WritePrecision.NS)
This example records humidity data from the garden.
Raspberry Pi
from datetime import datetime

point = Point("humidity") \
    .tag("location", "garden") \
    .field("value", 60) \
    .time(datetime.utcnow(), WritePrecision.NS)
Sample Program

This program connects to InfluxDB on your Raspberry Pi, creates a temperature data point with a room tag, and writes it to the database. It then prints a confirmation message.

Raspberry Pi
from influxdb_client import InfluxDBClient, Point, WritePrecision
from datetime import datetime

# Connect to InfluxDB running on Raspberry Pi
client = InfluxDBClient(url="http://localhost:8086", token="my-token", org="my-org")
write_api = client.write_api()

# Create a data point for temperature
point = Point("temperature") \
    .tag("room", "kitchen") \
    .field("value", 22.7) \
    .time(datetime.utcnow(), WritePrecision.NS)

# Write the point to the bucket
write_api.write(bucket="home_data", org="my-org", record=point)

print("Data point written to InfluxDB")
OutputSuccess
Important Notes

Make sure InfluxDB is installed and running on your Raspberry Pi before running the code.

Replace your-token, your-org, and your-bucket with your actual InfluxDB details.

Use UTC time to keep your data consistent across devices and time zones.

Summary

InfluxDB stores time-series data like sensor readings with timestamps.

You create data points with tags (labels) and fields (values) to save data.

Use Python client on Raspberry Pi to send data easily to InfluxDB.