Giter Site home page Giter Site logo

pimoroni / enviroplus-python Goto Github PK

View Code? Open in Web Editor NEW
377.0 29.0 173.0 552 KB

Python library for the Enviro+ environmental monitoring board

Home Page: https://shop.pimoroni.com/products/enviro-plus

License: MIT License

Makefile 5.73% Shell 48.12% Python 46.15%
python hardware-libraries raspberry-pi pypi-package

enviroplus-python's Introduction

Enviro+

Designed for environmental monitoring, Enviro+ lets you measure air quality (pollutant gases and particulates), temperature, pressure, humidity, light, and noise level. Learn more - https://shop.pimoroni.com/products/enviro-plus

Build Status Coverage Status PyPi Package Python Versions

Installing

Note The code in this repository supports both the Enviro+ and Enviro Mini boards. The Enviro Mini board does not have the Gas sensor or the breakout for the PM sensor.

Enviro Plus pHAT Enviro Mini pHAT

⚠️ This library now supports Python 3 only, Python 2 is EOL - https://www.python.org/doc/sunset-python-2/

Install and configure dependencies from GitHub:

  • git clone https://github.com/pimoroni/enviroplus-python
  • cd enviroplus-python
  • ./install.sh

Note Libraries will be installed in the "pimoroni" virtual environment, you will need to activate it to run examples:

source ~/.virtualenvs/pimoroni/bin/activate

Note Raspbian/Raspberry Pi OS Lite users may first need to install git: sudo apt install git

Or... Install from PyPi and configure manually:

  • python3 -m venv --system-site-packages $HOME/.virtualenvs/pimoroni
  • Run python3 -m pip install enviroplus

And install additional dependencies:

sudo apt install python3-numpy python3-smbus python3-pil python3-setuptools

Note this will not perform any of the required configuration changes on your Pi, you may additionally need to:

  • Enable i2c: raspi-config nonint do_i2c 0
  • Enable SPI: raspi-config nonint do_spi 0

And if you're using a PMS5003 sensor you will need to:

Bookworm

  • Enable serial: raspi-config nonint do_serial_hw 0
  • Disable serial terminal: raspi-config nonint do_serial_cons 1
  • Add dtoverlay=pi3-miniuart-bt to your /boot/config.txt

Bullseye

  • Enable serial: raspi-config nonint set_config_var enable_uart 1 /boot/config.txt
  • Disable serial terminal: sudo raspi-config nonint do_serial 1
  • Add dtoverlay=pi3-miniuart-bt to your /boot/config.txt

Alternate Software & User Projects

Help & Support

enviroplus-python's People

Contributors

andrewgleave avatar andypiper avatar cameronbunce avatar cipy avatar dedsyn4ps3 avatar gadgetoid avatar helgibbons avatar hotplot avatar idotj avatar jpwsutton avatar jspauley avatar makeupsomething avatar mendhak avatar michaeldufault avatar petermcd avatar rbricheno avatar ricki-z avatar robmarkcole avatar roscoe81 avatar rubiojr avatar sandyjmacdonald avatar spincrisis avatar svetlemodry avatar tanyafish avatar tijmenvandenbrink avatar topshed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

enviroplus-python's Issues

Understanding the MICS output

Hey there, I really appreciate the work that's gone into the Enviro+ and the library, it's a nifty piece of kit!

I'm having a bit of trouble at the moment translating the readings from the MICS sensor into something meaningful beyond increasing or decreasing air quality relative to the environment it started measuring in.

Are there are any reference materials for translating the Ohms output by each of the sensors to some bands for measuring air quality? For example, if the Oxidising output was 4570 Ohms, what does that mean in itself? Is that normal levels? Dangerous levels? Or does it not intrinsically mean anything?

If the latter, am I right in thinking that to measure the air quality of a particular area, I first need to start the sensor in a "clean" room to set the baseline?

Any guidance is much appreciated!

Put display to sleep (when using Luftdaten)

Hi

I am really happy using my Enviro + and PMS5003 with Luftdaten but I was wondering if there is a way to put the display to sleep after a few minutes. The information being displayed (ID and Wifi status) is useful for the initial configuration but not after that.

I would love to learn more about this and how to edit the Luftdaten code to make this happen.

Thank you!

First temperature reading always incorrect

It appears that the first value in each example is always incorrect. Why is that?

