Saturday 26 June 2021

Temperature measuring Web Server

So, having had the Pimoroni Breakout Garden for a while and having used it as a temperature measurement device with a BME680 and display, I needed to measure the temperature and compare it with the temperature measured  by the analogue sensor of an Adafruit PyPortal and the CPU temperature.

The BME680 results are affected by the heat generated by the CPU, and a correction formula based on the CPU temperature was used to compensate for the CPU temperature.

An alternative is to separate the temperature sensor from the CPU.

This was achieved using a Breakout Garden to Stemma QT/QWIIC adapter and STEMMA QT / Qwiic to Breakout Garden Adapter  joined by a JST to JST cable. A BMP280 breakout was plugged in at one end, and the other plugged into the Breakout Garden. This should provide sufficient thermal isolation from the hot CPU.


Software installation

The Python library for the BMP280 temperature, pressure and altitude sensor is available via PIP. As with all installations, check if pip is for the now obsolete Python 2.x or Python 3.x. If the former, then use pip3 (that is the case on my Raspberry Pi Zero development systerm).

sudo pip3 install bmp280

The easiest way to make the data available to an Internet connectable device is by making the temperature measuring Raspberry Pi a web server.

The Flask library is similarly installed with pip. Note Flask starts with a capital letter
sudo pip3 install -U Flask

Web Server

This is a very simple web server, it has two  pages - /temperature and /json.

from flask import Flask, render_template
import time
import datetime
import json
from bmp280 import BMP280

try:
    from smbus2 import SMBus
except ImportError:
    from smbus import SMBus
app = Flask(__name__)

@app.route('/temperature')
def temperature():
    now = datetime.datetime.now()
    timeString = now.strftime("%Y-%m-%d %H:%M")
    temperature = bmp280.get_temperature()
    temp = '{:05.2f}*C'.format(temperature)
    templateData = {
      'temperature' : temp,
      'time': timeString
      }
    return render_template('temperature.html', **templateData)

@app.route('/json')
def tempjson():
    now = datetime.datetime.now()
    timeString = now.strftime("%Y-%m-%d %H:%M")
    temperature = bmp280.get_temperature()
    temp = '{:05.2f}'.format(temperature)
    templateData = {
      'temperature' : temp,
      'time': timeString
      }

    return json.dumps(templateData)

if __name__ == '__main__':
    bus = SMBus(1)
    bmp280 = BMP280(i2c_dev=bus)
    app.run(debug=True, host='0.0.0.0')

References