def run(args): from gpiozero import MCP3008 from brego.database import SensorDB from brego.sensors import (find_onewire_devices, MultiOneWireSensor, DS18B20Sensor, ADCManager) database = SensorDB.request_instance() server = SensorServer(database, broadcast_socket=args.broadcast_socket, report_status=args.report_status) # one-wire temperature sensors onewire_devices = [DS18B20Sensor(fn) for fn in find_onewire_devices()] onewire_sensors = MultiOneWireSensor(onewire_devices) for device in onewire_devices: database.add_device(device.device_name, 'temperature') server.register_reporter(onewire_sensors.reporter) # ADCs adc_devices = [MCP3008(channel=0), MCP3008(channel=7)] adc_names = ['Potentiometer', 'Tachometer'] for name in adc_names: database.add_device(name, 'ADC') adc_manager = ADCManager(adc_devices, adc_names) adc_manager.start() server.register_reporter(adc_manager.reporter) curio.run(server.run, with_monitor=True)
def record(): soil_sensor = MCP3008(0) light_sensor = MCP3008(1) air_sensor = adafruit_dht.DHT11(board.D18) try: air_temp_c = air_sensor.temperature air_humidity = air_sensor.humidity soil_humidity = round(soil_sensor.value, 2) light = round(abs(light_sensor.value - 1), 2) click.echo('-' * 20) click.echo(datetime.now().isoformat()) click.echo('Writing measures...') db.session.add(Measure(label='air-temp-c', value=air_temp_c)) db.session.add(Measure(label='air-humidity', value=air_humidity)) db.session.add(Measure(label='soil-humidity', value=soil_humidity)) db.session.add(Measure(label='light', value=light)) db.session.commit() click.echo('Wrote 4 measures.') except RuntimeError as err: click.echo(err)
def defineElectronics(): global led global flashlight global buzzer global temperatureSensorInput global humiditySensorInput global gasSensorInput global pi global INA global INB global INC global IND pi = pigpio.pi() led = LED(22) flashlight = LED(23) buzzer = Buzzer(24) temperatureSensorInput = MCP3008(channel=0) humiditySensorInput = MCP3008(channel=1) gasSensorInput = MCP3008(channel=2) INA = 13 INB = 19 INC = 26 IND = 12 for i in [INA, INB, INC, IND]: pi.set_mode(i, pigpio.OUTPUT)
def publisher_thread(): # Set up the LDR and potentiometer ldr = MCP3008(channel=LDR_CHANNEL) pot = MCP3008(channel=POT_CHANNEL) # TODO Check Normalization of values while (True): # lightSensor publishing (from the LDR) global lightSensor currentLDR = ldr.value * SCALE if (abs(lightSensor - currentLDR) >= THRESH): # Since difference is outside threshold, publish lightSensor = currentLDR client.publish(topic='lightSensor', payload=lightSensor, qos=2, retain=True) # threshold publishing (from the potentiometer) global threshold currentPOT = pot.value if (abs(threshold - currentPOT) >= THRESH): # Since difference is outside threshold, publish threshold = currentPOT client.publish(topic='threshold', payload=threshold, qos=2, retain=True) # Only query every 100 ms sleep(0.10)
def __init__(self, server_connection, tree_id, moisture_channel=0, water_channel=1, water_pump_gpio=26, sensor_switch_gpio=7, dht_gpio=17): super().__init__(server_connection) self.moisture = MCP3008(channel=moisture_channel) self.water_level = MCP3008(channel=water_channel) self.water_pump = OutputDevice(pin=water_pump_gpio, active_high=False) self.dht_sensor = DHT22(dht_gpio) self.current_moisture_level = 0 self.sensor_switch = OutputDevice(pin=sensor_switch_gpio, active_high=True) self.server_connection = server_connection self.current_temperature = 0 self.current_humidity = 0 self.tree_id = tree_id self.hx = HX711(5, 6) self.hx.set_reading_format("MSB", "MSB") referenceUnit = 261 * 1.34 * 0.9 * 1.05 self.hx.set_reference_unit(referenceUnit) self.hx.set_offset(-5600) self.current_weight = 0 self.watering_mode = False
def start(self): n = 0 while not rospy.is_shutdown(): while (True): adc = MCP3008(channel=0) # Toggle A forwards / back voltage1 = 3.3 * adc.value print("Toggle A forwards / back: ", voltage1) adc = MCP3008(channel=1) # Toggle A left / right voltage2 = 3.3 * adc.value print("Toggle A left / right: ", voltage2) adc = MCP3008(channel=2) # Toggle B forwards / back voltage3 = 3.3 * adc.value print("Toggle B forwards / back: ", voltage3) adc = MCP3008(channel=3) # Toggle B left / right voltage4 = 3.3 * adc.value print("Toggle B left / right: ", voltage4) print("") n = n + 1 self.pubt.publish(self.throttControl) self.pubu.publish(self.steerControl) self.throttControl = ((voltage3 * 50) - 60) * 2 self.steerControl = ((voltage4 * 50) - 60) * 5 + 500 print(n, " throttControl", self.throttControl) print(n, " steerControl", self.steerControl) print("") self.loop_rate.sleep()
def __init__(self, w): #firebase cred = credentials.Certificate( "/home/pi/raspberryfirebase-firebase-adminsdk-y4f0x-ce1ddd9e4b.json" ) firebase_admin.initialize_app( cred, {'databaseURL': 'https://raspberryfirebase.firebaseio.com/'}) self.mcp3008Ref = db.reference('raspberrypi/MCP3008') #設定視窗基本功能 w.title('溫度和光線的感應') w.option_add("*font", ("verdana", 18, "bold")) w.option_add("*background", "#068587") w.option_add("*foreground", "#ffffff") #建立sensor self.lightness = MCP3008(channel=7) self.temperature = MCP3008(channel=6) self.m = MCP3008(channel=0) #設定介面變數 self.temperatureText = StringVar() self.lightnessText = StringVar() self.mvariable = StringVar() #設定介面 mainFrame = Frame(w, borderwidth=2, relief=GROOVE, padx=100, pady=10) Label(mainFrame, text="室內溫度:").grid(row=0, column=0, sticky=E, padx=5, pady=20) Label(mainFrame, text="室內光線:").grid(row=1, column=0, sticky=E, padx=5, pady=20) Label(mainFrame, text="可變電阻:").grid(row=2, column=0, sticky=E, padx=5, pady=20) Label(mainFrame, textvariable=self.temperatureText).grid(row=0, column=1, sticky=E, padx=5, pady=20) Label(mainFrame, textvariable=self.lightnessText).grid(row=1, column=1, sticky=E, padx=5, pady=20) Label(mainFrame, textvariable=self.mvariable).grid(row=2, column=1, sticky=E, padx=5, pady=20) mainFrame.pack(padx=10, pady=10) self.autoUpdate()
def _update_adc(self): """Main function for ADC update thread, will grab new temp values every two seconds.""" T0 = MCP3008(0) T1 = MCP3008(1) T2 = MCP3008(2) counter = 0 temp_a0 = 0 temp_a1 = 0 temp_a2 = 0 temp_b0 = 0 temp_b1 = 0 temp_b2 = 0 temp_c0 = 0 temp_c1 = 0 temp_c2 = 0 while True: with self._lock: # Read the temperature from the ADC and deliver weighted average V0 = T0.value * 3.3 V1 = T1.value * 3.3 V2 = T2.value * 3.3 if counter == 0: temp_a0 = (10.617 * math.pow(V0, 4)) - (65.957 * math.pow( V0, 3)) + (155.58 * math.pow(V0, 2)) - (197.45 * V0) + 146.08 temp_a1 = (10.617 * math.pow(V1, 4)) - (65.957 * math.pow( V1, 3)) + (155.58 * math.pow(V1, 2)) - (197.45 * V1) + 146.08 temp_a2 = (10.617 * math.pow(V2, 4)) - (65.957 * math.pow( V2, 3)) + (155.58 * math.pow(V2, 2)) - (197.45 * V2) + 146.08 if counter == 1: temp_b0 = (10.617 * math.pow(V0, 4)) - (65.957 * math.pow( V0, 3)) + (155.58 * math.pow(V0, 2)) - (197.45 * V0) + 146.08 temp_b1 = (10.617 * math.pow(V1, 4)) - (65.957 * math.pow( V1, 3)) + (155.58 * math.pow(V1, 2)) - (197.45 * V1) + 146.08 temp_b2 = (10.617 * math.pow(V2, 4)) - (65.957 * math.pow( V2, 3)) + (155.58 * math.pow(V2, 2)) - (197.45 * V2) + 146.08 if counter == 2: temp_c0 = (10.617 * math.pow(V0, 4)) - (65.957 * math.pow( V0, 3)) + (155.58 * math.pow(V0, 2)) - (197.45 * V0) + 146.08 temp_c1 = (10.617 * math.pow(V1, 4)) - (65.957 * math.pow( V1, 3)) + (155.58 * math.pow(V1, 2)) - (197.45 * V1) + 146.08 temp_c2 = (10.617 * math.pow(V2, 4)) - (65.957 * math.pow( V2, 3)) + (155.58 * math.pow(V2, 2)) - (197.45 * V2) + 146.08 counter = counter + 1 if counter == 3: counter = 0 self._temperature_0 = (temp_a0 + temp_b0 + temp_c0) / 3 self._temperature_1 = (temp_a1 + temp_b1 + temp_c1) / 3 self._temperature_2 = (temp_a2 + temp_b2 + temp_c2) / 3 # Wait 2 seconds then repeat. time.sleep(2.0)
def __init__(self): self.a = MCP3008( channel=0 ) # objects that access the flex sensor values through the adc self.b = MCP3008(channel=1) self.dtimes = deque('', 15) # deque, which is like a list but for queueing self.dratios = deque('', 15) self.dfav = deque('', 15)
def __init__(self, level='lvl0'): #instantiating all the motors and sensors on the bot self.robot = Robot(left=MOTOR_L, right=MOTOR_R) self.sonic = DistanceSensor(echo=SONIC_ECHO, trigger=SONIC_TRIG) self.ir_l = MCP3008(IR_L) self.ir_r = MCP3008(IR_R) self.button = MCP3008(BTN) self.bz = TonalBuzzer(BZ) self.led = RGBLED(R, G, B) #creating custom variables self.speed = self.get_speed(level)
def run(): while (1): adc0 = MCP3008(channel=0, device=0) adc1 = MCP3008(channel=1, device=0) adc2 = MCP3008(channel=2, device=0) adc3 = MCP3008(channel=3, device=0) sensor0 = int(adc0.value * 1023) sensor1 = int(adc1.value * 1023) sensor2 = int(adc2.value * 1023) sensor3 = int(adc3.value * 1023) def percent(x): return ((1023 - x) / 603) * 100 if (percent(sensor0) >= 0 and percent(sensor0) < 40): print("Pump is running", int(percent(sensor0))) pump0.on() else: print("Pump is closed", int(percent(sensor0))) pump0.off() if (percent(sensor1) >= 0 and percent(sensor1) < 40): print("Pump is running", int(percent(sensor1))) pump1.on() else: print("Pump is closed", int(percent(sensor1))) pump1.off() if (percent(sensor2) >= 0 and percent(sensor2) < 40): print("Pump is running", int(percent(sensor2))) pump2.on() else: print("Pump is closed", int(percent(sensor2))) pump2.off() if (percent(sensor3) >= 0 and percent(sensor3) < 40): print("Pump is running", int(percent(sensor3))) pump3.on() else: print("Pump is closed", int(percent(sensor3))) pump3.off() time.sleep(1)
def __init__(self, adc_channel=0, config_file=None): self.adc_channel = adc_channel self.adc = MCP3008(self.adc_channel, device=0) config_file_path = os.path.join(os.path.dirname(__file__), config_file) with open(config_file_path, "r") as f: self.config = json.load(f) vin = self.config["vin"] vdivider = self.config["vdivider"] for dir in self.config["directions"]: dir["vout"] = self.calculate_vout(vdivider, dir["ohms"], vin) dir["adc"] = (1 * (dir["vout"] / vin)) sorted_by_adc = sorted(self.config["directions"], key=lambda x: x["adc"]) for index, dir in enumerate(sorted_by_adc): if index > 0: below = sorted_by_adc[index - 1] delta = (dir["adc"] - below["adc"]) / 2.0 dir["adcmin"] = dir["adc"] - delta else: dir["adcmin"] = 0 if index < (len(sorted_by_adc) - 1): above = sorted_by_adc[index + 1] delta = (above["adc"] - dir["adc"]) / 2.0 dir["adcmax"] = dir["adc"] + delta else: dir["adcmax"] = 1 # old vlaue #self.adc.value - 1
def temp(): temp1 = MCP3008(0) T = 15 * temp1.raw_value - 2048 whole = T / 100 temp = T / 100 sleep(0.5) return (temp)
def main(): # SHT31D Temperature and Humidity sensor i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_sht31d.SHT31D(i2c) # TMP36 Temperature Sensor backup_sensor = MCP3008(channel=TEMPERATURE_SENSOR_CHANNEL) # SHT31D Measurements sht31d_temperature_c = sensor.temperature sht31d_temperature_f = round((sht31d_temperature_c * (9 / 5)) + 32, 1) sht31d_temperature_f_adj = round(sht31d_temperature_f + calibrations['SHT31D']['temperature'], 1) sht31d_humidity = int(sensor.relative_humidity) sht31d_humidity_adj = int(sht31d_humidity + calibrations['SHT31D']['humidity']) # TMP36 Measurements temperature_voltage = backup_sensor.voltage tmp36_temperature_c = get_temperature_c(temperature_voltage, round_digits=1) tmp36_temperature_f = round((tmp36_temperature_c * (9 / 5)) + 32, 1) tmp36_temperature_f_adj = round(tmp36_temperature_f + calibrations['TMP36']['temperature'], 1) # Save Measurements print('logging {}F, {}% Humidity '.format(sht31d_temperature_f_adj, sht31d_humidity_adj)) environment_models.AirMeasurement.objects.create( sht31d_temperature_c=sht31d_temperature_c, sht31d_temperature_f=sht31d_temperature_f, sht31d_temperature_f_adj=sht31d_temperature_f_adj, sht31d_humidity=sht31d_humidity, sht31d_humidity_adj=sht31d_humidity_adj, tmp36_temperature_c=tmp36_temperature_c, tmp36_temperature_f=tmp36_temperature_f, tmp36_temperature_f_adj=tmp36_temperature_f_adj )
def gpioInit(self): self.vrChannel = MCP3008(channel=7) self.distanceSensor = DistanceSensor(23, 24) self.servo = AngularServo(18, min_angle=-45, max_angle=45) self.servo.angle = 0.0 Timer(1, self.gpioAutoUpdate).start()
def readInfo(): #humidity, temperature = Adafruit_DHT.read_retry(sensor, pinNum)#read_retry - retry getting temperatures for 15 times read = MCP3008(canal) humidadesolo = (1 - read.value) * 100 print('Umidade do Solo {0}%',humidadesolo) return saveToDatabase(humidadesolo)
def get_adc_value(): for pos in range(0, 4): if pos not in adcs: adcs[pos] = MCP3008(pos) vals = np.array([adcs[pos].value for pos in range(0, 4)]) vals[vals > .985] = None return vals
def irrigate_by_moisture_new_thread(irrigate_level_bars): global is_irrigate_by_moisture global state is_irrigate_by_moisture = True while is_irrigate_by_moisture == True: # after calling irrigate_by_moisture this mode is on all the time unless someone canceled it if MCP3008.readadc(5) < int( irrigate_level_bars["low_level"] ): # if moisture level too low start irrigate while MCP3008.readadc(5) < int(irrigate_level_bars["high_level"]): if state == False: start_irrigate() time.sleep(30) # else just make sure the watering is off and wait 8 hours for next check stop_irrigate() time.sleep(60 * 60 * 8)
def render_POST_separate(self, request): pot = MCP3008(0) val = pot.value ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') self.payload = "Trigering new Temp Measurement which is : %s at timestamp %s" % ((val * 10000), st) #self.payload = request.payload return self
def __init__(self): self.conn = Database('assignment', DEVICE_ID) self.pin_dht11 = None self.pin_ldr = None self.load_config() self.sensor_dht11 = Adafruit_DHT.DHT11 self.sensor_ldr = MCP3008(channel=self.pin_ldr) self.stop = False
def __init__(self, name="BasicResource", coap_server=None): super(BasicResource, self).__init__(name, coap_server, visible=True, observable=True, allow_children=True) pot = MCP3008(0) val = pot.value self.payload = "Hello From RPi3!!, Temp value is : %s" % (val) self.resource_type = "rt1" self.content_type = "text/plain" self.interface_type = "if1"
def readMoisture(): pot = MCP3008(0) #specify the MCP3008 port moistureA = [pot.value] #read the first value for h in range(numOfReads): moistureA = moistureA + [ pot.value ] #add the reading value to the list of values moisture = s.mean(moistureA) #calculate the mean of the list return moisture #return the value
def __init__(self,window): print("LM35App的實體被建立") self.vrText = StringVar() mainFrame = Frame(window, borderwidth=2, relief=GROOVE) Label(mainFrame, text="溫度:").pack(side=LEFT) Entry(mainFrame, width=20, state=DISABLED, textvariable=self.vrText).pack(side=LEFT) mainFrame.pack(padx=30, pady=30) self.lm35 = MCP3008(channel=6) self.checkTemperature()
def readADCValue(): # Assign Pins for software spi clk = 18 miso = 23 mosi = 24 cs = 12 adc = MCP3008(channel = 0, clock_pin = clk, mosi_pin = mosi, miso_pin = miso, select_pin = cs) GPIO.cleanup() return adc.voltage
def GetTemp(B, R0, R1, V0, T0): Vpre = MCP3008(channel=0) V = V0 * Vpre.value #print("V : ", V) R = (V0 / V - 1) * R1 #print("R : ", R) T = (1) / ((1 / B) * (log(R / R0)) + (1) / (T0 + 273)) - 273 #print("1/B : ", (1/B), "log(R/R0)", log(R/R0)) #print("temperature : ", T) return T
def get_sensor_value(channel, value_list, length): input_value = MCP3008(channel=channel) present_value = V0 * input_value.value for i in range(length - 1): value_list[i] = value_list[i + 1] value_list[length - 1] = present_value return value_list
def setUpClass(cls): clock_pin = 21 mosi_pin = 20 miso_pin = 19 select_pin = 7 cls.dev = MCP3008(channel=0, mosi_pin=mosi_pin, miso_pin=miso_pin, select_pin=select_pin, clock_pin=clock_pin)
def __init__(self, datapin, device=0): self.__datapin = datapin self.__device = 0 if device is None else device self.__value = None logger.debug( 'Initializing sensor type \'%s\' with Analog address %s,%s' % (self.__class__.__name__, self.__datapin, self.__device)) self.__sensor = MCP3008(channel=int(self.__datapin), device=int(self.__device))
def __init__(self, name="Advanced"): super(AdvancedResource, self).__init__(name) #self.payload = "Advanced resource" pot = MCP3008(0) val = pot.value global currenttemp currenttemp = random.randint(10,30) self.payload = "Hello From RPi3!!, Temp value is : %s" % (currenttemp) self.resource_type = "rt1" self.content_type = "text/plain" self.interface_type = "if1"
def debug_start(message): start_time = time.time() sample_length = 10 timeout = 2 d_out = DigitalInputDevice(pin=LOAD_CELL_DOUT, pull_up=True) sck = DigitalOutputDevice(pin=LOAD_CELL_SCK) adc = MCP3008(channel=0) sck.off() counter = 1 emit_data = [] while time.time() - start_time < sample_length: # Retrieve data from MCP3008 fsr_data = adc.value # Retrieve data from HX711 loop_start = time.time() while not d_out.is_active: if time.time() - loop_start > timeout: break data = 0 for j in range(24): data = data << 1 sck.on() sck.off() if d_out.value == 0: data = data + 1 #loadcell_data = {'hex': hex(data), 'num': convert_twos_complement(data)} #emit('debug data', {'data': {'fsr': fsr_data, 'loadcell': loadcell_data}}) #counter = counter + 1 #if counter % 8 == 0: # emit('debug data', {'data': emit_data}) # emit_data = [] #else: # emit_data.append({'fsr': fsr_data, 'loadcell': convert_twos_complement(data)}) emit_data.append({ 'fsr': fsr_data, 'loadcell': convert_twos_complement(data) }) # 25th pulse sck.on() sck.off() # 128 pulses for i in range(LOAD_CELL_GAIN): sck.on() sck.off() emit('debug data', {'data': emit_data}) time.sleep(1) emit('debug finish')