root@zero:/home/pi/enviroplus-python/examples# ./temperature.py
21.6270364913
30.9992406745
30.9919257087
30.9839746596
30.9776138208
30.9737973178
30.9702988568
30.9661643122
root@zero:/home/pi/enviroplus-python/examples# ./gas.py
gas.py - Print readings from the MICS6814 Gas sensor.

Oxidising: 72333.33 Ohms
Reducing: 21289.84 Ohms
NH3: 10811.28 Ohms

Oxidising: 617.65 Ohms
Reducing: 37759.51 Ohms
NH3: 461.96 Ohms

Oxidising: 565.66 Ohms
Reducing: 85284.40 Ohms
NH3: 721.92 Ohms

Oxidising: 513.76 Ohms
Reducing: 113696.97 Ohms
NH3: 1037.04 Ohms

Oxidising: 513.76 Ohms
Reducing: 135304.35 Ohms
NH3: 1409.13 Ohms

Oxidising: 565.66 Ohms
Reducing: 152108.11 Ohms
NH3: 1731.96 Ohms```

```console
root@zero:/home/pi/enviroplus-python/examples# ./light.py
light.py - Print readings from the LTR559 Light & Proximity sensor.

Light: 00.00 Lux
Proximity: 00.00

Light: 07.97 Lux
Proximity: 00.00

Light: 07.97 Lux
Proximity: 00.00

