class LedImpl(Led): def __init__(self, name, pin: Output, reference, description): super().__init__(name, pin, reference, description) self._gpio = GPIO(self.pin.channel, self.pin.type_pin) self._pmw = RPIGPIO.PWM(self.pin.channel, 100) self._pmw.start(self.bright) def light(self, status): self.shutdown = not status self._gpio.write(status) if status: print("Allumage d'une led sur le port {} ".format(self.pin.channel)) else: print("Extinction d'une led sur le port {} ".format(self.pin.channel)) def fade_in(self, time_in): delay = time_in / 100 for x in range(100): self._pmw.ChangeDutyCycle(x) time.sleep(delay) def fade_out(self, time_out): delay = time_out / 100 for x in range(100, 0, -1): self._pmw.ChangeDutyCycle(x) time.sleep(delay) def __del__(self): self._pmw.stop() RPIGPIO.cleanup()
def __init__(self, clk, dio, brightness=BRIGHT_DEFAULT): self.brightness = brightness self.clk = GPIO(clk, direction=GPIO.OUT) self.dio = GPIO(dio, direction=GPIO.OUT) self.data = [0] * 4 self.show_colon = False
def cleanAndExit(): print("Cleaning...") if not EMULATE_HX711: GPIO.cleanup() print("Bye!") sys.exit()
class OneLedTypedGpio(OneLed): def __init__(self, pin, high_enable=True): super(OneLedTypedGpio, self).__init__(pin) self.__high_en = high_enable self.__gpio = GPIO(pin, GPIO.OUT) def _lighton(self, b=True): v = self.__high_en == bool(b) and bool(self._bright) # print("write {} {}".format(self._bright, int(v))) self.__gpio.write(int(v))
def __init__(self, led=1): self.num_led = led self.r_all = [0] * self.num_led self.g_all = [0] * self.num_led self.b_all = [0] * self.num_led self.clk_pin = 5 self.data_pin = 6 self.tv_nsec = 100 self.GPIOCLK = GPIO(self.clk_pin, GPIO.OUT) self.GPIODATA = GPIO(self.data_pin, GPIO.OUT)
def __init__(self, dht_type, pin=12, bus_num=1): if dht_type != self.DHT_TYPE['DHT11'] and dht_type != self.DHT_TYPE[ 'DHT22'] and dht_type != self.DHT_TYPE['DHT10']: print('ERROR: Please use 11|22|10 as dht type.') exit(1) self.dht_type = dht_type if dht_type == self.DHT_TYPE['DHT10']: self.bus = Bus(bus_num) self.addr = self.DEFAULT_ADDR self._dht10_init() else: self.pin = GPIO(pin, GPIO.OUT) self._last_temp = 0.0 self._last_humi = 0.0
class SensorBocina: #Constructor de la clase Bocina #Pin: Numero del pin que ocupa la bocina en el sombrero def __init__(self, pin): self.bocina = GPIO(pin, GPIO.OUT) #Funcion para encender la bocina def encender(self): self.bocina.write(1) #Funcion para apagar la bocina def apagar(self): self.bocina.write(0)
class SensorBoton: #Constructor de la clase led #Pin: Numero del pin que ocupa el led en el sombrero def __init__(self, pin): self.boton = GPIO(pin, GPIO.IN) def estaPresionado(self): if (self.boton.read() == 1): return True
def __init__(self, pin, low_pressed = True): super(ButtonTypedGpio, self).__init__(pin) self.__low_press = low_pressed self.__state = self.KEY_STATE_IDLE self.__duration = 0.0 self.__distance = _KEY_INTERVAL self.__thrd_exit = False self.__thrd = None self.__gpio = GPIO(pin, GPIO.IN) self.__gpio.on_event = self.__gpio_event if self.__thrd is None or not self.__thrd.is_alive(): self.__thrd = threading.Thread( \ target = ButtonTypedGpio.__thrd_chk_evt, \ args = (self,)) self.__thrd.setDaemon(True) self.__thrd.start()
class SensorLed: #Constructor de la clase led #Pin: Numero del pin que ocupa el led en el sombrero def __init__(self, pin): self.luz = GPIO(pin, GPIO.OUT) #Funcion para encender el led def encender(self): self.luz.write(1) #Funcion para apagar el led def apagar(self): self.luz.write(0) #Funcion para comprobar el estado de led def encendido(self): if self.luz.read() == 1: return True else: return False
class SensorPresion: #Constructor de la clase presion #Pin: Numero del pin que ocupa el sensor de presion en el sombrero def __init__(self, pin): self.presion = GPIO(pin, GPIO.IN) #Funcion para comprobar si hay algo encima o no def presionado(self): if self.presion.read() == 1: return True else: return False
class GroveOpticalRotaryEncoder(object): def __init__(self, pin1, pin2 = None): pin2 = pin1 + 1 if pin2 is None else pin2 self.__gpio = GPIO(pin1, GPIO.IN) self.__gpio2 = GPIO(pin2, GPIO.IN) self.__gpio.on_event = self.__gpio_event self._pos = 0 # called by GPIO library def __gpio_event(self, pin, value): v1 = self.__gpio.read() if not v1: return v2 = self.__gpio2.read() self._pos += 1 if v2 else -1 def position(self, pos = None): "set or get the position counter" " pos --- the position counter to be set" " return current position counter" if not pos is None: self._pos = pos return self._pos
def main(): v = 0 pre_v = 0 # print disable sys.stdout = open(os.devnull, 'w') from grove.helper import SlotHelper sh = SlotHelper(SlotHelper.GPIO) pin = sh.argv2pin() gpio = GPIO(pin, GPIO.IN) v = pre_v = gpio.read() # print enable sys.stdout = sys.__stdout__ while True: v = gpio.read() if v != pre_v: print(v) pre_v = v time.sleep(0.1)
class GroveOpticalRotaryEncoder(object): ''' Grove optical Rotary Encoder(TCUT1600X01) class Args: pin(int): the number of gpio/slot your grove device connected. ''' def __init__(self, pin1, pin2=None): pin2 = pin1 + 1 if pin2 is None else pin2 self.__gpio = GPIO(pin1, GPIO.IN) self.__gpio2 = GPIO(pin2, GPIO.IN) self.__gpio.on_event = self.__gpio_event self._pos = 0 # called by GPIO library def __gpio_event(self, pin, value): v1 = self.__gpio.read() if not v1: return v2 = self.__gpio2.read() self._pos += 1 if v2 else -1 def position(self, pos=None): ''' set or get the position counter Args: pos(int): optinal, the position counter to be set. if not specified, only get the current counter Returns: (int): current position counter ''' if not pos is None: self._pos = pos return self._pos
class SensorNivel: #Constructor de la clase Nivel #Pin: Numero del pin que ocupa el sensor de nivel en el sombrero def __init__(self, pin): self.nivel = GPIO(pin, GPIO.IN) #Funcion para comprobar el nivel del liquido desinfectante def comprobarNivel(self): if self.nivel.read() == 1: #Devuelve True si queda liquido return True else: #Devuelve false si no queda liquido return False
# HOW TO CALCULATE THE REFFERENCE UNIT # To set the reference unit to 1. Put 1kg on your sensor or anything you have and know exactly how much it weights. # In this case, 92 is 1 gram because, with 1 as a reference unit I got numbers near 0 without any weight # and I got numbers around 184000 when I added 2kg. So, according to the rule of thirds: # If 2000 grams is 184000 then 1000 grams is 184000 / 2000 = 92. #hx.set_reference_unit(113) hx.set_reference_unit(92) hx.reset() hx.tare() print("Tare done! Add weight now...") led = GPIO(26, GPIO.OUT) # to use both channels, you'll need to tare them both #hx.tare_A() #hx.tare_B() while True: try: # These three lines are usefull to debug wether to use MSB or LSB in the reading formats # for the first parameter of "hx.set_reading_format("LSB", "MSB")". # Comment the two lines "val = hx.get_weight(5)" and "print val" and uncomment these three lines to see what it prints. # np_arr8_string = hx.get_np_arr8_string() # binary_string = hx.get_binary_string() # print binary_string + " " + np_arr8_string
class GroveUltrasonicRanger(object): def __init__(self, pin): self.dio = GPIO(pin) def _get_distance(self): self.dio.dir(GPIO.OUT) self.dio.write(0) usleep(2) self.dio.write(1) usleep(10) self.dio.write(0) self.dio.dir(GPIO.IN) t0 = time.time() count = 0 while count < _TIMEOUT1: if self.dio.read(): break count += 1 if count >= _TIMEOUT1: return None t1 = time.time() count = 0 while count < _TIMEOUT2: if not self.dio.read(): break count += 1 if count >= _TIMEOUT2: return None t2 = time.time() dt = int((t1 - t0) * 1000000) if dt > 530: return None distance = ((t2 - t1) * 1000000 / 29 / 2) # cm return distance def get_distance(self): while True: dist = self._get_distance() if dist: return dist
class Ultrasonic(object): def __init__(self, pin): #Digital Port self.dio = GPIO(pin) self._TIMEOUT1 = 1000 self._TIMEOUT2 = 10000 def usleep(self, x): sleep(x / 1000000.0) def _get_distance(self): self.dio.dir(GPIO.OUT) self.dio.write(0) self.usleep(2) self.dio.write(1) self.usleep(10) self.dio.write(0) self.dio.dir(GPIO.IN) t0 = time() count = 0 while count < self._TIMEOUT1: if self.dio.read(): break count += 1 if count >= self._TIMEOUT1: return None t1 = time() count = 0 while count < self._TIMEOUT2: if not self.dio.read(): break count += 1 if count >= self._TIMEOUT2: return None t2 = time() dt = int((t1 - t0) * 1000000) if dt > 530: return None distance = ((t2 - t1) * 1000000 / 29 / 2) # cm return distance def read(self): while True: dist = self._get_distance() if dist: return dist
def __init__(self, pin): #Digital Port self.dio = GPIO(pin) self._TIMEOUT1 = 1000 self._TIMEOUT2 = 10000
import time from grove.gpio import GPIO led = GPIO(22, GPIO.OUT) led2 = GPIO(24, GPIO.OUT) led3 = GPIO(26, GPIO.OUT) button = GPIO(5, GPIO.IN) button2 = GPIO(16, GPIO.IN) button3 = GPIO(18, GPIO.IN) count = 0 count2 = 0 count3 = 0 p = 0 def potencia(i): switcher = {1: 1, 2: 2, 3: 3, 4: 5, 5: 8, 6: 13, 7: 21, 8: 34} return switcher.get(i, 10) while True: if button.read(): count = count + 1 print(count) p = potencia(count) led.write(p) else: led.write(0) count = 0 time.sleep(0.1)
import time from grove.gpio import GPIO led = GPIO(12, GPIO.OUT) print("connect an LED to pin #12\nPress CTRL + c to quit") try: while True: led.write(not led.read()) time.sleep(0.5) except KeyboardInterrupt: print("Done!") led.write(False) quit()
#if len(sys.argv) == 3 and sys.argv[1] in sensor_args: # sensor = sensor_args[sys.argv[1]] # pin = sys.argv[2] #else: # print('Usage: sudo ./Adafruit_DHT.py [11|22|2302] <GPIO pin number>') # print('Example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO pin #4') # sys.exit(1) sensor = 11 pin = 24 pinBuzzer = 12 sensorDistancia = DistanceSensor(trigger=18, echo=24) # Try to grab a sensor reading. Use the read_retry method which will retry up # to 15 times to get a sensor reading (waiting 2 seconds between each retry). led1 = GPIO(26, GPIO.OUT) led2 = GPIO(16, GPIO.OUT) mraa_pin = getGpioLookup("GPIO%02d" % pinBuzzer) buzzer = upmBuzzer.Buzzer(mraa_pin) chords = [ upmBuzzer.BUZZER_DO, upmBuzzer.BUZZER_DO, upmBuzzer.BUZZER_MI, upmBuzzer.BUZZER_DO, upmBuzzer.BUZZER_DO, upmBuzzer.BUZZER_MI, upmBuzzer.BUZZER_DO ] #Humidity = AdafruitDHT.humidity #Temperature = AdafruitDHT.temperature cont = 0 while True: humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
def __init__(self, pin): self.luz = GPIO(pin, GPIO.OUT)
import time from grove.gpio import GPIO motor = GPIO(24, GPIO.OUT) def encenderM(): print("Motor encendido") motor.write(1) def apagarM(): print("Motor apagado") motor.write(0)
def __init__(self, pin): self.distancia = GPIO(pin)
class DHT(object): DHT_TYPE = {'DHT11': '11', 'DHT22': '22', 'DHT10': '10'} DEFAULT_ADDR = 0x38 RESET_REG_ADDR = 0xba MAX_CNT = 320 PULSES_CNT = 41 def __init__(self, dht_type, pin=12, bus_num=1): if dht_type != self.DHT_TYPE['DHT11'] and dht_type != self.DHT_TYPE[ 'DHT22'] and dht_type != self.DHT_TYPE['DHT10']: print('ERROR: Please use 11|22|10 as dht type.') exit(1) self.dht_type = dht_type if dht_type == self.DHT_TYPE['DHT10']: self.bus = Bus(bus_num) self.addr = self.DEFAULT_ADDR self._dht10_init() else: self.pin = GPIO(pin, GPIO.OUT) self._last_temp = 0.0 self._last_humi = 0.0 @property def dht_type(self): return self._dht_type @dht_type.setter def dht_type(self, type): self._dht_type = type ######################## dht10 ############################ def _dht10_start_mess(self): reg_set = [0x33, 0x00] self.bus.write_i2c_block_data(self.addr, 0xac, reg_set) def _dht10_reset(self): self.bus.write_byte(self.addr, self.RESET_REG_ADDR) def _dht10_set_system_cfg(self): reg_set = [0x08, 0x00] self.bus.write_i2c_block_data(self.addr, 0xe1, reg_set) def _dht10_read_status(self): return self.bus.read_byte_data(self.addr, 0) def _dht10_init(self): time.sleep(.5) self._dht10_reset() # delay is needed after reset time.sleep(.3) self._dht10_set_system_cfg() status = self._dht10_read_status() # we must check the calibrate flag, bit[3] : 1 for calibrated ok,0 for Not calibrated. while status & 0x08 != 0x08: print("try calibrated again!n\n") self._dht10_reset() time.sleep(.5) self.bus.dth10_set_system_cfg() status = self._dht10_read_status() time.sleep(.5) ######################################################### def _read(self): if self.dht_type == self.DHT_TYPE['DHT10']: t = 0 h = 0 self._dht10_start_mess() time.sleep(.075) # we must check the device busy flag, bit[7] : 1 for busy ,0 for idle. while (self._dht10_read_status() & 0x80) != 0: time.sleep(.5) print("wait for device not busy") from smbus2 import SMBus, i2c_msg, SMBusWrapper with SMBusWrapper(1) as bus: msg = i2c_msg.read(self.addr, 6) data = bus.i2c_rdwr(msg) data = list(msg) t = (t | data[1]) << 8 t = (t | data[2]) << 8 t = (t | data[3]) >> 4 h = (h | data[3]) << 8 h = (h | data[4]) << 8 h = (h | data[5]) & 0xfffff t = t * 100.0 / 1024 / 1024 h = h * 200.0 / 1024 / 1024 - 50 return t, h # Send Falling signal to trigger sensor output data # Wait for 20ms to collect 42 bytes data else: self.pin.dir(GPIO.OUT) self.pin.write(1) time.sleep(.2) self.pin.write(0) time.sleep(.018) self.pin.dir(GPIO.IN) # a short delay needed for i in range(10): pass # pullup by host 20-40 us count = 0 while self.pin.read(): count += 1 if count > self.MAX_CNT: # print("pullup by host 20-40us failed") return None, "pullup by host 20-40us failed" pulse_cnt = [0] * (2 * self.PULSES_CNT) fix_crc = False for i in range(0, self.PULSES_CNT * 2, 2): while not self.pin.read(): pulse_cnt[i] += 1 if pulse_cnt[i] > self.MAX_CNT: # print("pulldown by DHT timeout %d" % i) return None, "pulldown by DHT timeout %d" % i while self.pin.read(): pulse_cnt[i + 1] += 1 if pulse_cnt[i + 1] > self.MAX_CNT: # print("pullup by DHT timeout %d" % (i + 1)) if i == (self.PULSES_CNT - 1) * 2: # fix_crc = True # break pass return None, "pullup by DHT timeout %d" % i total_cnt = 0 for i in range(2, 2 * self.PULSES_CNT, 2): total_cnt += pulse_cnt[i] # Low level ( 50 us) average counter average_cnt = total_cnt / (self.PULSES_CNT - 1) # print("low level average loop = %d" % average_cnt) data = '' for i in range(3, 2 * self.PULSES_CNT, 2): if pulse_cnt[i] > average_cnt: data += '1' else: data += '0' data0 = int(data[0:8], 2) data1 = int(data[8:16], 2) data2 = int(data[16:24], 2) data3 = int(data[24:32], 2) data4 = int(data[32:40], 2) if fix_crc and data4 != ((data0 + data1 + data2 + data3) & 0xFF): data4 = data4 ^ 0x01 data = data[0:self.PULSES_CNT - 2] + ('1' if data4 & 0x01 else '0') if data4 == ((data0 + data1 + data2 + data3) & 0xFF): if self._dht_type == self.DHT_TYPE['DHT11']: humi = int(data0) temp = int(data2) elif self._dht_type == self.DHT_TYPE['DHT22']: humi = float(int(data[0:16], 2) * 0.1) temp = float( int(data[17:32], 2) * 0.2 * (0.5 - int(data[16], 2))) else: # print("checksum error!") return None, "checksum error!" return humi, temp def read(self, retries=15): for i in range(retries): humi, temp = self._read() if not humi is None: break if humi is None: return self._last_humi, self._last_temp self._last_humi, self._last_temp = humi, temp return humi, temp
def __init__(self, name, pin: Output, reference, description): super().__init__(name, pin, reference, description) self._gpio = GPIO(self.pin.channel, self.pin.type_pin) self._pmw = RPIGPIO.PWM(self.pin.channel, 100) self._pmw.start(self.bright)
def __init__(self, pin): self.dio = GPIO(pin)
def __init__(self, pin1, pin2 = None): pin2 = pin1 + 1 if pin2 is None else pin2 self.__gpio = GPIO(pin1, GPIO.IN) self.__gpio2 = GPIO(pin2, GPIO.IN) self.__gpio.on_event = self.__gpio_event self._pos = 0
class SensorDistancia(object): def __init__(self, pin): self.distancia = GPIO(pin) def _get_distance(self): usleep = lambda x: time.sleep(x / 1000000.0) _TIMEOUT1 = 1000 _TIMEOUT2 = 10000 self.distancia.dir(GPIO.OUT) self.distancia.write(0) usleep(2) self.distancia.write(1) usleep(10) self.distancia.write(0) self.distancia.dir(GPIO.IN) t0 = time.time() count = 0 while count < _TIMEOUT1: if self.distancia.read(): break count += 1 if count >= _TIMEOUT1: return None t1 = time.time() count = 0 while count < _TIMEOUT2: if not self.distancia.read(): break count += 1 if count >= _TIMEOUT2: return None t2 = time.time() dt = int((t1 - t0) * 1000000) if dt > 530: return None distance = ((t2 - t1) * 1000000 / 29 / 2) # cm return distance def get_distance(self): while True: dist = self._get_distance() if dist: return dist