如何用Python编写自动化脚本实现PI传感器数据采集、存储与分析?
Absolutely! Both of your goals—automating your sensor script to run on a schedule and saving data for later analysis—are totally doable with Python on a Raspberry Pi. Let’s walk through each part with practical, actionable examples.
1. Automating Script Execution (Scheduled Runs)
You’ve got two solid options here, depending on how robust you need the setup to be:
Option 1: Simple Python Loop with time.sleep()
Great for quick testing or short-term use. Just wrap your existing sensor logic in a loop that pauses for your desired interval between runs.
import time # Assume your existing sensor reading function is here def get_sensor_data(): # Replace with your actual sensor code to fetch temp, pressure, altitude temperature = 22.5 pressure = 1013.25 altitude = 120.0 return temperature, pressure, altitude # Set your desired interval in seconds (e.g., 300 = 5 minutes) INTERVAL = 300 while True: temp, press, alt = get_sensor_data() print(f"Temp: {temp}°C, Pressure: {press} hPa, Altitude: {alt}m") # We'll add data saving logic here next time.sleep(INTERVAL)
Pro tip: If you want this to run in the background even when you close your terminal, launch it with nohup python3 code.py &—the & sends it to the background, and nohup keeps it running after you log out.
Option 2: System Cron Job (More Reliable for Long-Term Use)
Cron is Linux’s built-in scheduler—it’s stable, will restart your script if your Pi reboots, and doesn’t require keeping a Python loop running. Here’s how to set it up:
- Open your user’s crontab editor:
crontab -e - Add a line at the end to schedule your script. For example, to run every 5 minutes:
Let’s break this down:*/5 * * * * /usr/bin/python3 /home/pi/code.py >> /home/pi/sensor_logs.log 2>&1*/5 * * * *: Runs every 5 minutes (adjust the first number to change intervals—e.g.,0 */1 * * *for hourly)/usr/bin/python3: Absolute path to your Python interpreter (find yours withwhich python3)/home/pi/code.py: Absolute path to your script>> /home/pi/sensor_logs.log 2>&1: Saves output/errors to a log file (optional but super helpful for debugging)
- Save and exit—cron will automatically apply the new schedule.
2. Saving Data for Analysis
CSV (Comma-Separated Values) is the ideal format here—it’s human-readable, works with Excel/Google Sheets, and integrates seamlessly with Python tools like pandas for advanced analysis. Here’s how to add this to your script:
Option 1: Using Python’s Built-in csv Module (No Extra Installs)
This is lightweight and doesn’t require any external packages:
import time import csv from datetime import datetime def get_sensor_data(): # Replace with your actual sensor code temperature = 22.5 pressure = 1013.25 altitude = 120.0 return temperature, pressure, altitude INTERVAL = 300 DATA_FILE = "/home/pi/sensor_data.csv" def save_data(temp, press, alt): # Add timestamp for context (critical for analysis) timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Check if file exists to write header only once file_exists = False try: with open(DATA_FILE, 'r') as f: file_exists = True except FileNotFoundError: pass # Write data to CSV with open(DATA_FILE, 'a', newline='') as f: writer = csv.writer(f) if not file_exists: # Write header row writer.writerow(["Timestamp", "Temperature (°C)", "Pressure (hPa)", "Altitude (m)"]) # Write the latest sensor reading writer.writerow([timestamp, temp, press, alt]) # Main loop while True: temp, press, alt = get_sensor_data() save_data(temp, press, alt) print(f"Saved data: {temp}°C, {press}hPa, {alt}m at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") time.sleep(INTERVAL)
Option 2: Using pandas (For Easier Advanced Analysis)
If you plan to do things like plot trends, filter data by date, or calculate averages later, pandas simplifies this work. First install it:
pip install pandas
Then modify your save function:
import pandas as pd from datetime import datetime def save_data(temp, press, alt): timestamp = datetime.now() # Create a small DataFrame with the new reading new_data = pd.DataFrame({ "Timestamp": [timestamp], "Temperature (°C)": [temp], "Pressure (hPa)": [press], "Altitude (m)": [alt] }) # Append to CSV (automatically creates file if it doesn't exist) new_data.to_csv(DATA_FILE, mode='a', header=not pd.io.common.file_exists(DATA_FILE), index=False)
Quick Final Checks
- Ensure your script has execute permissions:
chmod +x /home/pi/code.py - If using cron, double-check all absolute paths—cron uses a minimal environment, so relative paths might break your script.
- For sensor access (e.g., I2C sensors), make sure your Pi user is in the correct group:
sudo usermod -aG i2c pi
内容的提问来源于stack exchange,提问作者Pras4

