• Skip to main content
  • Skip to primary sidebar

RNTLab.com

The Ultimate Shortcut to Learn Electronics and Programming with Open Source Hardware and Software

  • Courses
  • Forum
    • Forum
    • Ask Question
  • Shop
  • Account
  • Blog
  • Login

Average Micropython

Q&A Forum › Category: ESP32 › Average Micropython
0 Vote Up Vote Down
self.raymond asked 4 years ago

I want to take a sensor reading in a group of 5 and print the average of those numbers. Take a reading every 5 sec and print the average every 30 sec. Thanks for the help. Ray

18 Answers
0 Vote Up Vote Down
Sara Santos Staff answered 4 years ago

I think the best way to do that is to save each reading in an array with 5 values.
Then, get all the values from the array and calculate the average.
Do you have something lined up already?
Regards,
Sara

0 Vote Up Vote Down
self.raymond answered 4 years ago

Yes I did the Bme680 project and want to use it to do averages, 

Start your code here

from machine import Pin, I2C
from time import sleep
from bme680 import *
# ESP32 – Pin assignment
i2c = I2C(scl=Pin(22), sda=Pin(21))
# ESP8266 – Pin assignment
#i2c = I2C(scl=Pin(5), sda=Pin(4))
bme = BME680_I2C(i2c=i2c)
while True:
try:
#temp = str(round(bme.temperature, 2)) + ‘ C’
temp = (bme.temperature) * (9/5) + 32

tempR = str(round(temp, 2)) + ‘ F’

hum = str(round(bme.humidity, 2)) + ‘ %’

pres = str(round(bme.pressure, 2)) + ‘ hPa’

gas = str(round(bme.gas/1000, 2)) + ‘ KOhms’
print(‘Temperature:’, tempR)
print(‘Humidity:’, hum)
print(‘Pressure:’, pres)
print(‘Gas:’, gas)
print(‘——-‘)
except OSError as e:
print(‘Failed to read sensor.’)

sleep(5)

0 Vote Up Vote Down
Sara Santos Staff answered 4 years ago

Hi again.
I think you may be looking for something like this: https://maker.pro/arduino/tutorial/how-to-clean-up-noisy-sensor-data-with-a-moving-average-filter
It is written for Arduino IDE, but I think it can be easily “translated” to MicroPython.
Try it. Then, let me know if you need further help.
Regards,
Sara

0 Vote Up Vote Down
self.raymond answered 4 years ago

Sorry I miss the info on converting a Arduino file to Micro-python.  Very interested on how that is done. 
I was able to find a python code at https://hackaday.com/2019/09/06/sensor-filters-for-coders/
The one code that got my interest was moving averages. Might need a little help to make it work with the BME680. Thanks

Start your code here
# SMA:
n = 10
array_meanA = array('f', [])
for h in range(n):
    array_meanA.append(14.0)         # Initialise the array with 10 values of '14'.
for x in range(n):
    getSensorData()                  # Get some data.eg tempPiFloat
    array_meanA[n] = tempPiFloat     # tempPiFloat slots into end of array.
    for h in range(n):
        array_meanA[h] = array_meanA[(h+1)]     # Shift the values in the array to the left
    meanA = 0
    for h in range(n):
        meanA = array_meanA[h] + meanA          # Calculate the mean, no weights.
    meanA = meanA/n
0 Vote Up Vote Down
self.raymond answered 4 years ago

I try to put both of these 2 together.  The file hangs at
Ready to download this file,please wait!
……….
download ok
exec(open(‘testMean.py’).read(),globals())
any idea  Thanks

Start your code here

from machine import Pin, I2C
from time import sleep
from bme680 import *

# ESP32 – Pin assignment
i2c = I2C(scl=Pin(22), sda=Pin(21))
# ESP8266 – Pin assignment
# i2c = I2C(scl=Pin(5), sda=Pin(4))

bme = BME680_I2C(i2c=i2c)

while True:
try:
# temp = str(round(bme.temperature, 2)) + ‘ C’
temp = bme.temperature * (9 / 5) + 32
n = 8
array_meanTemp = array(‘f’, [])
for h in range(n):
array_meanTemp.append(10.0) # Initialise the array with 10 values of ’14’.
for x in range(n):
getSensorData(temp) # Get some data.eg tempPiFloat
array_meanTemp[n] = tempPiFloat # tempPiFloat slots into end of array.
for h in range(n):
array_meanTemp[h] = array_meanTemp[(h + 1)] # Shift the values in the array to the left
meanTemp = 0
for h in range(n):
meanTemp = array_meanTemp[h] + meanTemp # Calculate the mean, no weights.
meanTemp = meanTemp / n
tempR = str(round(meanTemp, 2)) + ‘ F’

print(‘Temperature:’, tempR)

except:
#print(‘Failed to read sensor.’)

sleep(3)

 

0 Vote Up Vote Down
Sara Santos Staff answered 4 years ago

Hi.
I’m sorry for taking so long to get back to you.
What you need is something like this:
https://gist.github.com/sarasantos/3f6e6852793640b2f61896624b343579
It calculates the average of the last 5 temperature readings. You need to wait a couple of minutes until it has 5 readings to get accurate results. It gets a temperature reading every 30 seconds.
Let me know if this is what you were looking for.
Regards,
Sara

