Last active
November 19, 2019 05:53
-
-
Save IdrisCytron/aa9b23b404e97f07c65cd45ec1b1b374 to your computer and use it in GitHub Desktop.
Read pressure, altitude and temperature from MPL3115A2 sensor and send to ProjekIoT.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import time | |
from gpiozero import Buzzer | |
from urllib import request, error | |
import board | |
import busio | |
import adafruit_mpl3115a2 | |
buzzer = Buzzer(26) | |
# Initialize the I2C bus. | |
i2c = busio.I2C(board.SCL, board.SDA) | |
# Initialize the MPL3115A2. | |
sensor = adafruit_mpl3115a2.MPL3115A2(i2c) | |
# Alternatively you can specify a different I2C address for the device: | |
#sensor = adafruit_mpl3115a2.MPL3115A2(i2c, address=0x10) | |
# You can configure the pressure at sealevel to get better altitude estimates. | |
# This value has to be looked up from your local weather forecast or meteorlogical | |
# reports. It will change day by day and even hour by hour with weather | |
# changes. Remember altitude estimation from barometric pressure is not exact! | |
# Set this to a value in pascals: | |
sensor.sealevel_pressure = 102250 | |
token = "430c0d91-3621-4917-9557-3aea5dc5fadb" | |
interval = 60 # in seconds | |
prevTime = 0 | |
buzzer.beep(0.1, 0.1, 2) | |
try: | |
while True: | |
if time() - prevTime > 1: | |
pressure = sensor.pressure / 1000 | |
print("Pressure: {0:0.2f}kPa".format(pressure)) | |
altitude = sensor.altitude | |
print("Altitude: {0:0.2f}m".format(altitude)) | |
temperature = sensor.temperature | |
print("Temperature: {0:0.2f}°C".format(temperature)) | |
url = "http://endpoint.projekiot.com/send?token=" + token | |
url = url + "&pressure={0:0.2f}".format(pressure) | |
url = url + "&altitude={0:0.2f}".format(altitude) | |
url = url + "&temperature={0:0.2f}".format(temperature) | |
url = url + "&interval={}".format(interval) | |
print(url) | |
try: | |
response = request.urlopen(url).read() | |
print(response) | |
except error.HTTPError as e: | |
print(e.code) | |
buzzer.beep(0.1, 0.1, 1) | |
except error.URLError as e: | |
print(e.reason) | |
buzzer.beep(0.1, 0.1, 1) | |
except error.HTTPException as e: | |
print("HTTP Exception") | |
buzzer.beep(0.1, 0.1, 1) | |
except Exception: | |
import traceback | |
print(traceback.format_exc()) | |
buzzer.beep(0.1, 0.1, 1) | |
print("") | |
prevTime = time() | |
except KeyboardInterrupt: | |
buzzer.off() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment