Files
sensornode_py/sensor.py
2021-04-20 20:51:36 +02:00

53 lines
1.8 KiB
Python

from micropython import const
import machine
SENSOR_ADC = const(0)
SENSOR_I2C = const(1)
SENSOR_SPI = const(2)
class Sensor:
def __init__(name, type, **kwargs):
self.name = name
self.type = type
# Different treatment depending on sensortype
if type == SENSOR_ADC:
#ADC is fairly simple
#Only a ADC-Pin is required
if "pin" not in kwargs.keys():
raise ValueError("Sensortype requires a pin (ADC), but no 'pin'-argument was passed")
self.pin = kwargs["pin"]
self.adc = machine.ADC(machine.Pin(self.pin))
# Optionally a attenuation parameter may be supplied
# otherwise the maximum attenuation (i.e. maximum range) is used
if "attenuation" in kwargs.keys():
adc.atten(kwargs["attenuation"])
else:
adc.atten(machine.ADC.ATTN_11DB)
if type == SENSOR_I2C:
if "sda" not in kwargs.keys():
raise ValueError("Sensortype requires pins (I2C), but no 'sda'-argument was passed")
if "scl" not in kwargs.keys():
raise ValueError("Sensortype requires pins (I2C), but no 'scl'-argument was passed")
if "handler" not in kwargs.keys():
raise ValueError("Sensortype requires handler-method (I2C), but no 'handler'-argument was passed")
self.sda = kwargs["sda"]
self.scl = kwargs["scl"]
self.scl = kwargs["handler"]
# SPI isn't used yet
if type == SENSOR_SPI:
raise NotImplementedError("SPI is not yet implemented")
# Read the sensor and return data ready for appending to the POST-request to influxdb
def read():
if type == SENSOR_ADC:
return self.name + "=" + str(self.adc.read())