Saving Sensor Readings To CSV (Python / Raspberry Pi)

Saving Readings To CSV

So far I have looked at outputting the data from my sensors to Flask, Twitter and Azure. However, a simpler option could be to output the date to a CSV (Comma Seperated Value) file that could be used by various programs later on.

I’ve placed the Python code to capture data from the Pi sensors into a CSV on my GitHub at https://github.com/geektechdude/temperature_project/blob/master/write_readings_to_csv

I have commented the parts of the program that may need commenting such as the import of the csv module (to open, write or amend csv files) and that I’m using the “a” option to amend the csv rather than the “r” to read it or the “w” to write it. I did originally use the “w” option but that overwrites any data in the csv file which is not great if you are trying to keep a log.

In my csv file I’ve manually added a title row which says:

date, time, temperature, pressure, lux, cpu temperature

I’ve then created a function (write_to_csv) that inserts the readings in the same order. I’m using cron to run the Python program every 15 minutes and this captures the readings to a csv file.

# geektechstuff
# Sensor to CSV

# initial set up of imports

import time
import datetime

# gpiozero for CPU
from gpiozero import CPUTemperature

# imports the modules for the sensor
from bmp280 import BMP280
try:
from smbus2 import SMBus
except ImportError:
from smbus import SMBus

# lux sensor
import ltr559

# csv to be able to open file
import csv

# sets up the variables for the sensor
bus=SMBus(1)
bmp280 = BMP280(i2c_dev=bus)

# functions to use

def cpu_temperature():
cpu = CPUTemperature()
cpu_temp = cpu.temperature
cpu_temp = str(cpu_temp)
return(cpu_temp)

def get_temp():
temperature = bmp280.get_temperature()
temperature = round((temperature),2)
temperature = temperature -2
temperature = str(temperature)
return(temperature)

def get_pressure():
pressure = bmp280.get_pressure()
pressure = round(pressure)
pressure = str(pressure)
return(pressure)

def get_lux():
lux = ltr559.get_lux()
for x in range(1,5):
x_lux = lux
time.sleep(0.5)
lux_rounded = round(x_lux,2)
lux_str = str(lux_rounded)
return(lux_str)

def date_now():
today = datetime.datetime.now().strftime(“%Y-%m-%d”)
today = str(today)
return(today)

def time_now():
now = datetime.datetime.now().strftime(“%H:%M:%S”)
now = str(now)
return(now)

def write_to_csv():
# the a is for append, if w for write is used then it overwrites the file
with open(‘/home/pi/twitter_sensor/sensor_readings.csv’, mode=’a’) as sensor_readings:
sensor_write = csv.writer(sensor_readings, delimiter=’,’, quotechar='”‘, quoting=csv.QUOTE_MINIMAL)
write_to_log = sensor_write.writerow([date_now(),time_now(),get_temp(),get_pressure(),get_lux(),cpu_temperature()])
return(write_to_log)

write_to_csv()

Saving Readings To CSV
Saving Readings To CSV

One thought on “Saving Sensor Readings To CSV (Python / Raspberry Pi)

Comments are closed.