In this step-by-step guide on CSV Data Logger on Raspberry Pi Pico, we captures the temperature readings from an onboard sensor, logs them to a CSV file along with timestamps, and reads back the logged data for analysis or monitoring.
This Sensor Data Logger project is perfect for beginners and enthusiasts alike, this guide will empower you to unlock the full potential of Raspberry Pi Pico in data logging and beyond. Join us to enhance your projects with precise, easy-to-manage sensor data logging capabilities!
Step 1. Setting Up Your Raspberry Pi PicoTo start, connect your Raspberry Pi Pico to your computer using the Micro-USB cable. If you haven’t already, you’ll need to install MicroPython onto your Pico. This can be done through the Thonny IDE, which offers an easy interface to install MicroPython directly.
You can go through: How To Get Started with Raspberry Pi Pico in 2024
Step 2. Setting Up the Temperature SensorThe Raspberry Pi Pico doesn’t come with a dedicated temperature sensor but has an ADC (Analog to Digital Converter) that can be used to approximate the CPU temperature.
Define the function for read the temperature.
import machine
import time
import os
# Function to read temperature sensor
def read_temperature():
adc = machine.ADC(4) # Use ADC pin GP4
conversion_factor = 3.3 / (65535) # ADC conversion factor
sensor_value = adc.read_u16() * conversion_factor
temperature = 27 - (sensor_value - 0.706) / 0.001721 # Convert sensor value to temperature (formula may vary)
return temperature
Step 3. Define the function for Create CSV File and Write DataCreate 2 functions:* log_temperature() - To write CSV file and data
* format_timestamp(timestamp) - To format the system datetime into specified format.
# Function to log temperature data to CSV file
def log_temperature():
file_name = "temperature_log.csv"
timestamp = time.localtime()
temperature = read_temperature()
print(temperature)
timestamp_str = format_timestamp(timestamp)
# Check if CSV file exists, if not create it with header
if not file_name in os.listdir():
with open(file_name, 'w') as file:
file.write('Timestamp,Temperature (°C)\n')
# Append temperature data to CSV file
with open(file_name, 'a') as file:
file.write('{},{:.2f}\n'.format(timestamp_str, temperature))
def format_timestamp(timestamp):
year, month, day, hour, minute, second, *_ = timestamp
timestamp_str = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(year, month, day, hour, minute, second)
return timestamp_str
Check this below data, how it's being logged!
For analyzing or simply checking the logged data, the read_temperature_log
function reads the CSV file, skipping the header, and parses each line to collect timestamps and temperature readings.
# Function to read temperature data from CSV file
def read_temperature_log():
file_name = "temperature_log.csv"
temperature_data = []
# Check if CSV file exists
if file_name in os.listdir():
with open(file_name, 'r') as file:
# Skip header line
next(file)
# Read each line and parse data
for line in file:
parts = line.strip().split(',')
if len(parts) >= 2:
timestamp = parts[0].strip('(') # Remove any extra characters from the timestamp
temperature = float(parts[1])
temperature_data.append((timestamp, temperature))
else:
print("Invalid line:", line)
return temperature_data
counter = 0
# Example usage: Log temperature every 5 seconds
while True:
counter += 1
if counter <=5:
log_temperature()
else:
print(read_temperature_log())
counter = 0
time.sleep(2)
That's all, check out https://rajivcodelab.com/csv-data-logger-how-to-read-and-write-csv-files/ for detailed guide.
If I have provided a real value for you, consider buying me a coffee☕
Source code: https://gist.github.com/RajivCodeLab
Comments