Light: 07.97 Lux
Proximity: 00.00```

base example gives error

right after a clean install on rpi3

(env) pi@raspberrypi:~/AIY-projects-python/enviroplus-python/examples $ python compensated-temperature.py 
compensated-temperature.py - Use the CPU temperature
to compensate temperature readings from the BME280 sensor.
Method adapted from Initial State's Enviro pHAT review:
https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441

Press Ctrl+C to exit!


Traceback (most recent call last):
  File "compensated-temperature.py", line 39, in <module>
    cpu_temp = get_cpu_temperature()
  File "compensated-temperature.py", line 29, in get_cpu_temperature
    return float(output[output.index('=') + 1:output.rindex("'")])
TypeError: a bytes-like object is required, not 'str

python3 not supported yet

$ python3 enviroplus-python/examples/all-in-one.py

Displays readings from all of Enviro plus' sensors

Press Ctrl+C to exit!

Traceback (most recent call last):
File "enviroplus-python/examples/all-in-one.py", line 143, in
cpu_temp = get_cpu_temperature()
File "enviroplus-python/examples/all-in-one.py", line 96, in get_cpu_temperature
return float(output[output.index('=') + 1:output.rindex("'")])
TypeError: argument should be integer or bytes-like object, not 'str'

Converted c++ code into python

I'm trying to converted a bit of c++ code which uses a MiCS6814 to estimate the ppm of the detectable gasses but I'm not sure how to get the equivalent enviroplus-python values for resistance & base resistance with in the getCurrentRatio function which is then used with in the measure function. Could anyone give me any pointers please?

pms5003 timeouts

Hi,

I keep getting timeouts with the pms5003 particle sensor library

In [5]: readings = pms5003.read()
---------------------------------------------------------------------------
ReadTimeoutError                          Traceback (most recent call last)
<ipython-input-5-dc7f60780eda> in <module>
----> 1 readings = pms5003.read()

/usr/local/lib/python3.7/dist-packages/pms5003-0.0.2-py3.7.egg/pms5003/__init__.py in read(self)
    119             elapsed = time.time() - start
    120             if elapsed > 5:
--> 121                 raise ReadTimeoutError("PMS5003 Read Timeout")
    122
    123             sof = bytearray(self._serial.read(2))

ReadTimeoutError: PMS5003 Read Timeout

It times out every time. I have not gotten a reading from it yet. What are some things I can do to debug? I can hear the fan spinning on the pms5003 sensor, so it appears to be on.

Adding a CSV writer to the All-in-One script

Could anyone help me with this? I tried to add a csv writer to the all-in-one script so that each row indicated the variables taken at each interval. However I couldnt get this to work properly. Does anyone have anything similar they could share? Thanks

all-in-one.py always hangs after ltr559.get_proximity() returns 6291552

and this 6291552 value is constant every single time

the python process hangs at random times too

2019-08-07 04:07:04.255 INFO temp: 16.9 C
2019-08-08 06:27:57.758 INFO temp: 17.6 C
2019-08-10 15:33:00.070 INFO temp: 26.6 C
2019-08-11 22:16:45.719 INFO temp: 21.5 C
2019-08-12 06:08:43.521 INFO temp: 20.7 C
2019-08-13 03:26:02.298 INFO temp: 19.0 C
2019-08-14 16:07:36.694 INFO temp: 25.9 C
2019-08-15 04:02:06.605 INFO temp: 17.3 C
2019-08-16 03:15:17.037 INFO temp: 22.4 C
2019-08-17 17:53:19.751 INFO temp: 26.6 C

anybody seen anything like it?

it must be an issue coming from ltr559, as the whole python process is hosed after that

Please clarify the PMS output

The current output erroneously gives the impression that the first 3 values are the actual amount of particles read by the sensor with the names like combustion particles, organic compounds, metals.
Those values are actually the standard value, which is a calculation off the concentration "corrected" to the "standard atmosphere", and not the real values of the sensor.
https://www.aqmd.gov/docs/default-source/aq-spec/resources-page/plantower-pms5003-manual_v2-3.pdf

PM1.0 ug/m3 (ultrafine particles): 88
PM2.5 ug/m3 (combustion particles, organic compounds, metals): 129
PM10 ug/m3 (dust, pollen, mould spores): 148
PM1.0 ug/m3 (atmos env): 58
PM2.5 ug/m3 (atmos env): 85
PM10 ug/m3 (atmos env): 98

There is more info here:
https://publiclab.org/questions/samr/04-07-2019/how-to-interpret-pms5003-sensor-values#c23772

At least for me, this is how different this values are comparing to other similar devices side by side reporting in "under atmospheric environment" :
https://imgur.com/a/NbRluZU

Issues with setup

Working with Raspberry Lite

enviroplus 0.0.1 Python Library: Installer

Installing for Python 2..
Checking for python-numpy
Checking for python-smbus
Checking for python-pil
Traceback (most recent call last):
  File "setup.py", line 25, in <module>
    from setuptools import setup
ImportError: No module named setuptools
Installing for Python 3..
Checking for python3-numpy
Checking for python3-smbus
Checking for python3-pil
Traceback (most recent call last):
  File "setup.py", line 25, in <module>
    from setuptools import setup
ModuleNotFoundError: No module named 'setuptools'
Setting up i2c and SPI..
Backing up /boot/config.txt to /boot/config.preinstall-enviroplus-2019-04-04-07-04-05.txt
Setting up serial for PMS5003..
Adding dtoverlay=pi3-miniuart-bt # for Enviro+ to /boot/config.txt
Done!

Ill send in a PR to add python-setuptools

Installation issues on Stretch Lite

Hi - its entirely possible the problem is with me, as I am not that familiar with Linux or Python, however - I installed Stretch Lite on my Pi0WH, and have installed python and python3, along with pip (and pip3) and git.

When I run "sudo ,/install.sh", the install script runs, but I get a warning flash up (twice, once for python2 and once for python3):

Installing for Python 2..
/usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'project_urls'
warnings.warn(msg)

and

Installing for Python 3..
/usr/lib/python3.5/distutils/dist.py:261: UserWarning: Unknown distribution option: 'project_urls'
warnings.warn(msg)

There doesn't appear to be any other errors. Having looked online, it was suggested that the setuptools app was out of date, and to run "pip install setuptools --upgrade" which I did, and it installed version 41 if I recall.

Re-run the installer but the errors remain.

I tried carrying on regardless, and when I try and run "python luftdaten.py" the I get:

Traceback (most recent call last):
File "luftdaten.py", line 3, in
import requests
ImportError: No module named requests

Nothing is showing on the Enviro+ display either.

Hope I have provided enough information!

Problems getting started

Hi,

I'm following the getting started instructions here

  • I've installed and updated Raspian on my Pi Zero
  • When I run the install script I get this

image

Can you advise?

Apparently incompatabile with Buster Lite

the setup guide is missing alot of needed installs. For example. I have had to install

  • Git
  • Python
  • sumbus2
  • numpy

Is there not a consolidated script that can install this for semi-beginners like myself.

LCD always shows id after executing luftdaten.py

HI,

I've executed luftdaten.py script in order to get my sensor ID for luftdaten registration page. The thing is, after that, there is no way to get others scripts working on lcd screen.

I've made a reboot, a hard reset and even uninstalled all data... nothing.

Anyone has experienced this?

rotate_mode

It be nice for me at least to see all the readings.
So I add a rotate_mode like proximity.
Anything > 0 enables it, default is 10 seconds for me.

diff --git a/examples/all-in-one-no-pm.py b/examples/all-in-one-no-pm.py
index 6bb6873..100cf9e 100755
--- a/examples/all-in-one-no-pm.py
+++ b/examples/all-in-one-no-pm.py
@@ -101,6 +101,7 @@ factor = 0.8
 cpu_temps = [get_cpu_temperature()] * 5
 
 delay = 0.5  # Debounce the proximity tap
+rotate_mode = 10  # seconds between screen mode rotate
 mode = 0  # The starting mode
 last_page = 0
 light = 1
@@ -130,6 +131,12 @@ try:
             mode %= len(variables)
             last_page = time.time()
 
+        # If time elapsed > rotate_mode, show next mode
+        if rotate_mode > 0 and time.time() - last_page > rotate_mode:
+            mode += 1
+            mode %= len(variables)
+            last_page = time.time()
+
         # One mode for each variable
         if mode == 0:
             # variable = "temperature"

[Question] - Enviro example with icons

Hi there

Just a question: the example shown on the store page for Enviro, the one with icons and sensor values with the orange backgroufnd. Where can i find it?

Thanks

all-in-one error

unfortunately there is a new error. when running this from ipython:

In [12]: %run all-in-one.py                                                                                   
all-in-one.py - Displays readings from all of Enviro plus' sensors

Press Ctrl+C to exit!


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/AIY-projects-python/enviroplus-python/examples/all-in-one.py in <module>
    133             variable = "temperature"
    134             unit = "C"
--> 135             cpu_temp = get_cpu_temperature()
    136             # Smooth out with some averaging to decrease jitter
    137             cpu_temps = cpu_temps[1:] + [cpu_temp]

~/AIY-projects-python/enviroplus-python/examples/all-in-one.py in get_cpu_temperature()
     87     process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
     88     output, _error = process.communicate()
---> 89     return float(output[output.index('=') + 1:output.rindex("'")])
     90 
     91 

TypeError: a bytes-like object is required, not 'str'

BME280 humidity readings issue

Hi,

I am having issues with the humidity reading of the BME280 sensor. Here we have around 80% of relative humidity, however, the maximum value I get with the all-in-one-no-pm.py is 36-40% HR.

I have looked at the BME280 datasheets and it can read from 0-100% HR, so in theory, an 80% HR is achievable.

Any idea or suggestion is welcomed.

trying to start it all on startup gives Read Timeout

so ... this seems a bit odd. i have a script that runs just fine from the terminal but it gives this error when it is started up with @reboot in crontab.

Traceback (most recent call last):
  File "/home/pi/AIY-projects-python/enviroplus-python/examples/particles-lcd.py", line 48, in <module>
    readings = pms5003.read()
  File "build/bdist.linux-armv7l/egg/pms5003/__init__.py", line 121, in read
pms5003.ReadTimeoutError: PMS5003 Read Timeout

any suggestions what would be wise here? i am trying to make my raspberry log useful info to the screen such that when i leave it in a room with power plugged in it will show metrics without the need for the raspberry to be plugged into a screen.

Update luftdaten.py with better error handling and logging

I can see a few improvements to luftdaten.py which may be worth incorporating:

  1. Moving update_time = time.time() to before send_to_luftdaten so the data sending function has the full 145??? seconds to retry sending the values. Though I can't see any fearture for sending a timestamp to luftdaten.
  2. Adding python logging, so we can log success/failure states and other info with timestamps, this is illustrated nicely here:
    import logging
    logging.basicConfig(
    format='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S')
    logging.info("""all-in-one.py - Displays readings from all of Enviro plus' sensors
    Press Ctrl+C to exit!
    """)
  3. Catch exceptions when posting data to luftdaten as raised in #79 - should attempt to send data multiple times (with a small delay) and output a log entry in case of failure.

Need to ensure instructions aren't broken: https://learn.pimoroni.com/tutorial/sandyj/enviro-plus-and-luftdaten-air-quality-station

Should probably attempt to log to /tmp/luftdaten.log since the instructions linked above do not pipe error output anywhere useful.

Additionally it might be worth authoring a systemd unit for running and maintaining the script.

Install misses package

The install fails because it can't find a package named 'ffi'. For both Python 2 and 3.

This is fixed by running:
sudo apt-get install python3-cffi python-cffi
And restarting the install.

Examples LCD gives an error

While following the getting started guide but ran into problems while testing the LCD.
I get this error

pi@raspberrypi:~/enviroplus-python/examples $ python lcd.py
Traceback (most recent call last):
  File "lcd.py", line 3, in <module>
    import ST7735
  File "/usr/local/lib/python2.7/dist-packages/ST7735-0.0.3-py2.7.egg/ST7735/__init__.py", line 25, in <module>
    import spidev
ImportError: No module named spidev
pi@raspberrypi:~/enviroplus-python/examples $

the same for all-in-one.py

pi@raspberrypi:~/enviroplus-python/examples $ python all-in-one.py
Traceback (most recent call last):
  File "all-in-one.py", line 7, in <module>
    import ST7735
  File "/usr/local/lib/python2.7/dist-packages/ST7735-0.0.3-py2.7.egg/ST7735/__init__.py", line 25, in <module>
    import spidev
ImportError: No module named spidev
pi@raspberrypi:~/enviroplus-python/examples $

installed python version is 2.7.16

pi@raspberrypi:~/enviroplus-python/examples $ python
Python 2.7.16 (default, Apr  6 2019, 01:42:57)
[GCC 8.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
[1]+  Stopped                 python
pi@raspberrypi:~/enviroplus-python/examples $

What can be the problem?

noise.py amp_total wrong

get_noise_profile() always returns the same value for amp_total.
amp_total = (low + mid + high) / 3.0
low, mid, high are parameters. Shouldn't that be
amp_total = (amp_low + amp_mid + amp_high) / 3.0
?

problems with enviro + library

I have a problem with the enviro (+) library with an enviro card. When I launch weather.py I get these messages:
  Traceback (most recent call last):
   File "/home/pi/enviroplus-python/examples/weather.py", line 4, in
     from bme280 import BME280
   File "/usr/local/lib/python3.7/dist-packages/pimoroni_bme280-0.0.2-py3.7.egg/bme280/init.py", line 2, in
     from i2cdevice import Device, Register, BitField, _int_to_bytes
ModuleNotFoundError: No module named 'i2cdevice'

I did ; pip install i2cdevice and bme280, but always the same,

weather-and-light example fails with SyntaxError

Clean Raspbian Lite install, one line installer for dependencies, clone this repo to directory, navigate to repo and call "python weather-and-lite.py' on a raspberry pi zero causes the following error

File "weather-and-light.py", line 380
SyntaxError: Non-ASCII character '\xc2' in file weather-and-light.py on line 380, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

Adding

# -*- coding: utf-8 -*-

to the file removes this issue, but then you get the following error:

  File "weather-and-light.py", line 381
    temp_string = f"{corr_temperature:.0f}°C"
                                             ^
SyntaxError: invalid syntax

Removing the °C still causes this error

device reports readiness to read but returned no data

Getting a lot of the following errors. Anyone else encountered this before?

read failed: device reports readiness to read but returned no data (device disconnected or multiple access on port?)

Perhaps because serial port is trying to be accessed by another process or should be disalbed at boot? I'm presently trying to integrate with BaleanOS for easier device deployments. Perhaps a config.txt boot setting could cause this?

No display for noise analysis example

When I run python3 lcd.py I get the expected output on the display

image

However when I run python3 noise-profile.py I see the backlight turn on but there's no display?

image

Extra dependency needed

With the regular white Enviro (not with air monitoring), I needed to install one more dependency to get the noise-profile.py working. Possibly this should be done when enviro is setup the first time.

python3 -m pip install sounddevice

why use GPU instead of CPU for temperature compensation?

Just out of curiosity - why does it compensate relative to the GPU temperature returned from the video core library instead of reading the CPU temperature? The two are pretty similar, but the latter is easier to get at.

process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)

You can directly read the CPU core temperature from /sys/class/thermal/thermal_zone0/temp and not run the vcgencmd sub process.

Localization of dt in sun_moon_time() of weather-and-light.py

I've found that the dt = pytz.timezone(time_zone).localize(dt) in line 90 appears to always return the datetime based on the Raspberry Pi's timezone setting , rather than the timezone provided to pytz. This issue is highlighted here https://www.journaldev.com/23370/python-pytz

This is only an issue if the timezone provided to pytz differs from the Raspberry Pi's timezone setting. In may case, I want to be able to deploy systems in multiple time zones without needing to change the Raspberry Pi's timezone setting.

I addressed it by using astimezone to convert to the desired timezone via UTC as follows:
utc = pytz.utc
utc_dt = datetime.now(tz=utc)
local_dt = utc_dt.astimezone(pytz.timezone(time_zone))
today = local_dt.date()
I then used local_dt in the remainder of sun_moon_time() and also returned that value so that the local time is displayed, rather than the Raspberry Pi's system time.

Let me know if you agree that this is an issue. If so, I'm happy to raise a PR.

Invalid argument on read()

After a while, the script will fail with the following printed in the Terminal:

(22, 'Invalid argument')

And when I press Ctrl + C I get the following stack trace:

  File "./luftdaten.py", line 177, in <module>
    values = read_values()
  File "./luftdaten.py", line 62, in read_values
    pm_values = pms5003.read()
  File "/usr/local/lib/python2.7/dist-packages/pms5003-0.0.4-py2.7.egg/pms5003/__init__.py", line 123, in read
    sof = bytearray(self._serial.read(2))
  File "/usr/local/lib/python2.7/dist-packages/pyserial-3.4-py2.7.egg/serial/serialposix.py", line 480, in read
    timeout = Timeout(self._timeout)
  File "/usr/local/lib/python2.7/dist-packages/pyserial-3.4-py2.7.egg/serial/serialutil.py", line 123, in __init__
    def __init__(self, duration):
KeyboardInterrupt

But I can't see why it's failing. Does anyone know the exception to catch in this case?

Support MEMS microphone

I received my enviro+ last week and over the weekend I managed to install the examples and build my own InfluxDB bridge to show all those measurements via Grafana. Had a lot of tinkering fun, thanks :)

But I'm missing a way to interface the MEMS microphone to read out noise levels. I suppose that support is under way, can someone give an ETA or directions where to read further.

Running live vs cron

I've tinkered with the weather.py code to create my own routine. I've noticed that when you read data from the sensors just once you get a different measurement to what you get if you loop through the process a few times as it seems to correct itself after the second reading. So I've set it to loop ten times, and then write the tenth set of readings to a CSV file.

If I run the routine at the terminal prompt (python /home/pi/enviro.py) it writes accurate readings to the CSV. However, I've set up a cron job to run it every 30 minutes, and always the readings it outputs are exactly the same, without even a millionth of a degree difference between each running:

Temperature: 22.54967373898835
Pressure: 676.4017617518247
Humidity: 89.2103699647858

Can anybody show me what I'm doing wrong?

#!/usr/bin/env python3

import time

from bme280 import BME280

try:
    from smbus2 import SMBus
except ImportError:
    from smbus import SMBus

import logging

logging.basicConfig(
    format='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S')

logging.info("""Print readings from the BME280 weather sensor.
""")

bus = SMBus(1)
bme280 = BME280(i2c_dev=bus)

from datetime import datetime

now = datetime.now()
thedate = now.strftime("%Y-%m-%d")
thetime = now.strftime("%H:%M:%S")

counter = 0

while counter < 10:
    temperature = bme280.get_temperature()
    pressure = bme280.get_pressure()
    humidity = bme280.get_humidity()
    logging.info("""Temperature: {:05.2f} *C
Pressure: {:05.2f} hPa
Relative humidity: {:05.2f} %
""".format(temperature, pressure, humidity))
    counter = counter + 1


import csv
csvRow = [thedate, thetime, temperature, pressure, humidity]
csvfile = "/home/pi/lounge.csv"
with open(csvfile, "a") as fp:
    wr = csv.writer(fp, dialect='excel')
    wr.writerow(csvRow)

Allow for Backlight Brightness Control in Python

It would be great if you could control the brightness of the TFT screen. Right now even when you make the color red, its very bright in a dark room. It would be great if it supported some level of PWM to darken the screen up.

Calibration / correction of sensor readings

Is there any standardised way of calibrating the sensors provided with the Enviro+ or can a simple linear correction be applied in python to some of these?

The following readings seem to be off (I don't have comparables for the others):

  • Temperature: Around 10C to high (enviro board is attached to a RPi4 with a heatsink and at 90deg angle, so it's unlikely this is due to the heat from the CPU)
  • Humidity: Is reading around 15-20% while other sensors (incl Luftdaten) suggest 46-52%
  • Pressure: Off by 6 hPa compared to Luftdaten (accuracy is pretty important here)

How are other's handling this issue?

Raspberry Pi 4 Enviro+ examples error.

Hi,

I'm using Raspberry Pi 4.
I'm getting an error when I try to run example weather.

image

Maybe I have a problem w Enviro+ because the display always blank.

IMG_20201018_153706

When I run sudo i2cdetect -y 1 I get:

image

Do you have any idea what could be wrong?

Easy way to detect if gas sensor is available

Hello,

I have both an Enviro (for inside) and an Enviro+ (for outside).

I am writing code to collect data from them. The same code will run on each device, with the only difference being that the Enviro+ also collects data from the gas sensor.

At the moment, I am using this rather nasty bit of code to detect if the gas sensor is available:

try:
    gas.read_all()
    hasGasSensor = True
except Exception:
    hasGasSensor = False

This works, however I am worried about what kind of exceptions might be thrown during read_all. Without the try/except, I get "OSError: [Errno 121] Remote I/O error" from the i2c code. I only hope that code is properly cleaning up after it fails to connect to the sensor, or that it doesn't modify anything.

It would be nice if the library provided a cleaner way to detect if the sensor is available. Something like an is_available method, which detects if the sensor is available/active before attempting to do anything with it.

I could be wrong, and my try/except method above is perfectly fine. But if that is the case then the library could just use that as the implementation of is_available.

Combined.py - not python 3 compatible and text display issues

In the display_everything() function -
xrange is deprecated in python 3
also there is a creep in the x position of each successive text element so they display in a stepped line going off the right side of the screen. The y positions are fine, just the x positions are wrong.

I fixed as follows -
A: changed both xrange() statements to range()
B: changed end of x= statement from (i / row_count)) to (i % column_count))

# Displays all the text on the 0.96" LCD
def display_everything():
    draw.rectangle((0, 0, WIDTH, HEIGHT), (0, 0, 0))
    column_count = 2
    row_count = (len(variables)/column_count)
    for i in range(len(variables)):
        variable = variables[i]
        data_value = values[variable][-1]
        unit = units[i]
        x = x_offset + ((WIDTH/column_count) * (i % column_count))
        y = y_offset + ((HEIGHT/row_count) * (i % row_count))
        message = "{}: {:.1f} {}".format(variable[:4], data_value, unit)
        lim = limits[i]
        rgb = palette[0]
        for j in range(len(lim)):
            if data_value > lim[j]:
                rgb = palette[j+1]
        draw.text((x, y), message, font=smallfont, fill=rgb)
    st7735.display(img)

LCD does not show anything only backlight is on

Hi,

after I have installed the enviro+ and update/upgrade my pi zero W i tried the example of lcd.py and the only thing that happens is that the backlight is on but no "Hello" message!

How can i solve this, it seems that all the connections are fine since i do get measurements when executing other example files.

Suggested enhancement - map gas readings to values stated in MiCS-6814 data sheet

Total newbie suggestion. I am no Pythong programmer.

Why not map the raw values in KOhms from the gas sensor to the value range shown in the data sheet for the MiCS-6814?

For example:

from numpy import interp

# Nitrogen dioxide
oxidised_data = interp(oxidised_data,[0.8,20],[0.05,10])

# Carbon monoxide
reduced_data = interp(reduced_data,[100,1500],[1,1000])

# Amonia.
nh3_data = interp(nh3_data,[10,1500],[1,300])

This code does not take into sensitivity factor which varies over the range.

Read ADC

When will this be possible? The current adc example only reads ref/gnd and the library has no access to the 4th input. I am looking to use my analog co2 sensor with this.

Data reading with PMS5003 - super hi values

Hi,
I have some dubts about values I am getting with PMS5003 sensor.
I am getting very hight values (almoust the double) from the expected.
Is there a way to verify if the sensor is working properly?
The data I am getting are to hi to be very credible.
Is there in general a way to verify data from PMS5003 and BME280?
Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.