0 Vote Up Vote Down
self.raymond answered 4 years ago

Thank you This code will it dump the readings when it starts another 5 readings.  Will this keep storing those numbers?  Thank you for clarifying with this short code.  So I am thinking to define each reading like humidity and pressure to read all the bmp680 sensor data.  Thank you again for the help

0 Vote Up Vote Down
Sara Santos Staff answered 4 years ago

This stores the last 5 readings on the temperatures array and the current average of the last 5 readings on the average variable.
You can use the same strategy for the other readings.
Regards,
Sara

0 Vote Up Vote Down
self.raymond answered 4 years ago
Have been working on this file into a function with no luck.  Seems the file works but 
does not read temp. Did I break it.


Start your code here

from machine import Pin, I2C
from time import sleep
from bme680 import *

# ESP32 – Pin assignment
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=10000)
bme = BME680_I2C(i2c=i2c)

temperatures = [0, 0, 0, 0, 0]
n = 0

def temp_sensor():
while True:
print(‘loop’)
n= 0
if n >= len(temperatures):
temperatures[n] = bme.temperature * (9 / 5) + 32
#temperatures[n] = (((round(bme.temperature * 9/5) + 32.0), 1)
average = sum(temperatures)/len(temperatures)
n += 1
print(round(average, 2))
#print(average)
#print(round(temperatures, 2))
#print(“{:.2f}”.format(temperatures));
print(temperatures)
sleep(10)

temp_sensor()

0 Vote Up Vote Down
Sara Santos Staff answered 4 years ago

Hi.
Indentation in MicroPython is very important. I don’t know if there’s something wrong with your code if it loses indentation when you paste it here.
Please, format your code correctly or use github, pastebin or any other service to share your code.
Did my code work for you?
Regards,
Sara

0 Vote Up Vote Down
self.raymond answered 4 years ago

= len(temperatures):
temperatures[n] = bme.temperature * (9 / 5) + 32

# temperatures[n] = (((round(bme.temperature * 9/5) + 32.0), 1)

average = sum(temperatures) / len(temperatures)
n += 1
print(round(average, 2))

# print(average)
# print(round(temperatures, 2))
# print(“{:.2f}”.format(temperatures));

print(temperatures)
sleep(10)

temp_sensor()>
I do not know why this code is not being formatted

on here

I hope this is better on the indentation. Your code work great. The problem I have been having is putting into a function call def temp_sensor(): I thought since I will be having 4 readings it would be best to def each sensors. I would make note when I ran your code with the 20 sec delay in it it work great. So I try to run it with 20 15 10 5 and 2 and found 10 sec delay all things work ok. anything below 10sec it is not stable. Thank you for all your help

Ray

0 Vote Up Vote Down
self.raymond answered 4 years ago

https://github.com/sprinkfitter/BMEHome.git
The test file is the one.  I hope this will work

0 Vote Up Vote Down
self.raymond answered 4 years ago

This is the file I work on.  bmetestdef.py

0 Vote Up Vote Down
Sara Santos Staff answered 4 years ago

Hi.
Your code doesn’t work because of line 17.
Your n variable is always zero.
I don’t think it is a good practice to have a while True loop inside a function.
There isn’t an easy way to build a function with that because you need to know how many times a function was called: https://stackoverflow.com/questions/21716940/is-there-a-way-to-track-the-number-of-times-a-function-is-called
For simplicity you can use something like this:https://gist.github.com/sarasantos/0bc38dddb3ae7d993862ed1d4a48d179
but notice that you’ll always have to increase and check the n size on the loop.
Regards,
Sara
 
 

0 Vote Up Vote Down
self.raymond answered 4 years ago

Thank You I get the following error
download ok
exec(open(‘Sarabmetest.py’).read(),globals())
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
File “<string>”, line 42, in <module>
File “<string>”, line 22, in get_BME680_average
NameError: name ‘humidity’ isn’t defined

0 Vote Up Vote Down
Sara Santos Staff answered 4 years ago

Can you double-check the indentation?
I’ve tested the code myself before sharing and it was working.
Regards,
Sara

0 Vote Up Vote Down
self.raymond answered 4 years ago

still get the same Error 
download ok
exec(open(‘Sarabmetest.py’).read(),globals())
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
File “<string>”, line 43, in <module>
File “<string>”, line 22, in get_BME680_average
NameError: name ‘humidity’ isn’t defined

0 Vote Up Vote Down
Sara Santos Staff answered 4 years ago

Hi.
I’m sorry. I’ve posted the wrong version of the code.
Can you try it again?
https://gist.github.com/sarasantos/0bc38dddb3ae7d993862ed1d4a48d179
Regards,
Sara

Primary Sidebar

Login to Ask or Answer Questions

This Forum is private and it’s only available for members enrolled in our Courses.

Login »

Latest Course Updates

  • [New Edition] Build ESP32-CAM Projects eBook – 2nd Edition April 16, 2025
  • [eBook Updated] Learn ESP32 with Arduino IDE eBook – Version 3.2 April 16, 2025

You must be logged in to view this content.

Contact Support - Refunds - Privacy - Terms - MakerAdvisor.com - Member Login

Copyright © 2013-2025 · RandomNerdTutorials.com · All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.