def measureTemperature(owBus,rom=None): while True: # we loop until we get a valid measurement temp = DS18X20(owBus) temp.start_conversion(rom) time.sleep(1) # wait for one second TempCelsius=temp.read_temp_async(rom) if TempCelsius is not None: return TempCelsius # TempCelsius exit loop and return result
def setup(): global logger, rtc, sd, iCAM, iACC, CTLR_IPADDRESS, logfile, filename global wdt, ow, temp, py, sensor gc.enable() # HW Setup wdt = WDT(timeout=wdt_timeout) sd = SD() rtc = RTC() os.mount(sd,'/sd') # Enable WiFi Antenna Pin('P12', mode=Pin.OUT)(True) # TEMPERATURE SENSORS: DS18B20 and SI7006A20 ow = OneWire(Pin('P10')) temp = DS18X20(ow) py = Pysense() sensor = SI7006A20(py) # SYSTEM VARIABLES iCAM = pycom.nvs_get('iCAM') # pycom.nvs_set('iCAM',1) iACC = pycom.nvs_get('iACC') # pycom.nvs_set('iACC',1) logfile='/sd/log/{}.log'.format(datetime_string(time.time())) logging.basicConfig(level=logging.DEBUG,filename=logfile) logger = logging.getLogger(__name__) # # NETWORK VARIABLES # pbconf = pybytes.get_config() # AP = pbconf['wifi']['ssid'] # if AP == 'wings': # CTLR_IPADDRESS = '192.168.1.51' # elif AP == 'RUT230_7714': # CTLR_IPADDRESS = '192.168.1.100' # # CONNECT TO AP # wlan = WLAN(mode=WLAN.STA) # while not wlan.isconnected(): # nets = wlan.scan() # for net in nets: # if net.ssid == 'RUT230_7714': # pybytes.connect_wifi() # # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8')) # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000) # while not wlan.isconnected(): # machine.idle() # save power while waiting socket_client.CTLR_IPADDRESS = CTLR_IPADDRESS # GREETING logger.info('--------------------') logger.info(' Starting CAM{}-ACC{}'.format(iCAM, iACC)) logger.info('--------------------') logger.info('AP={}'.format(AP)) gc.collect() return
def DS18B20_func(sens_name, sig_nbr, pin_str, temp_prior): #DS18B20 data line connected to pin pin_str pin = Pin(pin_str) ow = OneWire(pin) temp = DS18X20(ow) pycom.heartbeat(False) print('\n' + sens_name + ' sensor is initialized to ' + pin_str) # Prior needs to be within 5 degrees celsius from actual temp temperature_prev = temp_prior while True: temperature = temp.read_temp_async() time.sleep(1) #time.sleep(DELAY) temp.start_conversion() time.sleep(1) # Remove None values and outliers while temperature is None or abs(temperature - temperature_prev) > OUTLIER_THRESHOLD: print(sens_name + ' temperature error: ' + str(temperature)) # In order to remove the None values I need to reinitialize the sensor # it may be a better solution to this ow = OneWire(pin) temp = DS18X20(ow) temperature = temp.read_temp_async() time.sleep(1) temp.start_conversion() time.sleep(1) temperature = round(temperature, DECIMALS) print(sens_name + ' temperature: ' + str(temperature)) # Send to pybytes and blink red pycom.rgbled(0x330000) pybytes.send_signal(sig_nbr, temperature) pycom.rgbled(0x000000) # Send to ubidots and blink green pycom.rgbled(0x003300) ubidots_send.post_var("Pycom", sens_name, temperature) pycom.rgbled(0x000000) temperature_prev = temperature time.sleep(DELAY)
def daemon(): """ Measure the temperature at fixed intervals """ ds = DS18X20(OneWire(Pin.exp_board.G9)) t = 0.0 while True: # measure +- every 30 seconds time.sleep(27) for i, tx in enumerate([t0, t1]): time.sleep_ms(750) ds.start_conversion(ds.roms[i]) time.sleep_ms(750) t = ds.read_temp_async(ds.roms[i]) with t_lock: tx.append(t) if len(tx) > NMEASUREMENTS: del tx[0]
def daemon(): """ Measure the temperature at fixed intervals and adjust fan speed. """ global temp0, temp1, dutycycle ds = DS18X20(OneWire(Pin("P21"))) if len(ds.roms) == 0: print("no temperature sensors found") _thread.exit() t = 0 while True: # measure +- every 30 seconds time.sleep(27) for i in range(len(ds.roms)): time.sleep_ms(750) ds.start_conversion(ds.roms[i]) time.sleep_ms(750) t = int(ds.read_temp_async(ds.roms[i])) with lock: if i == 0: temp0 = t else: temp1 = t temp = max(temp0, temp1) # inlet temperature is highest if temp < (temp_fan_on - hysteresis): dutycycle = 0 set_dutycycle(dutycycle) if temp > temp_fan_on: dutycycle_range = max_dutycycle - min_dutycycle temp_range= temp_fan_max - temp_fan_on temp_clipped = min(max(temp - temp_fan_on, 0), temp_range) dutycycle_raw = int(temp_clipped * (dutycycle_range / temp_range)) dutycycle = 0 if dutycycle_raw <= 0 else min_dutycycle + dutycycle_raw set_dutycycle(dutycycle)
def __init__(self, pin=PIN_TEMP): self._ow = OneWire(pin) self._temp = DS18X20(self._ow) self.temperature = 0 pass
import time from machine import Pin from onewire import DS18X20 from onewire import OneWire powerPin = Pin('G28', mode=Pin.OUT) powerPin(1) ow = OneWire(Pin('G11')) temp = DS18X20(ow) # DS18X20 must be powered on on instantiation (rom scan) powerPin(0) def medir(n=1): powerPin(1) for i in range(n): temp.start_convertion() time.sleep_ms(750) print('{:3.4f}'.format(temp.read_temp_async())) powerPin(0)
def read_temperature(): temp = DS18X20(ow) t_val = temp.read_temp_async() temp.start_conversion() return t_val
import time from machine import Pin from onewire import DS18X20 from onewire import OneWire # DS18B20 data line connected to pin P10 #ow = OneWire(Pin('P10',pull=Pin.PULL_UP)) ow = OneWire(Pin('P10')) temp = DS18X20(ow) # while True: # print(temp.read_temp_async()) # time.sleep(1) # temp.start_conversion() # time.sleep(1) # while True: # print(temp.read_temp_async()) # time.sleep(1) # # temp.start_conversion() # time.sleep(1) while True: print(temp.measure()) time.sleep(1)
# set the LoRaWAN data rate s.setsockopt(socket.SOL_LORA, socket.SO_DR, 4) # make the socket blocking # (waits for the data to be sent and for the 2 receive windows to expire) # s.setblocking(True) # make the socket non-blocking # (because if there's no data received it will block forever...) s.setblocking(False) time.sleep(1) # DS18B20 cavo dati connesso al pin P10, ow = OneWire(Pin('P10')) # G17 dell'Expansion Board sens = DS18X20(ow) # Inizializza sensore while True: sens.start_conversion( ) # Bisogna attendere almeno un secondo dopo questa istruzione time.sleep(1) data = sens.read_temp_async() # Leggo la temperatura try: # Errore su format di un valore None se non è collegato un sensore print("{} --> {:.1f}".format( round(data, 2), data)) # Arrotonda a due cifre decimali massime dopo la virgola net = (str("{:.1f}".format(data))).encode( 'utf-8') # Codifica la stringa da inviare in bytes s.send(net) # Finalmente invia pycom.heartbeat(True) time.sleep(1)
from machine import Pin from onewire import DS18X20 from onewire import OneWire import time # init Sigfox for RCZ1 (Europe) sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1) # create a Sigfox socket s = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW) # make the socket blocking s.setblocking(True) # configure it as uplink only s.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False) openW = OneWire(Pin("P23", mode=Pin.OUT)) temp = DS18X20(openW) while True: temp.start_conversion() tempSend = temp.read_temp_async() time.sleep(1) sendMessage = bytes((temp.read_temp_async() & 0xff, ((temp.read_temp_async() >> 8) & 0xff))) print(temp.read_temp_async()) s.send(sendMessage) time.sleep(2) # d=DS18X20(Pin('P23', mode=Pin.OUT)) # result=(d.read_temps())
# En forenkling av funksjonen ADC, en funksjon som tar analog input på en pin (mellom 3.3 og # 0 volt) og gjør det om til en # 12-bit verdi som øker proporsjonalt med spenningen. Gir verdien 0 for 0 volt og verdien 4095 for 3.3 volt. adc = ADC() # Bruker ADC på hver av de analoge pinnene som skal brukes til sensorene for lys, salinitet (konduktivitet) og PH-verdi. # Parameteren "pin" bestemmer hvilken pin som leses og parameteren "attn" bestemmer det øvre nivået (1-3) av spenning som kan leses i angitt pin. lysPin = adc.channel(attn=3, pin='P17') saltPin = adc.channel(attn=3, pin='P16') phPin = adc.channel(attn=3, pin='P15') # Bruker OneWire (importert fra biblioteket) for å lese digital verdi på den digitalpinen P23. ow = OneWire(Pin('P23')) # DS18X20 er en klasse i OneWire (DS18X20 er navnet på termometeret som er brukt i sensornoden). # Definerer så owTemp som en instanse av DS18X20 lest med verdien funnet i den digitale pinen. owTemp = DS18X20(ow) # En loop hvor all kode blir kjørt i intervaller. Intervallene er bestemt i time.sleep() metoden mot slutten av loopen. while True: # SALT / KONDUKTIVITET # Definerer saltLes som den leste verdien på saltPin, definert tidligere med bruk av ADC. # Variabelen salt, som representerer konduktiviteten i vannet, blir så regnet ut som prosent av spenningstap. # 0V (saltLes = 4095) i spenningstap gir konduktivitet på 100 og 3.3V i spenningstap (saltLes = 0) gir konduktivitet på 0. saltLes = saltPin.value() salt = 100 - (saltLes / 4095.0) * 100 # TURBIDITET # Definerer lysLes som den leste verdien på lysPin, definert tidligere med bruk av ADC. # Variabelen turb, som representerer turbiditeten i vannet (hvor mye lys som slipper gjennom vannet), blir så # regnet ut som prosent av spenningstap. # 0V (lysLes = 4095) i spenningstap gir turbiditet på 100 og 3.3V i spenningstap (lysLes = 0) gir turbiditet på 0.
import pycom from network import LoRa import time import binascii import socket from machine import Pin from onewire import DS18X20 from onewire import OneWire print("TTN Example v0") # DS18B20 data line connected to pin P10 ow = OneWire(Pin('G16')) d = DS18X20(ow) pycom.heartbeat(False) pycom.rgbled(0x00ff00) lora = LoRa(mode=LoRa.LORAWAN) app_eui = binascii.unhexlify('70B3D57EF0003CDF') app_key = binascii.unhexlify('221D0C89D6393F66C01EFE5588E99D65') lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) # wait until the module has joined the network while not lora.has_joined(): time.sleep(2.5) print('Not joined yet... Have you registered device ID? Mine is:') print(binascii.hexlify(lora.mac()).upper().decode('utf-8'))
msg = "Error initialising network: {}: {}".format(type(e), e) exit_error(msg, traceback=e) # ,-----------------------------------------------------------, # | These are the PySense specific sensors. | # '-----------------------------------------------------------' board = Pysense() light_sensor = LTR329ALS01(board) barometric_pressure = MPL3115A2(board, mode=PRESSURE) # barometric_altitude = MPL3115A2(board, mode=ALTITUDE) humidity_sensor = SI7006A20(board) # ,-----------------------------------------------------------, # | This is the DS18B20 liquid temperature sensor. | # '-----------------------------------------------------------' lts_pin = OneWire(Pin("P10")) # Set up input GPIO. liquid_temp_sensor = DS18X20(lts_pin) # ,-----------------------------------------------------------, # | Now let's see which sensors are attached and working. | # '-----------------------------------------------------------' # DS18B20 lts_ready = lts_pin.reset() logger.info("Liquid temperature sensor present = %s.", lts_ready) # MPL3115A2 barometer_ready = barometric_pressure._read_status() logger.info("Barometer sensor present = %s.", barometer_ready) # ,-----------------------------------------------------------, # | There are no available functions to test the presence of | # | the light or humidity sensors so these are just assumed |
def do_measurements(): if my_config_dict['node_version'] == 0x02: try: addr68_ch0 = MCP342x(i2c_irt, 0x68, channel=0, resolution=18, gain=8, scale_factor=1000.0) addr68_ch1 = MCP342x(i2c_irt, 0x68, channel=1, resolution=18, gain=8, scale_factor=1000.0) addr68_ch2 = MCP342x(i2c_irt, 0x68, channel=2, resolution=18, gain=8, scale_factor=1000.0) addr68_ch3 = MCP342x(i2c_irt, 0x68, channel=3, resolution=18, gain=8, scale_factor=1000.0) float_values[0] = addr68_ch0.convert_and_read() float_values[1] = addr68_ch1.convert_and_read() float_values[2] = addr68_ch2.convert_and_read() float_values[3] = addr68_ch3.convert_and_read() float_values[4] = float_values[0] * 5.0 float_values[5] = 0.0 except Exception as ex: rgb_blink(100, 0x13f2ab) print("Couldn't find ADC") print(ex) float_values[0] = -1.0 float_values[1] = -1.0 float_values[2] = -1.0 float_values[3] = -1.0 float_values[4] = -1.0 float_values[5] = 0.0 else: print("Waking up I2C sensors...") ### IRT Sensor irt = None try: irt = MLX90614(i2c_irt, 90) print("Waking IRT...OK") time.sleep(1) float_values[0] = irt.read_ambient_temp() float_values[1] = irt.read_object_temp() rgb_blink(100, 0xa013f2) except Exception as error: red_blink(1000) irt = None print("Couldn't find IRT") float_values[0] = -1.0 float_values[1] = -1.0 wdt.feed() ### Air sensor if my_config_dict["air_sensor"] == NONE: print("Ignoring air sensor...") float_values[2] = 0.0 float_values[3] = 0.0 float_values[4] = 0.0 elif my_config_dict["air_sensor"] == BME280: bme = None try: bme = BME280(address=BME280_I2CADDR, i2c=i2c_air) print("Waking BME280...OK") time.sleep(1) float_values[2] = bme.read_temperature() / 100.0 float_values[3] = bme.read_humidity() / 1024.0 float_values[4] = bme.read_pressure() / 256.0 / 100.0 rgb_blink(100, 0x0000ff) except Exception as error: red_blink(1000) print("Couldn't find BME") float_values[2] = -1.0 float_values[3] = -1.0 float_values[4] = -1.0 elif my_config_dict["air_sensor"] == SHT3x: sht30 = None try: sht30 = SHT30(i2c_air) print("Waking SHT3x...OK") time.sleep(1) float_values[2], float_values[3] = sht30.measure() float_values[4] = 0.0 green_blink(100) except Exception as error: red_blink(1000) print("Couldn't find SHT30") float_values[2] = -1.0 float_values[3] = -1.0 float_values[4] = 0.0 elif my_config_dict["air_sensor"] == SHT3x_single: sht30 = None try: sht30 = SHT30(i2c_air, i2c_address=0x44) print("Waking SHT3x...OK") time.sleep(1) float_values[2], float_values[3] = sht30.measure() float_values[4] = 0.0 green_blink(100) except Exception as error: rgb_blink(100, 0x13f2ab) print("Couldn't find SHT30") float_values[2] = -1.0 float_values[3] = -1.0 float_values[4] = 0.0 else: print("Sensor not supported") wdt.feed() ### Soil sensor temp = None try: ow_devices = ow.scan() if len(ow_devices) > 0: print("Waking OWD...OK") if len(ow_devices) > 0: ow_id = ubinascii.hexlify(ow_devices[0]).decode('ascii') else: ow_id = "None" print("OW ID: {}".format(ow_id)) temp = DS18X20(ow) time.sleep(1) temp.start_convertion() time.sleep(1) float_values[5] = temp.read_temp_async() if float_values[5] is None: float_values[5] = -100 rgb_blink(100, 0xf2b313) else: print("Soil temp not found") red_blink(1000) float_values[5] = -1.0 #time.sleep(1) except Exception as error: print(error) red_blink(1000) print("Couldn't find OWD") float_values[5] = -100.0 wdt.feed() # Battery sensing adc = machine.ADC(0) batt = adc.channel(pin='P16', attn=3) float_values[6] = (batt.value() / 4096.0) * 354.8 / 31.6 print("Battery: {}V".format(float_values[6]))
# Australia = LoRa.AU915 # Europe = LoRa.EU868 # United States = LoRa.US915 pycom.rgbled(0xA00000) lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) uart = UART(1, baudrate=9600, bits=8, pins=('P20', 'P21'), timeout_chars=50) # create an OTAA authentication parameters app_eui = ubinascii.unhexlify('70B3D57ED00114D6') app_key = ubinascii.unhexlify('ED9425C459DD25020CA5A24AEE1539FC') uart2.write('C,0\r') uart2.readall() uart2.write('*OK,0\r') uart2.readall() ow = OneWire(Pin('P12')) temp_sens = DS18X20(ow) temp_raw = temp_sens.read_temp_async() time.sleep(1) temp_sens.start_conversion() # join a network using OTAA (Over the Air Activation) lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) print('try to join... (9600)') pycom.rgbled(0x0000A0) # wait until the module has joined the network while not lora.has_joined(): time.sleep(2.5) print('Not yet joined...') # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) print("joined")
def __init__(self, queue, period, pin=DEAFULT_TEMPERATURE_PIN): self._ow = OneWire(pin) self._temp = DS18X20(self._ow) self.value = 0 PeriodicSensor.__init__(self, queue, period)
def __init__(self, owpin='P10'): #DS18B20 data line connected to pin P10 ow = OneWire(Pin(owpin)) nastemp = DS18X20(ow)
from machine import Pin import time, ubinascii from onewire import OneWire, DS18X20 ow = OneWire(Pin('P10')) # create a OneWire bus on P10 temp = DS18X20(ow) # create a DS18X20 sensor object on the OneWire bus temp.start_conversion() # send a command to the sensor to let it start the # temperature measurement time.sleep(1) # wait for one second (needed to ensure conversion is completed) TempCelsius = temp.read_temp_async() # read the temperature from the sensor print("Temperature (degrees C) = %7.1f" % TempCelsius) # print result