def exec_req(url, param_dict): """Function to execute the request This function executes the parsed request. Arguments: url: list, separated by /. So if a user comes to http://example.domain.com/read/1 this argument is ["read","1"] param_dict: dictionary, of the parameters that are sent to the server. """ print("URL:", url, param_dict) if len(url) == 0: with open("identity.json", "r") as f: identity = json.load(f) return """<html> <head> <title>NodeMCU</title> </head> <body> <b>Location: {}</b> </body> </html> """.format(identity["location"]) elif url[0] == 'write': pin_id = int(url[1]) try: pin = machine.Pin(pin_id, machine.Pin.OUT) except: return { "status": "Error, pin value {} is inaccessible".format(pin_id) } else: if url[2] == 'on': pin.on() return {"status": "Pin {} is on".format(str(pin_id))} elif url[2] == 'off': pin.off() return {"status": "Pin {} is off".format(str(pin_id))} else: return { "status": "{} is not a valid input for pin {} status".format( url[3], pin_id) } elif url[0] == 'read': try: pin_id = int(url[1]) if "pull" in param_dict.keys(): pull = param_dict["pull"] else: pull = None if pull == "up": pull = machine.Pin.PULL_UP elif pull == "down": pull = machine.Pin.PULL_DOWN pin = machine.Pin(pin_id, machine.Pin.IN, pull) #todo return {"value": pin.value()} except: return {"Status": "Error"} elif url[0] == "measure": pin_id = int(url[1]) measurement_type = param_dict.get("type") if measurement_type is None: return { "status": "measurement type is required in the query arguments!" } elif measurement_type.lower() == "dht11": # /measure/PIN_ID?type="dht11" try: import dht d = dht.DHT11(machine.Pin(pin_id)) d.measure() return { "temperature": d.temperature(), "humidity": d.humidity() } except: return {"Status": "Error"} elif measurement_type.lower() == "ds18b20": # /measure/PIN_ID?type=ds18b20 import onewire, ds18x20 temperatures = [] try: dat = machine.Pin(pin_id) ds = ds18x20.DS18X20(onewire.OneWire(dat)) roms = ds.scan() ds.convert_temp() time.sleep_ms(750) temperatures = [] for rom in roms: temperature = ds.read_temp(rom) address = hex(int.from_bytes(rom, "little")) temperatures.append({ "id": address, "temperature": round(temperature, 4) }) except Exception as e: return { "status": "{} error while attempting to measure ds18b20 temperature!" .format(repr(e)) } return {"temperatures": [temperatures], "unit": "celsius"} else: return { "status": "{} measurement not implemented.".format( measurement_type.lower()) } elif url[0] == "whoami": with open("identity.json", "r") as f: identity = json.load(f) return identity else: return {"Status": "No Action"}
# Function to read DHT def readDht(): dht22.measure() return dht22.temperature(), dht22.humidity() # DS18B20 import onewire, ds18x20 # Define which pin the 1-wire device will be connected ==> pin 2 (D4) dat = Pin(2) # Create the onewire object ds = ds18x20.DS18X20(onewire.OneWire(dat)) # scan for devices on the bus sensors = ds.scan() # function to read DS18B20 def readDs(): ds.convert_temp() time.sleep_ms(750) return round(ds.read_temp(sensors[0]), 1) # LDR from machine import ADC
def main_loop(): init_done = False ntptime.host = "fr.pool.ntp.org" ntptime.settime() try: with open("config.json", "rt") as cfg_file: config.update( ujson.loads( cfg_file.read() ) ) except OSError: pass try: #create the pwm channels pwm0 = PWM(Pin(12), duty=0) pwm0.freq(150) pwm1 = PWM(Pin(13), duty=0) if config["esp32"]: pwm2 = PWM(Pin(2), duty=0) pwm3 = PWM(Pin(4), duty=0) else: pwm2 = PWM(Pin(15), duty=0) #create dht if it is enabled in config if config["dht"]: env_nodes = [env_sensors.EnvironmentDht(Pin(0))] elif config["ds1820"]: import onewire, ds18x20 ds_driver = ds18x20.DS18X20(onewire.OneWire(Pin(0))) env_nodes = [env_sensors.EnvironmentDS1820(ds_driver, rom, num) for num, rom in enumerate(ds_driver.scan())] elif config["bme280"]: if config["esp32"]: i2c = I2C(0, scl=Pin(22), sda=Pin(21)) else: i2c = I2C(scl=Pin(16), sda=Pin(0)) devices = i2c.scan() bme_addrs = [addr for addr in devices if addr == 0x76 or addr == 0x77] env_nodes = [env_sensors.EnvironmentBME280(i2c, addr, num) for num, addr in enumerate(bme_addrs)] else: env_nodes = [] adcs = [] #check in config for analog period analog_period = config['analog_period'] analog2_period = config['analog2_period'] if config["esp32"]: if analog_period != 0: adcs.append(Analog("analog1", "Analog sensor 1", 34, analog_period, config["analog_bits"], config["analog_attn"])) if analog2_period != 0: adcs.append(Analog("analog2", "Analog sensor 2", 35, analog2_period, config["analog2_bits"], config["analog2_attn"])) else: if analog_period != 0: adcs.append(Analog("analog1", "Analog sensor 1", 0, analog_period)) #create the buttons and pwm channels if config["esp32"]: dimmers = [ Dimmer("A", pwm0, 32), Dimmer("B", pwm1, 33), Dimmer("C", pwm2, 25), Dimmer("D", pwm3, 26) ] else: dimmers = [ Dimmer("A", pwm0, 4), Dimmer("B", pwm1, 5), Dimmer("C", pwm2, 14) ] color_manager = ColorManager(dimmers) nodes = [ homie.Node("color", "Color leds (on ABC)", color_manager.props), homie.Node("dimmer", "Dimmers channels", dimmers)] if env_nodes: nodes.extend(env_nodes) if adcs: nodes.append(homie.Node("analog_sens", "Analog Sensors", adcs)) init_done = True #~ robust.MQTTClient.DEBUG = True #create the mqtt client using config parameters mqtt = robust.MQTTClient(config["client_id"], config["broker"], keepalive=4*homie.KEEP_ALIVE) device = homie.HomieDevice( mqtt, ubinascii.hexlify(network.WLAN().config('mac')), nodes, "Multicontroler{}".format(config["location"]), homie_broadcast_cb) time_tmp = 0 while True: device.main() time.sleep(.050) cur_time = int(time.time()) color_manager.do_cycle() #this simple test enables to get in this loop only once per second if time_tmp != cur_time: #~ print("In the loop") time_tmp = cur_time for env_node in env_nodes: env_node.periodic(cur_time) #analog publication period is user defined for adc in adcs: adc.periodic(cur_time) #buttons checks for dimmer in dimmers: dimmer.periodic() except KeyboardInterrupt as excp: print ("Interrupted") sys.print_exception(excp) except Exception as excp: sys.print_exception(excp) with open("exceptions.txt", "at") as excp_file: excp_file.write(str(RTC().datetime())) excp_file.write(" GMT\n") sys.print_exception(excp, excp_file) excp_file.write("\n") #if debug mode is not enabled in config automatic reset in 10 seconds if config['debug'] == False and init_done == True: mqtt.disconnect() for count in range (10,0, -1): print("Reboot in {} seconds\r".format(count)) time.sleep(1) reset() finally: mqtt.disconnect()
W1_PIN_0 = 4 W1_PIN_1 = 0 DHT_PIN_0 = 2 RELAY_HEAT1_PIN = 12 RELAY_HEAT2_PIN = 13 RELAY_HUMID_PIN = 14 DISPLAY_CLK_PIN = 5 DISPLAY_DIO_PIN = 4 # w1_0 = onewire.OneWire(machine.Pin(W1_PIN_0)) w1_1 = onewire.OneWire(machine.Pin(W1_PIN_1)) # ds_0 = ds18x20.DS18X20(w1_0) ds_1 = ds18x20.DS18X20(w1_1) dht_0 = dht.DHT22(machine.Pin(DHT_PIN_0)) sensors_ds = [ds_1] sensors_dht = [dht_0] heat1 = machine.Pin(RELAY_HEAT1_PIN, machine.Pin.OUT, value=1) heat2 = machine.Pin(RELAY_HEAT2_PIN, machine.Pin.OUT, value=1) humidifier = machine.Pin(RELAY_HUMID_PIN, machine.Pin.OUT, value=1) relays = { 'heat1': heat1, 'heat2': heat2, 'humidifier': humidifier, }
print("Dealing with %s" % line) if not line or line == b'\r\n': break response = json.dumps(data) cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n') cl.send(response) cl.close() relay_pin = machine.Pin(5, machine.Pin.OUT) relay_off() ds_pin = machine.Pin(2) time.sleep_ms(750) ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin)) time.sleep_ms(750) roms = ds_sensor.scan() time.sleep_ms(750) print(roms) rom_sensor = roms[0]
# for stm32 import machine from machine import Pin, UART import json import time, onewire, ds18x20 from machine import Pin from pyb import Timer import pyb uart2 = UART(2, 9600) alert_pin = Pin("PA7", Pin.OUT, Pin.PULL_DOWN) ow = onewire.OneWire(Pin("PB5")) #创建onewire总线 ds = ds18x20.DS18X20(ow) ds.scan() roms = ds.scan() #扫描总线上的设备 ds.convert_temp() #获取采样温度 time.sleep_ms(750) #获取最新温度 23.4375 temperature = ds.read_temp(roms[-1]) print(temperature) #PD7 water data_value = [0, 0, 0] #温度,流速,状态 data_down = [0, 0] #流速 #中断计数+定时器清零赋值 water_pin = Pin("PD7", Pin.IN) water_count = 0
def init_onewire(): ds = ds18x20.DS18X20(onewire.OneWire(temp_sensor_pin)) roms = ds.scan() for rom in roms: print("Found: {}".format(rom)) return ds, roms
import time import machine import onewire, ds18x20 dsPin = machine.Pin(12) ds = ds18x20.DS18X20(onewire.OneWire(dsPin)) roms = ds.scan() #[bytearray(b'(&\xad\x07\xd6\x01<R')] #print(roms) while True: print('temperatures:', end=' ') ds.convert_temp() for rom in roms: print(ds.read_temp(rom), end='\n') time.sleep(2)
作者:01Studio 说明:通过编程采集温度数据,并在OLED上显示。。 ''' #引用相关模块 from machine import Pin, I2C, Timer from ssd1306 import SSD1306_I2C import onewire, ds18x20 #初始化相关模块 i2c = I2C(sda=Pin(13), scl=Pin(14)) oled = SSD1306_I2C(128, 64, i2c, addr=0x3c) #初始化DS18B20 ow = onewire.OneWire(Pin(4)) #使能单总线 ds = ds18x20.DS18X20(ow) #传感器是DS18B20 rom = ds.scan() #扫描单总线上的传感器地址,支持多个传感器同时连接 def temp_get(tim): ds.convert_temp() temp = ds.read_temp(rom[0]) #温度显示,rom[0]为第1个DS18B20 #OLED数据显示 oled.fill(0) #清屏背景黑色 oled.text('MicroPython', 0, 0) oled.text('Temp test:', 0, 20) oled.text(str('%.2f' % temp) + ' C', 0, 40) #显示temp,保留2位小数 oled.show()
import definitions as df import functions as fn esp.osdebug(None) esp.sleep_type(0) #esp.sleep_type(esp.SLEEP_NONE) #Ορισμός timer timer1 = machine.Timer(-1) timer2 = machine.Timer(-1) #Πληροφορίες για το μέγεθος της μνήμης Flash print('[Program file system total :', os.statvfs("/")[0] * os.statvfs("/")[2], 'bytes]') print('[Program file system free :', os.statvfs("/")[0] * os.statvfs("/")[3], 'bytes]') #Δημιουρία αντικειμένων OneWire ds1 = ds18x20.DS18X20(onewire.OneWire(df.OW1_DATA)) #Εξωτερικό θερμόμετρο ds2 = ds18x20.DS18X20(onewire.OneWire(df.OW2_DATA)) #Εσωτερικό θερμόμετρο #Εμφάνισε τα Id των θερμομέτρων roms_ext = ds1.scan() hexstr = " ".join("%02x" % b for b in roms_ext[0]) print('[Found ow device in bus 1 with ID:', hexstr, ']') roms_int = ds2.scan() hexstr = " ".join("%02x" % b for b in roms_int[0]) print('[Found ow device in bus 2 with ID:', hexstr, ']') bme = bme280.BME280(i2c=fn.i2c) print('[Found I2C bus devices with IDs:', fn.i2c.scan(), ']') #Προετοιασία αντικειμένου για διάβασμα από ADC adc = machine.ADC(0)
import onewire, ds18x20 gc.collect() from machine import I2C, Pin gc.collect() from esp8266_i2c_lcd import I2cLcd gc.collect() import ds1307 gc.collect() import menu gc.enable() #setup sw = Pin(2, Pin.IN, Pin.PULL_UP) pb2 = Pin(0, Pin.IN, Pin.PULL_UP) relay = Pin(12, Pin.OUT) ds_sensor = ds18x20.DS18X20(onewire.OneWire(Pin(3))) roms = ds_sensor.scan() i2c = I2C(scl=Pin(5), sda=Pin(4)) lcd = I2cLcd(i2c, 0x27, 2, 16) ds = ds1307.DS1307(i2c) lcd.backlight_on() lcd.clear() lcd.putstr(" Programmable\n Mini Fridge") time.sleep_ms(3000) lcd.clear() gc.collect() #Main Loop while True: clock = ds.datetime() gc.collect()
def __init__(self, dsPinNum=0): self.dsPin = machine.Pin(dsPinNum) self.dsSensor = ds18x20.DS18X20(onewire.OneWire(self.dsPin)) self.roms = self.dsSensor.scan() print('Found DS devices: ', self.roms)
def __init___(self,pin): self.ow = onewire.OneWire(pin) self.ds = ds18x20.DS18X20(self.ow)
#Hardware Platform: FireBeetle-ESP32 #Result: measure enviromental temperature. #Hardware Connection: this test need to connect a 'DS18B20' digital temperature sensor in IO25. #The info below shows that ds18b20Demo is available for the current version. # IO0 IO2 IO4 IO5 IO9 IO10 IO12~19 # IO21 IO22 IO23 IO25 IO26 IO27 from machine import Pin import onewire import ds18x20 import time ow = onewire.OneWire(Pin(25)) #Init wire ds=ds18x20.DS18X20(ow) #create ds18x20 object while True: roms=ds.scan() #scan ds18x20 ds.convert_temp() #convert temperature for rom in roms: print(ds.read_temp(rom)) #display time.sleep(1)
# A demo of reading temperature sensors DS18x20 on a 1-Wire bus. # Since the internal pull up is activated on the pin used for the # 1-Wire bus, no external pull up resistor is needed. from machine import Pin import time, ds18x20, onewire # The pin to OW_PIN = 12 # Set up a 1-Wire bus on pin (with internal pull up resistor activated) one_wire_bus = onewire.OneWire(Pin(OW_PIN)) # An object representing all sensors on the bus sensors = ds18x20.DS18X20(one_wire_bus) # A list of unique 64 bit serial codes for the connectede sensors sensor_ids = sensors.scan() # Print status print("Found {} devices on 1-Wire bus on pin {}.".format( len(sensor_ids), OW_PIN)) # Tell sensors to measure temperature sensors.convert_temp() # Wait while sensors measure temperature. Takes 750ms (At 12bit resolution) according to datasheet. time.sleep_ms(750) # Read the stored temperature off of the sensors for id in range(len(sensor_ids)):
dht22 = dht.DHT22(machine.Pin(dhtPin)) dhtTempUnit = 'C' dhtRHUnit = 'RH' dhtTempId = '01001' dhtHumId = '01002' # for sht31 set up i2c i2c = machine.I2C(sda=machine.Pin(sdaPin), scl=machine.Pin(sclPin)) shtBoard = sht31.SHT31(i2c) shtTempUnit = 'F' shtRHUnit = 'RH' shtTempId = '01003' shtHumId = '01004' # For DS18B20 set up onewire ds = ds18x20.DS18X20(onewire.OneWire(machine.Pin(owPin))) roms = ds.scan() dsTempUnit = 'C' dsTempId = '01005' # set up socket wlan = network.WLAN(network.STA_IF) hostip = wlan.ifconfig()[0] port = 10000 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address = (hostip, port) sock.bind(server_address) # Main loop #
def get_sensor(): ds_pin = machine.Pin('PD11') ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin)) roms = ds_sensor.scan() return roms, ds_sensor
global tmr_mqtt_last if time.time() - tmr_mqtt_last > tmr_mqtt: print('Sending data via mqtt...') client.publish('house/kitchen/temp', str('{:.2f}'.format(BME_T))) client.publish('house/kitchen/humid', str('{:.1f}'.format(BME_H))) client.publish('house/outside/temp', str('{:.2f}'.format(DS_T))) tmr_mqtt_last = time.time() else: print('MQTT timer pass') print('BME280 init') bme = bme280.BME280(i2c=i2c, address=addrBME280) print('DS18X20 init') ds = ds18x20.DS18X20(onewire.OneWire(oneWire_pin)) print('OLED init') display = ssd1306.SSD1306_I2C(128, 32, i2c) display.contrast(0) tmr_bme_last = time.time() - tmr_bme tmr_ds_last = time.time() - tmr_ds tmr_display_off_last = time.time() - tmr_display_off tmr_mqtt_last = time.time() - tmr_mqtt while True: check_motion() read_bme(bme) read_ds(ds) mqtt_send()
def __init__(self, Dobby, DS18B20_Config): # Referance to dobby self.Dobby = Dobby # Var to hold configured Peripherals self.Peripherals = {} # Log Event self.Dobby.Log(1, "DS18B20", "Initializing") # Before we can init the sensor we need to create the pins # we also need to create a timer that can trigger a read and then pass the values to the configured sensors # Check if we got a pin config if DS18B20_Config.get('Pins', None) == None: # Raise a Module_Error so we disable this module since we dont have any configured pins raise self.Dobby.Module_Error("'Pins' not in config, unable to initialize") # Holds read timers used to trigger reading and store of values self.Read_Timers = {} # Holds the ds18b20 sensor object self.Sensor_Pins = {} self.Unconfigured = [] # Now we need to creat a ds18b20 instance for each pin for Pin_Name in DS18B20_Config['Pins']: # Lets reserve the pin try: self.Dobby.Pin_Monitor.Reserve(Pin_Name, "DS18B20-" + Pin_Name) except self.Dobby.Pin_Monitor.Error as e: if str(e).endswith("DS18B20-" + Pin_Name) == True: self.Dobby.Log(0, "DS18B20", "Pin already owned by a DS18B20") else: # Pin in use unable to configure DS18B20 self.Dobby.Log(2, "DS18B20/" + Pin_Name, "Pin in use - Unable to initialize") # Continue since we were unable to resetve the pin continue # Create the dict that will hopd the ds18b20 object and error count self.Sensor_Pins[Pin_Name] = {} # Now we need to create a ds18b20 object so we can do a scan and read from the sensors # Will store it in Sensor_Pins under pin name and then Sensor self.Sensor_Pins[Pin_Name]['Sensor'] = ds18x20.DS18X20( onewire.OneWire( machine.Pin( self.Dobby.Pin_Monitor.To_GPIO_Pin( Pin_Name ) ) ) ) # Now will create an error counter for that pin self.Sensor_Pins[Pin_Name]['Error'] = 0 # Creat the Read Timer, to refresh values from all the sensors on a spisific pin # so we dont have to wait when we request a value or have to publish # Check if the dobby.timer module is loaded self.Dobby.Timer_Init() # Get rate to default to 1.5s if present # if rate is less then 1.5 then we need to set the rate to 1.5s # anything else will generate None value from the sensor Rate = self.Dobby.Sys_Modules['Timer'].Time_To_ms( DS18B20_Config['Pins'].get( 'Rate', '1.5s' ), Min_Value='1.5s' ) # Log event self.Dobby.Log(0, "DS18B20/" + Pin_Name + "/ReadTimer", "Interval set to: " + str(Rate) + " ms") # Add a timer # 1 = Referance Name # 2 = Timeout # 3 = Callback # Disable logging since we trigger this timer a lot try: self.Read_Timers[Pin_Name] = self.Dobby.Sys_Modules['Timer'].Add( "DS18B20-" + Pin_Name + "-Read", Rate, self.Read_Sensor, Argument=Pin_Name, Logging=False ) # Unable to create the timer, remove the entire pin and all sensors attached to it from the config except self.Dobby.Sys_Modules['Timer'].Timer_Error as e: # delete both ds18b20 sensor object, the read timer was not stored so no reason to relete it del self.Sensor_Pins[Pin_Name] # continue since this pin failed continue # Start the timer self.Read_Timers[Pin_Name].Start() # After configuring the sensors we now need to do a scan and list all connected ids # Check if we got at least one pin if self.Sensor_Pins != {}: # Var to hold a string containing pin number and connected devices Return_String = "" for Pin_Name in self.Sensor_Pins: # Do a scan Scan = self.Sensor_Pins[Pin_Name]['Sensor'].scan() # Holds the id's we found during the init scan # during sensor setup will add the matching callback as the value # The key will be the sensors id as a string # that way we can loop over ids when reading and use: # [id_byte] = id in byte array to read spicific sensor # [Callback] = self.Store_Temperature from the matching sensor self.ids = {} # Add id to Return_String Return_String = Return_String + "'" + Pin_Name + "': " # Add each id to matching pin for Entry in Scan: # Convert the id to string id_str = str(hex(int.from_bytes(Entry, 'little'))) # Creat a key in self.ids self.ids[id_str] = {} # Save the id as bytearray so we can use it in self.Pass_Temperature self.ids[id_str]['id_byte'] = Entry # Add id to Return_String Return_String = Return_String + " '" + id_str + "'" # list what ids we found so we can spot of we got a new id we have not configured self.Dobby.Log(0, "DS18B20", "Connected devices:" + Return_String) # Unable to configre any pins # so fail module load else: # Raise error - Error logging done by Main raise self.Dobby.Module_Error("Unable to configure any of the pins in 'Pins'") # Delete Pins from DS18B20_Config so we dont load it as a sensor del DS18B20_Config['Pins'] # Loop over Peripherals in config for Name, Config in DS18B20_Config.items(): # Make sure Name is a string Name = str(Name) # Add the DS18B20 to the DS18B20 dict self.Peripherals[Name] = self.DS18B20(self.Dobby, self, Name, Config) # Check if the DS18B20 is ok if self.Peripherals[Name].OK is False: # Issue with DS18B20 detected disabling it self.Dobby.Log(2, "DS18B20/" + Name, "Issue during setup, disabling the DS18B20") else: # Subscribe to DS18B20 topic if at least one DS18B20 was ok self.Dobby.MQTT_Subscribe(self.Dobby.Peripherals_Topic("DS18B20", End="+")) # Log event self.Dobby.Log(0, "DS18B20", "Initialization complete")
def get_values(): data_dict = {} # vbat adc = ADC(Pin(38)) # create ADC object on ADC pin adc.atten( ADC.ATTN_6DB ) # set 6dB input attenuation (voltage range roughly 0.0v - 2.0 v) adc.width( ADC.WIDTH_12BIT) # set 12 bit return values (returned range 0-4095) v_raw = adc.read() data_dict["vbat"] = v_raw # calculate vbat #chargestate pin_ok = Pin(17, Pin.IN) # GPIO 17 - in - OK(green) pin_ch = Pin(16, Pin.IN) # GPIO 16 - in - CHRG(red) if pin_ch.value(): data_dict["chrg"] = 1 else: data_dict["chrg"] = 0 # system temperature t_raw = esp32.raw_temperature( ) # read the internal temperature of the MCU, in Farenheit data_dict["tsys"] = t_raw # soil humi pin_en = Pin(0, Pin.OUT) # GPIO 37 - out - VCC pin_en.on() # set pin to "on" (high) level adc = ADC(Pin(36)) # GPIO 36 - in - ADC adc.atten( ADC.ATTN_6DB ) # set 6dB input attenuation (voltage range roughly 0.0v - 2.0 v) adc.width( ADC.WIDTH_12BIT) # set 12 bit return values (returned range 0-4095) soil_raw = adc.read() time.sleep_ms(200) # wait for adc and sensor soil_raw = adc.read() soil_raw = adc.read() pin_en.off() # set pin to "off" (low) level data_dict["soil"] = soil_raw # calculate soil value # onwire ow = onewire.OneWire(Pin(12)) # create a OneWire bus on GPIO12 ds = ds18x20.DS18X20(ow) rom_t5 = "" rom_t20 = "" # onewire 5 cm ds.convert_temp() time.sleep_ms(750) t5_raw = ds.read_temp(rom_t5) data_dict["t5"] = t5_raw # onewire 5 cm ds.convert_temp() time.sleep_ms(750) t20_raw = ds.read_temp(rom_t20) data_dict["t20"] = t20_raw print(data_dict) for k, v in data_dict: print(k, v) return data_dict
# check if the device woke from a deep sleep reset_cause = machine.reset_cause() if reset_cause == machine.DEEPSLEEP_RESET: print('woke from a deep sleep') elif reset_cause == machine.SOFT_RESET: print('woke from a soft reset') sys.exit() # for reprogramming elif reset_cause == machine.PWRON_RESET: print('woke frome power on event') sys.exit() ## Init State do_connect() sleep_timer = machine.RTC() gy521 = GY521(I2C_SCL_PIN, I2C_SDA_PIN, I2C_FREQ, accel_range=ACCEL_RANGE) ds = ds18x20.DS18X20(onewire.OneWire(machine.Pin(DS18X20_PIN))) battery_sensor = machine.ADC(ADC_PIN) WW = WortWorm(gy521, ds, battery_sensor, UBI_DEVICE_LABEL, sleep_timer) ## Measure State temp = WW.getTemperature() print('Temp: %f' % temp) tilt = WW.getTiltAngle() print('Tilt: %f' % tilt) volt = WW.getBatteryVoltage() print('Battery Voltage: %f' % volt) #sensor_values = WW.measure_all() ## Transmit State WW.send2Ubidots(UBI_TEMP_LABEL, temp)
def __init__(self, pin_id): ds_pin = machine.Pin(pin_id) self.ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin)) self.roms = self.ds_sensor.scan() print('Found DS devices: ', self.roms)
mac='000AE4C99858', subnetmask='255.255.255.0', my_IPv4='192.168.1.101') camera = LS_Y201.LS_Y201() uos.dupterm(None, 1) try: sd = sdcard.SDCard(machine.SPI(1), machine.Pin(15)) uos.mount(sd, '/sd') except Exception: print("no sd card") rtc = machine.RTC() i2c = machine.I2C(scl=machine.Pin(0), sda=machine.Pin(16), freq=100000) BH = bh1750.BH1750(i2c) ds_sensor = ds18x20.DS18X20(onewire.OneWire(machine.Pin(4))) last_message = 0 last_net_check = 0 last_time_sync = 0 last_photo = 0 last_message_check = 0 last_door_check = 0 door_check_interval = 60 message_check_interval = 1 photo_interval = 60 time_sync_interval = 3600 net_check_interval = 2 message_interval = 15 counter = 0 old_data = "0"
from machine import Pin import time, ds18x20, onewire s = onewire.OneWire(Pin(12)) ds = ds18x20.DS18X20(s) roms = ds.scan() while 1: ds.convert_temp() time.sleep(1) for rom in roms: a = ds.read_temp(rom) print(str(a) + ' P')
break except: pass else: time.sleep_ms(10) pass machine.deepsleep() rtc=machine.RTC() temp_power = machine.Pin(32,machine.Pin.OUT) temp_power.value(1) rled=machine.Pin(18,machine.Pin.OUT) bled=machine.Pin(5,machine.Pin.OUT) bled.value(1) gled=machine.Pin(17,machine.Pin.OUT) temp_data = machine.Pin(12) ds = ds18x20.DS18X20(onewire.OneWire(temp_data)) roms = ds.scan() print(roms) temperature = 0 wlan() while True: if sta_if.isconnected()==True: try: mac=ubinascii.hexlify(network.WLAN().config('mac'),':').decode() mac=mac.replace(':','-') ip=sta_if.ifconfig() print(ip) gled.value(1) bled.value(0) ds.convert_temp() time.sleep_ms(750)
def __init__(self, pin): ifc = onewire.OneWire(machine.Pin(pin)) self._ds18x20 = ds18x20.DS18X20(ifc) self._sensors = self._ds18x20.scan() print('Found DS devices: ', self._sensors)
def connect_onewire(pin_temp): ds = ds18x20.DS18X20(onewire.OneWire(pin_temp)) sens = ds.scan() x = sens[0] return ds, x
# Assignment 3.1: DS18B20 Digital Temp Probe for Pi Pico # Docu: https://components101.com/sensors/ds18b20-temperature-sensor # Temperature Range: -55°C to +125°C; Accuracy: ±0.5°C # Black Cable: GND # Yellow Cable: Connect to a I2C SDA port # Red Cable: 3.3/5V import time import machine import onewire, ds18x20 temp_probe = ds18x20.DS18X20(onewire.OneWire(machine.Pin(0))) roms = temp_probe.scan() #scan for device bus if roms[0]: # if found, print out the address for the first probe print('Device found, address: ', roms) else: exit while True: print('Temp:', end=' ') temp_probe.convert_temp() # wait at least 750ms before read value print(temp_probe.read_temp(roms[0]), end='\n') time.sleep(2)