Python Forum
Averaging sensor results - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Averaging sensor results (/thread-34003.html)



Averaging sensor results - igorv1234 - Jun-17-2021

I have written the following code in python to monitor three sensor values per minute
My goal is to measure every second and take the average per minute and stores this in the csv file 'data.csv'
What is the best way to achieve this goal?

kind regards,

igor

#importeert alle bibliotheken
import csv
import time
import datetime as dt
import board
from board import SCL, SDA
import busio
from adafruit_seesaw.seesaw import Seesaw
import adafruit_tsl2591
import RPi.GPIO as GPIO
from time import sleep
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

#Sensoren
i2c = board.I2C()
i2c_bus = busio.I2C(SCL, SDA)
sensor = adafruit_tsl2591.TSL2591(i2c)
ss = Seesaw(i2c_bus, addr=0x36)

#Initialisatie nummers
date  = float
temp  = float
moist = float
lux   = float
i     = 1

#maakt een csv bestand straks aan met deze kolommen
fieldnames = ["date","temp","moist","lux"]

#opent het csv bestand
with open('/home/pi/Documents/Plant_monitor/data.csv', 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()

#zorgt ervoor dat er een maximaal hoeveelheid data gegenereerd kan worden (1dag)
while i < 1440*7:

    with open('/home/pi/Documents/Plant_monitor/data.csv', 'a') as csv_file:
        csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

        info = {
            "date": date,
            "temp": temp,
            "moist": moist,
            "lux": lux
                }
        
        #leest de sensoren uit en rond waarden af
        lux   = round(sensor.lux,1)
        moist = round(ss.moisture_read(),0)
        temp  = round(ss.get_temp(),1)
        date  = (dt.datetime.now().strftime('%H:%M'))
        
  

        #laat de led aangaan als de grond te droog is 
        if moist < 400:
            GPIO.output(18, GPIO.HIGH)
        else:
            GPIO.output(18, GPIO.LOW)

        
        #schrijft de waarden naar de juiste kolommen
        csv_writer.writerow(info)
        #print de waarden uit om te controleren of het script werkt
        print(date, temp, moist, lux)
        
        
    #verhoogt de waarde voor i 
    i=i+1
    #tussen elke meting zit 60s (1min)
    time.sleep(60)



RE: Averaging sensor results - topfox - Jun-17-2021

How about a loop inside your while loop to sum the sensor values received for each of 60 seconds, then divide all by 60 and write to file?