def __init__(self, pin): self._value = 0 #GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) #GPIO.add_event_detect(pin, GPIO.FALLING, callback=self._increment, bouncetime=10) encoder = DigitalInputDevice(pin, pull_up=True) encoder.when_activated = self._increment encoder.when_deactivated = self._increment
def __init__(self, pin): self._value = 0 # setup gpiozero to call increment on each when_activated encoder = DigitalInputDevice(pin) encoder.when_activated = self._increment encoder.when_deactivated = self._increment
def flowmeter_manager(): # an object to interface with the flowmeter flowmeter_sensor = DigitalInputDevice(Constants.FLOWMETER_PIN) # setup callbacks to detect the rising edges ( # https://gpiozero.readthedocs.io/en/stable/migrating_from_rpigpio.html) flowmeter_sensor.when_activated = count_flowmeter_pulse while True: # create an infinite loop so that the flowmeter listener never dies pass
def initialize(pin, device_type): if device_type == "DigitalInput": device = DigitalInputDevice(pin) device.when_activated = lambda: on_action(pin, 0) device.when_deactivated = lambda: on_action(pin, 1) pin_map[pin] = device print("Initialized pin {} as {}".format(pin, device_type)) elif device_type == "DigitalOutput": pin_map[pin] = DigitalOutputDevice(pin) print("Initialized pin {} as {}".format(pin, device_type))
def create_encoder(pin): """ Creates and configures a DigitialInputDevice at the specified pin for use as a rotary encoder input. This function is intended for internal use only. """ encoder = DigitalInputDevice(pin, pull_up=True) encoder.when_activated = on_change encoder.when_deactivated = on_change return encoder
def setup_devices(): global btn, distance_sensor btn = DigitalInputDevice(FLOW_PIN) btn.when_activated = count_paddle if USE_PIGPIOD: factory = PiGPIOFactory() else: factory = NativeFactory() distance_sensor = DistanceSensor( trigger=TRIGGER_PIN, echo=ECHO_PIN, pin_factory=factory, queue_len=20, partial=True, )
from messageDecoder import * from gpiozero import DigitalInputDevice #sends message to user when pet goes to food bowl. diginput = DigitalInputDevice(22) def WhenActivated(): data = "pet at bowl" sendMessageDogDetect(data) def WhenDeactivated(): data = "pet left bowl" sendMessageDogDetect(data) diginput.when_activated = WhenActivated diginput.when_deactivated = WhenDeactivated
def row2Released(): global scanning scanning = True def row3Released(): global scanning scanning = True def row4Released(): global scanning scanning = True row1.when_activated = row1Pressed row2.when_activated = row2Pressed row3.when_activated = row3Pressed row4.when_activated = row4Pressed row1.when_deactivated = row1Released row2.when_deactivated = row2Released row3.when_deactivated = row3Released row4.when_deactivated = row4Released currentMillis = 0 previousMillis = 0 interval = 10 colNumber = 0 keypadNumber = 20 scanning = True passCount = 0
enc2_rev = 0 def enc1_fn(): global enc1_clicks, enc1_rev enc1_clicks = enc1_clicks + 1 if enc1_clicks == 40: enc1_clicks = 0 enc1_rev = enc1_rev + 1 print(enc1_rev, ' Revolutions completed by enc 1') def enc2_fn(): global enc2_clicks, enc2_rev enc2_clicks = enc2_clicks + 1 if enc2_clicks == 40: enc2_clicks = 0 enc2_rev = enc2_rev + 1 print(enc2_rev, ' Revolutions completed enc 2') enc1.when_activated = enc1_fn enc1.when_deactivated = enc1_fn enc2.when_activated = enc2_fn enc2.when_deactivated = enc2_fn while True: time.sleep(1)
length = hex(len(epc) // 4)[2:] return uhf.ext_read(enum='0' + length, epc=epc) def start_workflow(): print("start") cmd = uhf.single_tag_read() i = 100 while i > 0: ser.write(cmd) response = read() if received_epc(response): cmd = request_tid(response) elif received_tid(response): print("got tid") check_access(response) break else: cmd = uhf.single_tag_read() time.sleep(0.1) i -= 1 pir = DigitalInputDevice(4, pull_up=False) while True: pir.when_activated = start_workflow ser.close()
from gpiozero import DigitalInputDevice from signal import pause def button_pressed(): print("pressed") def button_released(): print("released") button_pin = DigitalInputDevice(23, pull_up=True) button_pin.when_activated = button_pressed button_pin.when_deactivated = button_released pause()
from gpiozero import DigitalInputDevice as DID from time import sleep PIN = 17 IN_PIN = DID(pin=17, pull_up=None, active_state=True, bounce_time=0.05) def watering(IN_PIN): #该参数是产生中断的设备(端口) while IN_PIN.value: print('正在浇水...') sleep(5) IN_PIN.when_activated = watering while True: print(IN_PIN.value) sleep(1)
args = parser.parse_args() with open(args.config) as config_file: config = json.load(config_file) # Config variables GPIO = ensure_config('GPIO', 'GPIO pin') id = ensure_config('sensor', 'Sensor id') secret = ensure_config('secret', 'Sensor secret') interval = ensure_config('interval', 'Interval') # Global state variables token = None count = 0 sending_errors = 0 # Actions print("") print("") print("Tempis is running!") send_data_task = task.LoopingCall(send_data) send_data_task.start(interval) get_token_task = task.LoopingCall(refresh_access_token) get_token_task.start(3600) sensor = DigitalInputDevice(GPIO) sensor.when_activated = increment_count reactor.run()
from sweetmorse.morse import Morse from gpiozero import DigitalOutputDevice, DigitalInputDevice speed = 100 # bits per second cycle_time = 1 / speed # seconds per bit end_of_file = "1010101010101010101" print("Obtaining pin 21 for output...") gpio_out = DigitalOutputDevice(21) # voltage generated here print("Obtaining pin 16 for input...") print() gpio_in = DigitalInputDevice(16) # voltage read here edges = [] # rising or falling voltage transitions gpio_in.when_activated = lambda: edges.append((dt.datetime.now(), "1")) gpio_in.when_deactivated = lambda: edges.append((dt.datetime.now(), "0")) try: message = Morse.from_plain_text("sos") binary_outgoing = message.binary print("Sending message: " + message.plain_text) print("Converted to binary: " + binary_outgoing) print() print("Sending message at {} bits per second...".format(speed)) print() for value in binary_outgoing + end_of_file: if value == '0': gpio_out.off()
print ('Sealevel Pressure = {0:0.2f} Pa'.format(pressao_Mar)) # The sea-level pressure ''' #===========================================================# def DHT(): try: h,t = dht.read_retry(dht.DHT22,24) return h,t except: return 0,0 pass #print ('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t,h)) #===========================================================# Sensor_chuva = DigitalInputDevice(18) Sensor_chuva.when_activated = mm wind_speed_sensor = DigitalInputDevice(21) wind_speed_sensor.when_activated = spin #===========================================================# #inicializando o mqtt mqttc = mqtt.Client() mqttc.on_connect = on_connect mqttc.on_disconnect = on_disconnect mqttc.on_publish = on_publish def publish_To_Topic(topic, message): mqttc.publish(topic, message) print("Published: " + str(message) + " " + "on MQTT Topic: " + str(topic)) print ("")
# print("Left Foot Edge") leftFoot._encoderEdge() def _rightHeadEdge(): # print("Right Head Edge") rightHead._encoderEdge() def _rightFootEdge(): # print("Right Foot Edge") rightFoot._encoderEdge() lh = DigitalInputDevice(14, pull_up=True) lh.when_activated = _leftHeadEdge lf = DigitalInputDevice(15, pull_up=True) lf.when_activated = _leftFootEdge rh = DigitalInputDevice(7, pull_up=True) rh.when_activated = _rightHeadEdge rf = DigitalInputDevice(5, pull_up=True) rf.when_activated = _rightFootEdge leftHead = motorCtl(17, 27, 14) leftFoot = motorCtl(4, 18, 15) rightHead = motorCtl(6, 16, 7) rightFoot = motorCtl(8, 12, 5) run(host='0.0.0.0', port=80, debug=False) del leftHead
if geste == Directions.DIR_UP: print("Haut") if geste == Directions.DIR_DOWN: print("Bas") if geste == Directions.DIR_NEAR: print("Proche") if geste == Directions.DIR_FAR: print("Loin") capteur_APDS9960.enableGestureSensor(True) # Déclaration de la broche d'interruption du capteur APDS-9960 APDS9960_INT = DigitalInputDevice(SENSOR_INTERRUPT, pull_up=True) # Précise que lorsqu'un nouveau geste sera détecté (broche d'interruption changera d'état) # alors on exécutera la fonction 'Lecture_geste()' APDS9960_INT.when_activated = Lecture_geste # Déclaration de l'objet associé au capteur APDS-9960 capteur_APDS9960 = GestureSensor.APDS9960(bus=1) # Initialisation du capteur APDS-9960 capteur_APDS9960.initDevice() capteur_APDS9960.resetGestureParameters() # Modification légère des paramètres pour s'adapter au module présent sur la carte (meilleurs résultats de détection) capteur_APDS9960.setGestureGain(GGAIN_2X) capteur_APDS9960.setGestureLEDDrive(LED_DRIVE_25MA) # Rend le capteur APDS-9960 actif capteur_APDS9960.enableGestureSensor(True) # Boucle infinie d'attente d'interruption try: while True:
#!/usr/bin/python import time import cv2 import requests from gpiozero import LED, LightSensor, DigitalInputDevice led = LED(17) sensor = DigitalInputDevice(4) sensor.when_activated = led.on sensor.when_deactivated = led.off while True: time.sleep(1)
shutdown # make the activity LED pulse to show the camera is working # This script makes use of the green led which is already present in the raspberry pi zero and pi zero W activity = PWMLED(47) # /sys/class/leds/led0 activity.pulse() # shut down the pi if the button is held down for >2 seconds shutdown_btn = Button(22, hold_time=2) shutdown_btn.when_held = shutdown print('activated shutdown button') # automatically stop recording and shut down when the low battery signal is received low_batt_signal = DigitalInputDevice(4, pull_up=True, bounce_time=2) low_batt_signal.when_activated = low_battery print('activated the low battery detection') with picamera.PiCamera() as camera: start_time = datetime.now() camera.resolution = ( 1640, 1232 ) # 1640x1232 at 30fps seems to be the resolution limit which the pi zero w gpu can handle. We could set the reolution lower to achieve higher framerates. camera.framerate = 30 camera.start_recording('/mnt/' + start_time.strftime('%d-%m-%Y_%H-%M-%S') + '__1' + '.h264') file = open('/mnt/camera.log', 'a') file.write( start_time.strftime('%d/%m/%Y, %H:%M:%S') + '\tStarting recording\n') file.close() print('now recording...')
from gpiozero import DigitalInputDevice rain_sensor = DigitalInputDevice(6) BUCKET_SIZE = 0.2794 count = 0 def bucket_tipped(): global count count = count + 1 print (count * BUCKET_SIZE) rain_sensor.when_activated = bucket_tipped
logging.info("Login success %s", datetime.datetime.now().strftime("%H:%M:%S- %b %d %Y")) server.sendmail(sendEmail, recEmail, msg) logging.info( "Email has been sent to %s : %s" % (recEmail, datetime.datetime.now().strftime("%H:%M:%S- %b %d %Y"))) except Exception as e: logging.error( "Unable to send email %s : %s" % (e, datetime.datetime.now().strftime("%H:%M:%S- %b %d %Y"))) global isActive isActive = False isVibrating = False isActive = False vibrationEndTime = time.time() vibrationStartTime = vibrationEndTime sendEmail = configparser[credentials]['sender_email'] passwd = configparser[credentials]['password'] recEmail = configparser[credentials]['rec_email'] port = configparser[credentials]['port'] smtp = configparser[credentials]['smtp'] stopTime = int(configparser[config]['stop_time']) startTimer = int(configparser[config]['start_time']) vibrationSensor.when_activated = vibration threading.Timer(1, checkVibration).start()
return km_per_hour * ADJUSTMENT def spin(): global count count = count + 1 #print (count) def get_windspeed(): interval = 5 inst_wind_val = calculate_speed(interval) return inst_wind_val count = 0 #''' wind_speed_sensor = DigitalInputDevice(5) wind_speed_sensor.when_activated = spin #This increases count each time the device sends a pulse. The pulse can be triggered by the slightest movement, so we should ignore if the count = 1 while True: count = 0 sleep(3) instantaneous_windspeed = get_windspeed() if count == 1: print "wind: 0.0" else: print "wind: ", instantaneous_windspeed #'''
from gpiozero import DigitalInputDevice from signal import pause import time class encoder(object): def __init__(self): self.value = 0 def reset(self): self.value = 0 def increment(self): self.value += 1 def activated() : my_enc.increment() def deactivated() : return 0 my_enc = encoder() enc = DigitalInputDevice(17) enc.when_activated = activated enc.when_deactivated = deactivated start = time.time() while True: elapsed = time.time()-start print('Time {0:0.2f} -- N = {1} -- Velocity {2}'.format(elapsed,my_enc.value,my_enc.value/elapsed),end="\r") pause()
from gpiozero import LineSensor, DigitalInputDevice from signal import pause from time import sleep def found(): print("hehwerewrewr") def nofound(): print("adsadsadsad") # sensor = LineSensor(4) # sensor.when_line = found # sensor.when_no_line = nofound sensor = DigitalInputDevice(4) sensor.when_activated = found sensor.when_deactivated = nofound sleep(1) while True: print("Sensor value: ", sensor.active_state) sleep(1) #pause()
radius_cm = 9.0 # Radius of the anemometer interval = 1.0 # Duration to report on speed ADJUSTMENT = 2 # Adjustment for weight of cups CM_IN_A_KM = 100000.0 SECS_IN_AN_HOUR = 3600 wind_speed_sensor = DigitalInputDevice(pinReadSpeed,pull_up=True) def calculate_speed(time_sec): global count circumference_cm = (2 * math.pi) * radius_cm rotations = count / 2.0 dist_km = (circumference_cm * rotations) / CM_IN_A_KM km_per_sec = dist_km / time_sec km_per_hour = km_per_sec * SECS_IN_AN_HOUR return km_per_hour * ADJUSTMENT def spin(): global count count = count + 1 wind_speed_sensor.when_activated = spin def get_windspeed(): global count count = 0 sleep(interval) return calculate_speed(interval)
radio._setRXState() # enter the transceiver into RX mode # Transceiver "number plate" print("CC1101_PARTNUM: {}".format(radio._readSingleByte( radio.PARTNUM))) # Chip part number print("CC1101_VERSION: {}".format(radio._readSingleByte( radio.VERSION))) # Chip version number print("PaTable value: {}".format(radio._readSingleByte( radio.PATABLE))) # PA power control base_frequency = (radio._readSingleByte(radio.FREQ2) << 16) | ( radio._readSingleByte(radio.FREQ1) << 8) | radio._readSingleByte( radio.FREQ0) fxosc = 26 * pow(10, 6) print("Carrier frequency: {}".format( base_frequency * (fxosc / pow(2, 16)))) # Carrier frequency (registers FREQ1, FREQ2 y FREQ3) print("Operation mode: {}".format( radio_state(radio))) # Displaying the current state of the cc1101 # CC1101 Transceiver Operation ---- interrupt.when_activated = on_activated # on_activated is triggered every time the interrupt line is activated while True: start = time() rssi = radio._getRSSI(radio.getRSSI()) end = time() print(f"RSSI: {rssi} dBm --- Time: {end-start}") # the main thread can access to the RSSI register every time it needs sleep(0.25)
def __init__(self, pin): self._value = 0 encoder = DigitalInputDevice(pin) encoder.when_activated = self._increment encoder.when_deactivated = self._increment
#!/usr/bin/python3 #coding: utf-8 from gpiozero import DigitalInputDevice import datetime import ambient from signal import pause ambi = ambient.Ambient(ID, "writeKey") radar = DigitalInputDevice(18, pull_up=False, bounce_time=2.0) def detector(): timestamp = str((datetime.datetime.now())) timestamp = timestamp[0:19] print("Image captured at", timestamp) h = 1 r = ambi.send({"d1": h}) r.close() radar.when_activated = detector pause()
def rain(): global rain_cum rain_cum = rain_cum + BUCKET_SIZE def temperature(): return temp_sensor.get_temperature() windspeed = threading.Thread(name="wind", target=wind(INTERVAL)) raindata = threading.Thread(name="rain", target=rain) windspeed.start() raindata.start() wind_speed_sensor.when_activated = spin rain_sensor.when_activated = rain speed = [] i = 0 while True: sleep(INTERVAL) speed.append(wind(INTERVAL)) i += 1 if i == 15: temper = temperature() speed_avg = sum(speed, 0.00) / len(speed) speed_gust = max(speed) payload = json.dumps({ "idx": RAIN_DOMOTICZ_ID,
global wind_count wind_count = wind_count +1 #rain def precipitation(): global rain_count mm_rain = round(rain_count*BUCKET_SIZE,4) #get the total amount of precipitation return mm_rain #for every tip, add 1 to count def bucket_tipped(): global rain_count rain_count=rain_count+1 #call the tip module when pin is high rain_sensor.when_activated = bucket_tipped #read from BCM pin 17 wind_speed_sensor = DigitalInputDevice(17) #call the spin module when pin is high wind_speed_sensor.when_activated = spin ####################################################################################### ## ####################################################################################### #get data from sensor def getData(): s.trigger() #tell the sensor to report reading time.sleep(0.1)
def main(): global laserOverlay, explOverlay, camera, strike, vivant, vehicle, RedOverlay """LED strip configuration""" print "led" strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP) # Intialize the library (must be called once before other functions). strip.begin() colorWipe(strip, Color(255, 255, 255), 0) # Green wipe print "led ok" laserShot = None """Connexion to drone""" connection_string = "/dev/ttyACM0" vehicle = connect(connection_string, wait_ready=False) if vehicle.armed: print "Vehicule armed" # Create PixelStrip object with appropriate configuration. # Intialize the library (must be called once before other functions). strip.begin() """Creation de la video""" # Video Resolution VIDEO_HEIGHT = 480 VIDEO_WIDTH = 640 # Cross Hair Image crossHair = Image.new("RGBA", (VIDEO_WIDTH, VIDEO_HEIGHT), (0, 0, 0, 0)) crossHairPixels = crossHair.load() with picamera.PiCamera() as camera: camera.resolution = (VIDEO_WIDTH, VIDEO_HEIGHT) camera.rotation = 180 camera.framerate = 30 camera.led = False overlay_renderer = None camera.start_preview(fullscreen=True, window=(0, 0, 720, 1280)) topText = "Alt: 310m Spd: 45km/h Dir: N" textOverlayCanvas = Image.new("RGBA", ( ((img.size[0] + 31) // 32) * 32, ((img.size[1] + 15) // 16) * 16, )) # Use Roboto font (must be downloaded first) font = ImageFont.truetype( "/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 20) #Add cockpit img = Image.open('cockpit.png') img = img.resize((640, 480)) # Add cockpit Image to FPV feed pad = Image.new('RGBA', ( ((img.size[0] + 31) // 32) * 32, ((img.size[1] + 15) // 16) * 16, )) pad.paste(img, (0, 0)) topOverlay = camera.add_overlay(pad.tobytes(), size=img.size) topOverlay.alpha = 128 topOverlay.layer = 3 print "im" topOverlayImage = textOverlayCanvas.copy() topOverlay = camera.add_overlay(pad.tobytes(), size=(640, 60), layer=3, alpha=128, fullscreen=False, window=(0, 20, 640, 60)) print "im" #Add Laser PNG for fire imgLaser = Image.open('laser.png') imgLaser = imgLaser.resize((640, 480)) laser = Image.new('RGBA', ( ((img.size[0] + 31) // 32) * 32, ((img.size[1] + 15) // 16) * 16, )) laser.paste(imgLaser, (0, 0)) laserOverlay = camera.add_overlay(laser.tobytes(), size=imgLaser.size, layer=1) laserOverlay.alpha = 128 #Add Explosion layer imgExpl = Image.open('explosion.png') imgExpl = imgExpl.resize((640, 480)) explosion = Image.new('RGBA', ( ((img.size[0] + 31) // 32) * 32, ((img.size[1] + 15) // 16) * 16, )) explosion.paste(imgExpl, (0, 0)) explOverlay = camera.add_overlay(explosion.tobytes(), size=imgExpl.size, layer=1) explOverlay.alpha = 128 #add Hit layer imgRedLayer = Image.open('red-layer.png') redlayer = Image.new('RGBA', ( ((img.size[0] + 31) // 32) * 32, ((img.size[1] + 15) // 16) * 16, )) redlayer.paste(imgRedLayer, (0, 0)) RedOverlay = camera.add_overlay(redlayer.tobytes(), size=imgRedLayer.size, layer=1) RedOverlay.alpha = 128 time.sleep(0.1) """Connection de la board Inav Mavlink""" print "RC Channels:", vehicle.channels """Connection du IR RX""" '''irRxPin = 16 irRx = IRModule.IRRemote(callback='DECODE') GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # uses numbering outside circles GPIO.setup(irRxPin,GPIO.IN) # set irPin to input GPIO.add_event_detect(irRxPin,GPIO.BOTH,callback=irRx.pWidth) irRx.set_verbose(False) #Set function to be call when a IR message is received (drone has been hit) irRx.set_callback(drone_Hit)''' radar = DigitalInputDevice(16, pull_up=False, bounce_time=2.0) ## Pause until light is detected '''wait_for_light() ## Return True if light is detected light_detected''' """Connection du IR TX""" irTxPin = 21 GPIO.setmode(GPIO.BCM) GPIO.setup(irTxPin, GPIO.OUT) GPIO.output(irTxPin, False) """--Gestion des LEDS--""" try: print " System status: %s" % vehicle.system_status.state print "--->Lancement du drone<---" colorWipe(strip, Color(255, 0, 0), 0) # Green wipe while True: radar.when_activated = detector print "im2" topOverlayImage = textOverlayCanvas.copy() print "im3" topOverlay.update(topOverlayImage.tostring()) print "im4" print(ldr.value) print vehicle.channels, "\r" time.sleep(0.1) if (vehicle.channels['7'] > 1100): #fire print "\rFIRE\r" print vehicle.channels laserOverlay.layer = 5 GPIO.output(irTxPin, True) time.sleep(0.2) laserOverlay.layer = 1 GPIO.output(irTxPin, False) if (strike >= 4): #check number of impact on our drone explOverlay.layer = 5 vivant = 0 print "End striked ", strike, "times" time.sleep(3) explOverlay.layer = 1 strike = 0 except KeyboardInterrupt: camera.remove_overlay(topOverlay) colorWipe(strip, Color(0, 0, 0), 0) # Green wipe camera.close() vehicle.close() print "Cancelled"
from gpiozero import DigitalInputDevice rain_sensor = DigitalInputDevice(6) BUCKET_SIZE = 0.2794 count = 0 def bucket_tipped(): global count count = count + 1 print(count * BUCKET_SIZE) rain_sensor.when_activated = bucket_tipped