0

I am setting up a raspberry pi zero to sense air quality, temperature and humidity. I am able to run the script to get the sensed data every 60 second. What should do if I need to save the data in a csv file at regular intervals?


import bme680
import time
import datetime
from datetime import datetime
from bme680 import BME680
from pms5003 import PMS5003, ReadTimeoutError

try:
    sensor = bme680.BME680(bme680.I2C_ADDR_PRIMARY)
except IOError:
    sensor = bme680.BME680(bme680.I2C_ADDR_SECONDARY)


pms5003 = PMS5003()
readings = pms5003.read()
sensor.set_humidity_oversample(bme680.OS_2X)
sensor.set_pressure_oversample(bme680.OS_4X)
sensor.set_temperature_oversample(bme680.OS_8X)
sensor.set_filter(bme680.FILTER_SIZE_3)

print('Data sensing')

try:
    while True:
        if sensor.get_sensor_data():
            output = datetime.now().strftime('%Y-%m-%d,%H:%M:%S,')+'{0:.2f} C,{1:.2f} hPa,{2:.3f} %RH'.format(
                sensor.data.temperature,
                sensor.data.pressure,
                sensor.data.humidity)

            if pms5003.read():
               print(output, readings)
            else:
                print(output)

        time.sleep(60)

except KeyboardInterrupt:
    pass

I expect the program to save the data in a csv file with headers like date, time, temperature , humidity etc.

Sachit
  • 5
  • 4

1 Answers1

1

To store that data into CSV or any other file format there are plenty of ways out there in python. If you want more controlled and more detailed csv then you can use Pandas or Numpy.

But if just you want a simple solution, then here it is.

def store_data(time,temperature,pressure,humidity):
    append = [time,temperature,pressure,humidity]
    with open('sensor_output.csv', 'a') as csvFile:
        writer = csv.writer(csvFile)
        writer.writerow(append)
    csvFile.close()

Just pass your values in this function and python will handle rest. File will be created automatically and will be appended every time.

   store_data(datetime.now().strftime('%Y-%m-%d,%H:%M:%S,'),sensor.data.temperature,sensor.data.pressure,sensor.data.humidity)

This is how you can call the function in your case.

#UPDATE: If you are familiar with pandas and DataFrame then this answer might help you:

Writing a pandas DataFrame to CSV file