def main(pir_pin=2,inactiveDuration=10,outdir="."): """ *Parameters* > `pir_pin<int>`: the GPIO signal pin (in BCM mode) of the PIR motion sensor > `inactiveDuaration<int>`: specifies when the camera should stop recording after no motion has been detected > `outdir<str>`: the path to the desired directory of which to save the video files """ # === Local Variables === camera = PiCamera() # === setup Arduino === connection = SerialManager() a = ArduinoApi(connection=connection) # === start main loop === while True: # === sense PIR motion === motionDetected = a.digitalRead(pir_pin) print(motionDetected) # === condition === if motionDetected: print("started recording...") # === start recording === # Set-up camera camera.resolution = (1024,768) # Start camera camera.start_preview() # Camera warm-up time time.sleep(2) # Determine output filename outfilename = datetime.datetime.now().strftime("%m-%d-%Y-%H-%M-%S") + ".h264" # Start Recording camera.start_recording(outdir+"/"+outfilename) while motionDetected: # record for duration time.sleep(inactiveDuration) # detected motion motionDetected = a.digitalRead(pir_pin) # Stop Recording camera.stop_recording() print("recording finished")
class Sensor(): def __init__(self, pin, name='Sensor', connection=default_connection, analog_pin_mode=False, key=None): self.pin = pin self.name = name self.key = key.replace( " ", "_").lower() if key is not None else self.name.replace( " ", "_").lower() self.analog_pin_mode = analog_pin_mode self.connection = connection self.api = ArduinoApi(connection) return def init_sensor(self): #Initialize the sensor here (i.e. set pin mode, get addresses, etc) pass def read(self): #Read the sensor(s), parse the data and store it in redis if redis is configured pass def readRaw(self): #Read the sensor(s) but return the raw data, useful for debugging pass def readPin(self): #Read the pin from the ardiuno. Can be analog or digital based on "analog_pin_mode" data = self.api.analogRead( self.pin) if analog_pin_mode else self.api.digitalRead(self.pin) return data
class Control(): def __init__(self, pin, name=None, connection=default_connection, analog_pin_mode=False, key=None, redis_conn=None): self.pin = pin if key is None: raise Exception('No "key" Found in Control Config') else: self.key = key.replace(" ", "_").lower() if name is None: self.name = self.key.replace("_", " ").title() else: self.name = name self.analog_pin_mode = analog_pin_mode self.connection = connection self.api = ArduinoApi(connection) try: self.r = redis_conn if redis_conn is not None else redis.Redis( host='127.0.0.1', port=6379) except KeyError: self.r = redis.Redis(host='127.0.0.1', port=6379) return def init_control(self): #Initialize the control here (i.e. set pin mode, get addresses, etc) self.api.pinMode(self.pin, self.api.INPUT) pass def read(self): #Read the sensor(s), parse the data and store it in redis if redis is configured return self.read_pin() def read_raw(self): #Read the sensor(s) but return the raw data, useful for debugging pass def read_pin(self): #Read the pin from the ardiuno. Can be analog or digital based on "analog_pin_mode" data = self.api.analogRead( self.pin) if self.analog_pin_mode else self.api.digitalRead( self.pin) return data def emitEvent(self, data): message = {'event': 'ControlUpdate', 'data': {self.key: data}} print(message["data"]) self.r.publish('controls', json.dumps(message))
class Control(): def __init__(self, pin, name='Control', connection=default_connection, analog_pin_mode=False, key=None): self.pin = pin self.name = name self.key = key.replace( " ", "_").lower() if key is not None else self.name.replace( " ", "_").lower() self.analog_pin_mode = analog_pin_mode self.connection = connection self.api = ArduinoApi(connection) return def init_control(self): #Initialize the control here (i.e. set pin mode, get addresses, etc) self.api.pinMode(self.pin, self.api.INPUT) pass def read(self): #Read the sensor(s), parse the data and store it in redis if redis is configured return self.readPin() def readRaw(self): #Read the sensor(s) but return the raw data, useful for debugging pass def readPin(self): #Read the pin from the ardiuno. Can be analog or digital based on "analog_pin_mode" data = self.api.analogRead( self.pin) if self.analog_pin_mode else self.api.digitalRead( self.pin) return data def emitEvent(self, data): message = {'event': 'ControlUpdate', 'data': {self.key: data}} print(message["data"]) variables.r.publish('controls', json.dumps(message))
elif (name == "humidity"): device_values[name] = dht.readHumidity() elif (sensor == "ldr"): a.pinMode(device["port"], a.INPUT) intensity = a.analogRead(device["port"]) type_values = device["type_values"] for type_value in type_values: name = type_value["name"] device_values = device["device_values"] if (name == "intensity"): device_values[name] = intensity elif (sensor == "pir"): a.pinMode(device["port"], a.INPUT) reading = a.digitalRead(device["port"]) motion = False if (reading == a.HIGH): motion = True type_values = device["type_values"] for type_value in type_values: name = type_value["name"] device_values = device["device_values"] if (name == "motion"): device_values[name] = motion data = {} data["device_values"] = device["device_values"] device_id = device["_id"] req_url = url + "/" + str(device_id)
ledStat = False btnstat = 0 try: connection = serialManager() a = ArduinoApi(connection=connection) except: print("fail to connect to ardinno") # Setup t a.pinMode(ledPin, a.OUTPUT) a.pinMode(btnPin, a.INPUT) try: while True: btnStat - a.digitalRead(btnPin) print("btn state is : {}".format(btnStat)) if btnStat: if ledStat: a.digitalWrite(ledPin, a.LOW) ledstat = False print("leeed offff") sleep(1) else: a.digitalWrite(ledPin, a.HIGH) ledState = True print("leeed onnnn") sleep(1) except: a.digitalWrite(ledPin, a.LOW)
try: connection = SerialManager() a = ArduinoApi(connection=connection) except: print("Failed to connect to Arduino") #Setup arduino pins like in arduino IDE a.pinMode(buttonPin, a.INPUT) for m in servoPins: servo.append(Servo(m)) try: while True: buttonState = a.digitalRead(buttonPin) print(" Button State: {} Current Servo: {} Current Angle: {}".format( buttonState, currentServo, currentAngle)) if buttonState: servo[currentServo].write(0) currentAngle = 0 currentServo += 1 if currentServo > numPins: currentServo = 0 sleep(1) buttonState = False servo[currentServo].write(currentAngle) currentAngle += angleInc if currentAngle > 180: currentAngle = 0 sleep(1)
class ArduinoController(object): serialManager = None led_controller = None def __init__(self, zmq_context=None, debounce=DEFAULT_DEBOUNCE, button_pins=[], led_pin=DEFAULT_LED_PIN): self.debounce = debounce self.button_pins = button_pins self.led_pin = led_pin self.zmq_context = zmq_context or zmq.Context.instance() self.zmq_buttons_pub = self.zmq_context.socket(zmq.PUB) self.zmq_buttons_pub.bind("inproc://arduino/buttons_pub") self.buttons_timestamps = {pin: None for pin in self.button_pins} def connect(self): # close old connection if exists if self.serialManager: self.serialManager.close() # make new connection self.serialManager = SerialManager() self.a = ArduinoApi(connection=self.serialManager) def setup(self): self.a.pinMode(self.led_pin, self.a.OUTPUT) for pin in self.button_pins: self.a.pinMode(pin, self.a.INPUT) def loop(self): for pin in self.button_pins: if self.a.digitalRead(pin) == self.a.HIGH: if self.buttons_timestamps[pin] is None: self._keypress(pin) self.buttons_timestamps[pin] = self._get_millis() else: if self.buttons_timestamps[pin] is not None: if self.buttons_timestamps[ pin] + self.debounce < self._get_millis(): self._keyup(pin) self.buttons_timestamps[pin] = None if self.buttons_timestamps[pin] is not None: self._keydown(pin) self._led_frame() def set_led_controller(self, led_controller): self.led_controller = led_controller def set_led_blinking(self, countdown=None): self.set_led_controller(LedBlinker(freq=10, countdown=countdown)) def set_led_fading(self): self.set_led_controller(LedFader(freq=0.25)) def set_led_off(self): self.set_led_controller(LedSingle(brightness=0)) def set_led_on(self): self.set_led_controller(LedSingle(brightness=255)) def set_led_blink_once(self): self.set_led_controller(LedBlinker(freq=25, countdown=1)) def _keypress(self, pin): evt = 'keypress={}'.format(pin).encode() self.zmq_buttons_pub.send(evt) def _keydown(self, pin): evt = 'keydown={}'.format(pin).encode() self.zmq_buttons_pub.send(evt) def _keyup(self, pin): evt = 'keyup={}'.format(pin).encode() self.zmq_buttons_pub.send(evt) def _get_millis(self): return int(time.time() * 1000) def _led_frame(self): if self.led_controller is None: self.a.analogWrite(self.led_pin, 0) else: brightness = self.led_controller.frame(self._get_millis()) self.a.analogWrite(self.led_pin, brightness)
from nanpy import ArduinoApi, SerialManager from time import sleep connection = SerialManager() a = ArduinoApi(connection=connection) LED = 13 brightness = 0 fadeAmount = 5 a.pinMode(LED, a.OUTPUT) while True: a.analogWrite(LED, brightness) brightness += fadeAmount if brightness == 0 or brightness == 255: fadeAmount = -fadeAmount sleep(0.03) """ other basic functions - ArduinoApi.py a.digitalRead(pin) a.digitalWrite(pin, value) a.analogRead(pin) a.analogWrite(pin, value) a.millis() a.pulseIn(pin, value) a.shiftOut(dataPin, clockPin, bitOrder, value) """
a.pinMode(red, a.OUTPUT) #Setup red LED a.pinMode(yellow, a.OUTPUT) #Setup yellow LED a.pinMode(green, a.OUTPUT) #Setup green LED br = 2 by = 3 bg = 4 a.pinMode(br, a.INPUT) #Setup red button a.pinMode(by, a.INPUT) #Setup yellow button a.pinMode(bg, a.INPUT) #Setup green button while True: r = a.digitalRead(br) #Get state of red button y = a.digitalRead(by) #Get state of yellow button g = a.digitalRead(bg) #Get state of green button if r == 1: a.digitalWrite(red, 1) #Turn on red LED if y == 1: a.digitalWrite(yellow, 1) #Turn on yellow LED if g == 1: a.digitalWrite(green, 1) #Turn on green LED else: a.digitalWrite(red, 0) #Turn off red LED a.digitalWrite(yellow, 0) #Turn off yellow LED
try: connection = SerialManager() a = ArduinoApi(connection=connection) except: print("Failed to connect to Arduino.") trigger = 7 echo = 8 a.pinMode(trigger, a.OUTPUT) a.pinMode(echo, a.INPUT) a.digitalWrite(trigger, a.LOW) print("Waiting for sensor to settle..") time.sleep(0.5) print("Calculating distance...") a.digitalWrite(trigger, a.HIGH) time.sleep(0.00001) a.digitalWrite(trigger, a.LOW) while a.digitalRead(echo) == 0: startTime = time.time() while a.digitalRead(echo) == 1: endTime = time.time() duration = endTime - startTime distance = (duration * 34300) / 2 print("Distance:", distance, "cm")
enc_br = 'A1' # left motor enc_al = 'A6' enc_bl = 'A7' # Make pins digital inputs a.pinMode(enc_ar, a.INPUT) a.pinMode(enc_br, a.INPUT) a.pinMode(enc_al, a.INPUT) a.pinMode(enc_bl, a.INPUT) last_enc_al = a.LOW last_enc_bl = a.LOW while True: read_a = a.digitalRead(enc_al) read_b = a.digitalRead(enc_bl) print(read_a, read_b) ''' if last_enc_al != read_a: print('Left encA change') print(read_a, read_b) if last_enc_bl != read_b: print('Left encA change') print(read_a,read_b) last_enc_al = read_a last_enc_bl = read_b ''' sleep(.0001) #if last_enc_al is a.LOW and read_a is a.HIGH: # print('yipeee')
#Connection parameters #connection = SerialManager('COM5') connection = SerialManager('/dev/ttyACM0') a = ArduinoApi(connection=connection) motorPin = 12 speedPin = 3 brakePin = 9 bottomPin = 7 #Setup a.pinMode(motorPin, a.OUTPUT) a.pinMode(speedPin, a.OUTPUT) a.pinMode(brakePin, a.OUTPUT) a.pinMode(bottomPin, a.INPUT) def startMotor(): a.digitalWrite(brakePin, a.LOW) a.digitalWrite(motorPin, a.HIGH) a.analogWrite(speedPin, 1000) def stopMotor(): a.digitalWrite(brakePin, a.HIGH) #Loop while a.digitalRead(bottomPin) == a.LOW: startMotor() time.sleep(5) stopMotor()
buttonC = 5 buttonD = 6 buttonE = 7 #Definitions for notes are in tone library in Nanpy, can easily change names to simply "c", "d", etc. if needed c = Tone.NOTE_C6 d = Tone.NOTE_D6 e = Tone.NOTE_E6 a.pinMode(speaker, a.OUTPUT) #Setup speaker pin a.pinMode(buttonC, a.INPUT) #Setup buttonC a.pinMode(buttonD, a.INPUT) #Setup buttonD a.pinMode(buttonE, a.INPUT) #Setup buttonE while True: bc = a.digitalRead(buttonC) #Reading at buttonC bd = a.digitalRead(buttonD) #Reading at buttonD be = a.digitalRead(buttonE) #Reading at buttonE #If buttonC is pressed: if (bc == 1): tone.play(c, 1) #Play note c #If buttonD is pressed: elif (bd == 1): tone.play(d, 1) #Play note d #If buttonE is pressed: elif (be == 1): tone.play(e, 1) #Play note e
print("\nCancelling animation...\n") led_colour = [(black)] * 360 client.put_pixels(led_colour) time.sleep(1) continue elif Option == '5': print("Turn on sound near sensor.\nPress CTRL + C to exit.") try: while True: #reading values from sound sensor SensorData = a.digitalRead(soundSensor) print(SensorData) led_colour1 = [(255, 0, 0)] * 360 led_colour2 = [(0, 0, 0)] * 360 #condition for intensity of soundData if (SensorData == 0): client.put_pixels(led_colour1) elif (SensorData == 1): client.put_pixels(led_colour2) except KeyboardInterrupt:
from nanpy import (ArduinoApi, SerialManager) from time import sleep #Connect to Arduino. Automatically finds serial port. connection = SerialManager() a = ArduinoApi(connection = connection) motorPin = 6 button = 7 a.pinMode(motorPin, a.OUTPUT) a.pinMode(button, a.INPUT) while True: state = a.digitalRead(button) while (state == 1): for i in range(50, 255): #Start at 50 so it doesn't stop completely at any point a.analogWrite(motorpin, i) sleep(0.03) for i in range(255, 50): #Counts backwards to 50 a.analogWrite(motorpin, i) sleep(0.03) a.analogWrite(motorPin, 0) #Turns off motor