class BatteryService(object): def __init__(self): self.powerPin = 0 self.adc = 0 self.Battery = 0 self.vBiasDAC = 0 def confService(self): self.powerPin = Pin('P8', mode=Pin.OUT) self.adc = ADC() self.adc.vref(1058) self.vBiasDAC = DAC('P22') self.vBiasDAC.write(0.135) # approximately 0.5 V self.Battery = self.adc.channel(pin='P14', attn = ADC.ATTN_11DB) def getData(self): self.powerPin(1) time.sleep(0.002) batt = self.Battery.voltage() collectMemory() self.powerPin(0) return batt def connect(self): self.confService()
def main(): # Use the RGB LED as an indicator of WiFi status pycom.heartbeat(False) wlan = WLAN() if wlan.isconnected(): pycom.rgbled(0x000f00) else: pycom.rgbled(0x0f0000) # Set up the onboard ADC and establish a channel for each thermistor adc = ADC() adc.vref(config.VREF_ACTUAL_IN_MILLIAMPS) oven_channel = adc.channel(pin=config.OVEN_THERM_ADC_PIN, attn=ADC.ATTN_11DB) food_channel = adc.channel(pin=config.FOOD_THERM_ADC_PIN, attn=ADC.ATTN_11DB) # Modify config.py with your thermistor values from the datasheet oven = Thermistor(oven_channel, config.THERM_NOMINAL_TEMP, config.THERM_NOMINAL_RES, config.THERM_BETA, config.SERIES_RESISTOR_1, 12.0) food = Thermistor(food_channel, config.THERM_NOMINAL_TEMP, config.THERM_NOMINAL_RES, config.THERM_BETA, config.SERIES_RESISTOR_2, 12.0) dinner_tracker = LosantDinnerTracker(oven, food, status_led=config.STATUS_LED_PIN) dinner_tracker.start()
class AnalogSensor: def __init__(self, pin, attn=ADC.ATTN_0DB, vref=3300): global analog_counter self.pin = pin self.adc = ADC(analog_counter) self.adc.vref(vref) self.adc_channel = self.adc.channel(pin=pin, attn=attn) analog_counter += 1 def read(self): self.adc_channel() value = self.adc_channel.value() return value
def __init__(self, pinx, piny, atten=ADC.ATTN_11DB, width=ADC.WIDTH_12BIT, tolerance=300): self._pinX = pinx self._pinY = piny self._tolerance = tolerance ADC.vref(vref=1150) self._x = ADC(Pin(self._pinX)) self._x.atten(atten) self._x.width(width) self._y = ADC(Pin(self._pinY)) self._y.atten(atten) self._y.width(width) self._angle = 0
from machine import Pin from machine import I2C import pycom from network import LoRa from machine import ADC import socket import machine import ubinascii import tsl2591 # Ambient Light Sensor library file #----------------------------------------------------------------------------------------- #| Setup ADC Configuration: #| Initialize ADC using configured Vref value (1108 mV) and 12 bits of resolution #----------------------------------------------------------------------------------------- adc = ADC(0) adc.vref(1108) adc.init(bits=12) #----------------------------------------------------------------------------------------- #| Initialize Sensor Pinouts - Both GPIO and ADC #| #| Dual JSN-SR04T 2.0 Ultrasonic Sensors (Which sensor is #1 vs #2 does not matter): #| - Sensor 1: Trigger => Pin 21 ("trigger_1"); used as 3.3V GPIO Output from uC to sensor #| - Sensor 1: Echo => Pin 22 ("echo_1"); used as 3.3V (Down from 5V) Input to UC from sensor #| - Sensor 2: Trigger => Pin 23 ("trigger_2"); used as 3.3V GPIO Output from uC to sensor #| - Sensor 2: Echo => Pin 18 ("echo_2"); used as 3.3V (Down from 5V) Input to UC from sensor #| #| TSL2591 Ambient Light Sensor (initialize using "tsl = tsl2591.Tsl2591(0)" statement, #| pins provided below only for reference): #| - SCL (for I2C) => Pin 9; Configured in included tsl2591.py file, not here #| - SDA (for I2C) => Pin 10; Configured in included tsl2591.py file, not here
class TMP36: #resistor value in voltage divider _RESISTOR_REF = const(10) # attributes: # _adc: ADC object corresponding with ADC pin # LoPy4/Exp.board: default P13 # _sensor = ADC-channel which is attached to TMP36 # _threshold: temperature value for warnings def __init__(self, adc_pin): # 2018-0911 adopted for Pycom - added attn self._adc = ADC() self._adc.vref(1094) # calibration from LDR self._sensor = self._adc.channel(pin=adc_pin, attn=ADC.ATTN_11DB) self._threshold = 30 #defaut threshold # get threshold temperature celsius for temperature warning @property def threshold(self): """returns threshold temperature in Celsius""" return self._threshold @threshold.setter def threshold(self, temperature): """set threshold to a temperature in Celsius""" #OK: print('threshold=', temperature) self._threshold = temperature # returns temperature value in Fahrenheit # pre-condition: self_value is not None def fahrenheit(self): """returns temperature in Fahrenheit""" return (self.celsius() * 9 / 5) + 32 # returns temperature value in Celsius # pre-condition: self_sensor is not None # this method ALWAYS read data from sensor def celsius(self): """returns temperature in Celsius""" return (self._millivolts - 500.0) / _RESISTOR_REF #Pycom/LoPy4, Huzzah #NodeMCU: return (self.value) / _RESISTOR_REF # returns temperature value in Kelvin # Celsius to Kelvin: T(k) = T(c) + 273.15 # http://www.rapidtables.com/convert/temperature/how-celsius-to-kelvin.htm # pre-condition: self_value is not None def kelvin(self): """returns temperature in Kelvin""" return self.celsius() + 273.15 # get the raw sensor value in milliVolts @property def _millivolts(self): """returns sensor data in millivolts""" return self._sensor.voltage() # demo run reading T, Ctrl-C to abort def demo(self, threshold=30.0, dt=2.0): """demo of TMP36 sensor""" try: self.threshold = threshold # for temperature warnings print('class TMP36 demo, threshold={0:0.1f}'.format( self._threshold)) # start reading and displaying temperature while True: millivolts = self._millivolts # reading in millivolts celsius_temp = self.celsius() # degree Celsius fahrenheit_temp = self.fahrenheit() # degree Fahrenheit kelvin_temp = self.kelvin() # degree Kelvin print( 'TMP36: millivolts {0:0.1f}\tCelsius {1:0.1f}\tFahrenheit {2:0.1f}\tKelvin {3:0.1f}' .format(millivolts, celsius_temp, fahrenheit_temp, kelvin_temp)) if celsius_temp > self._threshold: print('T>{0:0.1f}: alert on'.format(self._threshold)) sleep(dt) #wait > s, see datasheet except Exception as ex: print(ex) print('TMP36 demo interrupted!')
from math import sqrt from utime import sleep_us adc = ADC() ''' Connects the internal 1.1v to external GPIO. It can only be connected to P22, P21 or P6. It is recommended to only use P6 on the WiPy, on other modules this pin is connected to the radio. ''' adc.vref_to_pin('P21') ''' If called without any arguments, this function returns the current calibrated voltage (in millivolts) of the 1.1v reference. Otherwise it will update the calibrated value (in millivolts) of the internal 1.1v reference. Use the ADC.vref_to_pin(*,pin) method and a voltmeter to find out the actual Vref. ''' adc.vref(1058) apin = adc.channel(pin='G5', attn=ADC.ATTN_11DB) ''' This function measures the ADC pin N times with a sampling period of delay. mean voltage, rms voltage and standard deviation are computed. ''' def measure(N=1000, delay=200): asum = 0 sqsum = 0 meanVolt = 0
from deepsleep import DeepSleep import deepsleep import socket import time import binascii import sys #initiliaze counter = 0 massaArray = [] floatArray = [] alarm = 1 #initiliaze massa sensor configuration (ADC) adc = ADC() adc.vref(3130) pin_massa = adc.channel(pin='P13',attn=ADC.ATTN_11DB) #initiliaze float sensor (GPIO pull up) pin_float_status = 1 pin_float = Pin('P0', mode=Pin.IN, pull=Pin.PULL_UP) #floatValue = 1 if not tripped #floatValue = 0 if tripped, send alarm # initiliaze relay (GPIO) pin_relay = Pin('P2',mode=Pin.OUT) pin_relay.value(0) #Initiliaze Sigfox def sendMessage():
from machine import ADC adc = ADC() # calibration - see Pycom documentation #adc.vref_to_pin('P6') # only P6, P21, P22 can be used. # # a reference voltage of 1.1V is on Pin, # measure a value with a multimeter, # For example my measured value was 1094 mV. # This will be calibrated value for adc.vref(value) # After reading value on multimeter: # 1. RESET the board!! # 2. comment the code adc.vref_to_pin('P6') # set calibration adc.vref(1094) # lightsensor is connected to GPIO3 / P16 # create an ADC-channel, use highest attenuation of 11dB # (ADC.ATTN_11DB) in order to use 3V3 input. # https://docs.pycom.io/firmwareapi/pycom/machine/adc ldr = adc.channel(pin='P16', attn=ADC.ATTN_11DB) # test lightsensor: reading values from time import sleep def test1(): while True: print('light={} mV'.format(ldr.voltage())) sleep(1)
import machine import pycom from machine import ADC from dth import DTH print("starting") pycom.heartbeat(False) th = DTH("P23", 1) time.sleep(2) adc = ADC() adc.vref_to_pin("P22") adc.vref(1100) adc_c = adc.channel(pin="P16", attn=ADC.ATTN_11DB) lora = LoRa(mode=LoRa.LORA, region=LoRa.US915) lora.init( tx_power=14, sf=7, frequency=915000000, coding_rate=LoRa.CODING_4_5, bandwidth=LoRa.BW_125KHZ, power_mode=LoRa.TX_ONLY, ) s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
vref = { 'lopy4-52e0': 1133, # does adc.vref() actually do anything? I see no effect :-P } if name not in vref: print('module', name, "has not been calibrated") import sys sys.exit() # calibration: # 1. output the internal reference voltage of 1100mV to P22 adc.vref_to_pin('P22') # 2. measture the voltage at P22 with a voltmeter # 3. enter the actual value into vref above and then re-run else: print('calibrate vref for', name) adc.vref(vref[name]) print("vref=", adc.vref(), "mV") # create an analog pin # Valid pins are P13 to P20. # attenuation suggested range: # (dB) (mV) # 0 100 ~ 950 # 2.5 100 ~ 1250 # 6 150 ~ 1750 # 11 150 ~ 2450 apin = adc.channel(pin='P20', attn=ADC.ATTN_11DB) # P20 seventh from top right
class IrradiationSensor(object): def __init__(self): self.serviceID = 3 self.samplingFrequency = 0 self.mode = 0 self.lastRadiation = 0 self.sumRadiation = 0 self.sampleCounter = 0 self.enabled = False self.sampleThread = 0 self.powerPin = 0 self.adc = 0 self.panel = 0 self.vBiasDAC = 0 self.lock = 0 self.errorLogService = 0 self.erCounter = 3 def confService(self, atributes): self.powerPin = Pin('P8', mode=Pin.OUT) self.adc = ADC() self.adc.vref(1058) self.vBiasDAC = DAC('P22') self.vBiasDAC.write(0.135) # approximately 0.5 V self.panel = self.adc.channel(pin='P13', attn=ADC.ATTN_11DB) self.errorLogService = atributes['errorLogService'] self.lock = atributes['lock'] if ('mode' in atributes) and ('samplingFrequency' in atributes): if not str(atributes['samplingFrequency']).isdigit() or atributes[ 'samplingFrequency'] < 0: #Comprobar si es un numero (isdigit) y si es negativo self.errorLogService.regError( self.serviceID, -9) #Incorrect AtributeValue Error else: self.samplingFrequency = atributes['samplingFrequency'] if not str(atributes['mode']).isdigit() or atributes[ 'mode'] < 0: #Comprobar si es un numero (isdigit) y si es negativo self.errorLogService.regError( self.serviceID, -9) #Incorrect AtributeValue Error else: self.mode = atributes['mode'] else: self.errorLogService.regError(self.serviceID, -2) #ConfFile Error def start(self): try: self.sampleThread = _thread.start_new_thread(self.sampling, ()) except: self.errorLogService.regError(self.serviceID, -3) #CreateThread Error code def sampling(self): while True: if self.enabled is True: time.sleep( self.samplingFrequency - 0.002 ) # Reducir el tiempo de muestreo teniendo en cuenta el sleep de powerPin self.lock.acquire() self.powerPin(1) time.sleep(0.002) self.lastRadiation = self.panel.voltage() count = 0 #El valor para el panel es aproximado pues se considera que devuelve 1000 en un día soleado de 25º while ((self.lastRadiation < 1.0 or self.lastRadiation > 10000.0) and count < self.erCounter): time.sleep(0.002) self.lastRadiation = self.panel.voltage() count += 1 if (self.lastRadiation < 1.0 or self.lastRadiation > 10000.0): self.errorLogService.regError( self.serviceID, -11) #Incorrect Value Error code else: self.sumRadiation += self.lastRadiation self.sampleCounter += 1 collectMemory() self.powerPin(0) self.lock.release() else: _thread.exit() def updateAtribute(self, atribute, newValue): if not str(newValue).isdigit() or newValue < 0: self.errorLogService.regError(self.serviceID, -9) #Incorrect Atribute Error else: if atribute == 'samplingFrequency': self.samplingFrequency = newValue elif atribute == 'mode': self.mode = newValue else: self.errorLogService.regError( self.serviceID, -8) #Incorrect Atribute Error code def getData(self): data = 0 self.lock.acquire() if self.mode == 0: try: data = self.sumRadiation / self.sampleCounter except ZeroDivisionError: self.errorLogService.regError(self.serviceID, -10) #ZeroDivisionError code elif self.mode == 1: data = self.lastRadiation else: self.errorLogService.regError(self.serviceID, -9) #Incorrect AtributeValue Error self.sumRadiation = 0 self.sampleCounter = 0 self.lock.release() return data def disconnect(self): self.enabled = False def connect(self, atributes): self.enabled = True self.confService(atributes) self.start() def serviceEnabled(self): return self.enabled
def peripheral_query(is_init, p_out_ctrla, p_out_ctrlb): import pycom import time import socket import binascii import struct import gc import sys import os import uio import ujson from machine import UART from machine import ADC from machine import I2C from machine import SPI from machine import Pin from tsl2591 import TSL2591 with uio.open('/flash/configure.json', 'r', encoding="utf-8") as hdl: parsed_json = ujson.load(hdl) sht31 = parsed_json["firmware"]["sht31"] bias_nh3 = parsed_json["calibration"]["sensor_nh3"]["bias"] bias_so2 = parsed_json["calibration"]["sensor_so2"]["bias"] bias_h2s = parsed_json["calibration"]["sensor_h2s"]["bias"] di_nh3 = parsed_json["calibration"]["sensor_nh3"]["di"] di_so2 = parsed_json["calibration"]["sensor_so2"]["di"] di_h2s = parsed_json["calibration"]["sensor_h2s"]["di"] i0_nh3 = parsed_json["calibration"]["sensor_nh3"]["i0"] i0_so2 = parsed_json["calibration"]["sensor_so2"]["i0"] i0_h2s = parsed_json["calibration"]["sensor_h2s"]["i0"] vref = parsed_json["calibration"]["vref"] p_data = PeripheralData() print('[2]===================') adc0 = ADC(id=0) outer_iter = 0 outer_iter_times = 20 outer_buff_NH3 = [] outer_buff_SO2 = [] outer_buff_H2S = [] while outer_iter < outer_iter_times: filtered_mvolts = _get_filtered_mvolts(adc0, vref) outer_buff_NH3.append(filtered_mvolts.NH3) outer_buff_SO2.append(filtered_mvolts.SO2) outer_buff_H2S.append(filtered_mvolts.H2S) outer_iter = outer_iter + 1 buff_nh3 = sum(outer_buff_NH3) / outer_iter_times buff_so2 = sum(outer_buff_SO2) / outer_iter_times buff_h2s = sum(outer_buff_H2S) / outer_iter_times buff_nh3 = round((buff_nh3 - bias_nh3 - i0_nh3 * 47 * 0.624) * 50 / (di_nh3 * 47 * 0.624), 1) adc0_str = '%.1f' % ((buff_nh3)) p_data.NH3 = (buff_nh3) print('[2]NH3: ' + adc0_str) buff_so2 = round((buff_so2 - bias_so2 - i0_so2 * 47 * 0.624) * 20 / (di_so2 * 47 * 0.624), 1) adc1_str = '%.1f' % ((buff_so2)) p_data.SO2 = ((buff_so2)) print('[2]SO2: ' + adc1_str) buff_h2s = round((buff_h2s - bias_h2s - i0_h2s * 47 * 0.624) * 50 / (di_h2s * 47 * 0.624), 1) adc2_str = '%.1f' % ((buff_h2s)) p_data.H2S = ((buff_h2s)) print('[2]H2S: ' + adc2_str) adc0.deinit() time.sleep(0.01) adc3 = ADC(id=0) # create an ADC object apin3 = adc3.channel(pin='P16') # create an analog pin on P16 adc3.vref(vref) adc3_str = '%.2f' % (apin3() * 220 / 4096) p_data.current = apin3() * 220 / 4096 print('[2]Current@5V: ' + adc3_str + 'mA') adc3.deinit() p_out_ctrla.value(0) p_out_ctrlb.value(1) uart_mul = UART(1, baudrate=9600, pins=('P3', 'P4')) time.sleep(0.1) co2_set = is_init while co2_set == 0: uart_mul.write('K 2\r\n') time.sleep(0.05) dumm = uart_mul.readline() if dumm == bytes([]): print('[2]CO2 sensor no respose!') break else: dumm_str = dumm.decode('utf-8') if dumm_str == ' K 00002\r\n': print('[2]CO2 sensor polling set successfully...') time.sleep(0.05) co2_set = 1 else: print('[2]CO2 sensor polling resetting...') time.sleep(0.05) uart_mul.write('M 00006\r\n') time.sleep(0.05) dumm_str = uart_mul.readall().decode('utf-8') if dumm_str == ' M 00006\r\n': print('[2]CO2 sensor key set successfully...') time.sleep(0.05) time.sleep(0.05) number = 0 while number != 18: dummy = uart_mul.readall() uart_mul.write('Q\r\n') time.sleep(0.1) number = uart_mul.any() data_str = uart_mul.readall().decode("utf-8") print('[2]CO2_Filtered: ' + data_str[4:8]) print('[2]CO2_Instant: ' + data_str[12:16]) p_data.CO2 = int(data_str[4:8]) * 100 - 1600 print('[2]CO2: ' + ('%d' % (p_data.CO2))) i2c = I2C(0, I2C.MASTER) i2c.init(I2C.MASTER, baudrate=100000, pins=('P9', 'P10')) time.sleep(0.05) #print(i2c.scan()) if sht31 == 0: i2c.writeto(0x40, bytes([0xF3])) time.sleep(0.1) temperature_data = i2c.readfrom(0x40, 3) #print(temperature_data) time.sleep(0.1) temperature_value = _get_temperature_from_buffer(temperature_data) p_data.temp = temperature_value time.sleep(0.1) i2c.writeto(0x40, bytes([0xF5])) time.sleep(0.05) humidity_data = i2c.readfrom(0x40, 3) humidity_value = _get_humidity_from_buffer(humidity_data) p_data.humd = humidity_value humidity_value_str = '%.2f' % humidity_value temperature_value_str = '%.2f' % temperature_value print('[2]Humidity: ' + humidity_value_str) print('[2]Temperature: ' + temperature_value_str) else: i2c.writeto(0x44, bytes([0x24, 0x00])) time.sleep(0.02) combined_data = i2c.readfrom(0x44, 6) temperature_value = _get_sht31_temp_from_buffer(combined_data) p_data.temp = temperature_value humidity_value = _get_sht31_humidity_from_buffer(combined_data) p_data.humd = humidity_value humidity_value_str = '%.2f' % humidity_value temperature_value_str = '%.2f' % temperature_value print('[2]Humidity (SHT31): ' + humidity_value_str) print('[2]Temperature (SHT31): ' + temperature_value_str) lux_sensor = TSL2591(i2c) lux_flt = lux_sensor.lux p_data.lux = lux_flt print('[2]Light: ' + '%.2f' % lux_flt + 'lux') uart_mul = UART(1, baudrate=9600, pins=('P3', 'P4')) p_out_ctrla.value(1) p_out_ctrlb.value(0) time.sleep(0.1) ggflag = 0 ddflag = 0 while ggflag == 0 or ddflag == 0: while uart_mul.any() == 0: time.sleep(0.1) nmealine_bytes = uart_mul.readall() #print(nmealine_bytes) time.sleep(0.1) nmealine_all = nmealine_bytes.decode('utf-8') nmealine_all_split = nmealine_all.split('\r\n') for nmealine in nmealine_all_split: if (nmealine[0:6] == '$GNGGA') and (len(nmealine.split(',')) >= 15) and (ggflag == 0): nmea_fields = nmealine.split(',') #print(nmea_fields) print('[2]Time: ' + nmea_fields[1]) if nmea_fields[1] != '': p_data.time = float(nmea_fields[1]) print('[2]Lat: ' + nmea_fields[2] + nmea_fields[3]) if nmea_fields[2] != '': p_data.lat = float(nmea_fields[2]) if nmea_fields[3] == 'S': p_data.lat *= -1 print('[2]Lon: ' + nmea_fields[4] + nmea_fields[5]) if nmea_fields[4] != '': p_data.Lon = float(nmea_fields[4]) if nmea_fields[5] == 'W': p_data.lon *= -1 print('[2]Fix: ' + nmea_fields[6]) print('[2]#Sat: ' + nmea_fields[7]) print('[2]HDOP: ' + nmea_fields[8]) print('[2]Alt: ' + nmea_fields[9]) if nmea_fields[9] != '': p_data.alt = float(nmea_fields[9]) ggflag = 1 elif (nmealine[0:6] == '$GNRMC') and (len(nmealine.split(',')) >= 13) and (ddflag == 0): nmea_fields = nmealine.split(',') print('[2]Date: ' + nmea_fields[9]) if nmea_fields[9] != '': p_data.date = int(nmea_fields[9]) ddflag = 1 dummy = uart_mul.readall() p_data_bytes = PeripheralBytes(p_data) print('[2]===================') time.sleep(0.01) gc.collect() print(gc.mem_free()) return p_data_bytes