0
0
Raspberry Piprogramming~5 mins

Why data logging matters for IoT in Raspberry Pi

Choose your learning style9 modes available
Introduction

Data logging helps save information from sensors so you can check it later. It makes your IoT devices smarter by keeping track of what happens over time.

You want to monitor temperature changes in your home over days.
You need to track how much water your plants get each day.
You want to record motion sensor data to see when someone enters a room.
You want to analyze energy usage patterns from your smart devices.
You want to keep a history of sensor readings to find problems early.
Syntax
Raspberry Pi
# Example of saving sensor data to a file
with open('data_log.txt', 'a') as file:
    file.write(f"{timestamp}, {sensor_value}\n")
Use 'a' mode to add new data without erasing old data.
Each line usually has a timestamp and the sensor reading.
Examples
This saves the current time and a sensor value to a file.
Raspberry Pi
import time
sensor_value = 25.3
with open('data_log.txt', 'a') as file:
    file.write(f"{time.time()}, {sensor_value}\n")
This saves a readable date and time with the sensor value.
Raspberry Pi
from datetime import datetime
sensor_value = 60
with open('data_log.txt', 'a') as file:
    file.write(f"{datetime.now()}, {sensor_value}\n")
Sample Program

This program saves the current date and sensor value to a file and prints a confirmation.

Raspberry Pi
import time
from datetime import datetime

sensor_value = 22.5

with open('data_log.txt', 'a') as file:
    timestamp = datetime.now()
    file.write(f"{timestamp}, {sensor_value}\n")

print('Data logged:', timestamp, sensor_value)
OutputSuccess
Important Notes

Always include a timestamp to know when data was recorded.

Use simple text files or CSV for easy reading and analysis later.

Make sure to handle file errors in real projects to avoid losing data.

Summary

Data logging saves sensor info so you can review it anytime.

It helps find patterns and problems in IoT devices.

Use timestamps and append mode to keep data organized.