from time import sleep from nanpy import SerialManager, ArduinoApi connection_one = SerialManager(device='/dev/ttyUSB0') a_one = ArduinoApi(connection=connection_one) leftForward = 13 leftBackward = 15 rightForward = 4 rightBackward = 5 a_one.pinMode(leftForward, a_one.OUTPUT) a_one.pinMode(leftBackward, a_one.OUTPUT) a_one.pinMode(rightForward, a_one.OUTPUT) a_one.pinMode(rightBackward, a_one.OUTPUT) while True: a_one.digitalWrite(leftForward, a_one.HIGH) a_one.digitalWrite(leftBackward, a_one.LOW) a_one.digitalWrite(rightForward, a_one.HIGH) a_one.digitalWrite(rightBackward, a_one.LOW) sleep(2) a_one.digitalWrite(leftForward, a_one.LOW) a_one.digitalWrite(leftBackward, a_one.LOW) a_one.digitalWrite(rightForward, a_one.LOW) a_one.digitalWrite(rightBackward, a_one.LOW) sleep(2) from time import sleep from nanpy import SerialManager, ArduinoApi connection_three = SerialManager(device='/dev/ttyUSB2')
#!/usr/bin/env python # Author :Mr.Chanapai Chuadchum # Project name :RoboticArm Kinematic Sim Con 'RKSC system' # Describetion: Use with Jetson Tk1 and Vision System function on the CUDA import numpy as np # Numpy function for the math and matrix calculation function import matplotlib.pyplot as plt from nanpy import (ArduinoApi,SerialManager) from nanpy import Servo from nanpy import serial_manager from nanpy import CapacitiveSensor # Capacitive sensor input from nanpy import DHT,DallasTemperature from nanpy.arduinotree import ArduinoTree # Arduino Tree function import time # Time control delaytion #Connection of the System on the serial communication system connection = SerialManager('/dev/ttyACM0',115200) # Serial communication via MCU function a = ArduinoApi(connection=connection) # Connection with the serial magnager connectionBody = SerialManager('/dev/ttyACM1',115200) # Serial sensing and control b = ArduinoApi(connection=connectionBody) # The Body and sensing connection for the system of therobotic arm #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # Servo part for the robotic arm servo3e = Servo(3) servo3u = Servo(4) servo1u = Servo(5) servo1e = Servo(8) servo2u = Servo(9) servo2e = Servo(10) # Servo for the robotic wrist of the arm servoWrist= Servo(43) # Wrist servo servowristrotate = Servo(44) # Wrist rotate servo # Stepper motor at the finger #Finger 1
Uses the nanpy library (https://github.com/nanpy/nanpy), which controls a slave Arduino processor. The sensors are connected to the Arduino. Both digital (1/0 output) and analogue (0-1023 ouput) sensors may be be connected to the Arduino. To use this, Nanpy firmware needs to be flashed onto the Arduino to allow Python to be used. Note -This sensor class can only be used with sensors which send their output straight to the Arduino pins. For sensors which use I2C or SPI, with their own registers, a library to use them has to be written separately. """ from thingflow.base import OutputThing, IndirectOutputThingMixin from nanpy import ArduinoApi, SerialManager ardApi = ArduinoApi(connection=SerialManager(device='/dev/ttyACM0')) class ArduinoSensor(OutputThing, IndirectOutputThingMixin): """Sensor connected to Arduino. Output is analogue(1/0) or digital output(0 - 1023). Nanpy firmware needs to be flashed onto Arduino. """ def __init__(self, sensor_id, AD): """sensor_id is port number, AD is True/False for Analogue/Digital """ super().__init__() self.sensor_id = sensor_id self.AD = AD ardApi.pinMode(sensor_id, ardApi.INPUT) def sample(self): if self.AD:
#! /usr/bin/env python # Author: Gopal Krishan Aggarwal and Piyush Mangtani # Contact: [email protected] # Desc: This assumes arduino is connected as /dev/ttyACM0 device to RasPi. It reads the analog 0 pin of arduino and calculates the wind direction from the analog value as done below. Read sparkfun weather meter's datasheet for more details. from nanpy import ArduinoApi from nanpy import SerialManager c = SerialManager(device='/dev/ttyACM0') from time import sleep a = ArduinoApi(c) direction = a.analogRead(0) if direction >= 728 and direction <= 792: d = 0 #print "The wind direction is : NORTH " + str(direction) elif direction >= 228 and direction <= 257: d = 180 # print "The wind direction is : SOUTH " + str(direction) elif direction >= 0 and direction <= 97: d = 90 # print "The wind direction is : EAST " + str(direction) elif direction >= 924 and direction <= 961: d = 270 # print "The wind direction is : WEST " + str(direction) elif direction >= 384 and direction <= 442:
def connect(self): attempts = 3 conn = None if self.config.get('use_wifi', False): while attempts > 0 and self.main_thread_running.is_set(): try: print('\033[1;36m{0}\033[0;0m -> Connecting... \t'. format(self.config["name"], (3 - attempts))) attempts -= 1 conn = SocketManager( host=str(self.config.get('address', 'mudpi.local'))) # Test the connection with api self.api = ArduinoApi(connection=conn) except (SocketManagerError, BrokenPipeError, ConnectionResetError, socket.timeout) as e: print( '{name} -> Connecting...\t\t\033[1;33m Timeout\033[0;0m ' .format(**self.config)) if attempts > 0: print('{name} -> Preparing Reconnect... \t'.format( **self.config)) else: print( '{name} -> Connection Attempts...\t\033[1;31m Failed\033[0;0m ' .format(**self.config)) conn = None self.resetConnection() time.sleep(15) except (OSError, KeyError) as e: print( '[{name}] \033[1;33m Node Not Found. (Is it online?)\033[0;0m' .format(**self.config)) conn = None self.resetConnection() time.sleep(15) else: print( '{name} -> Wifi Connection \t\t\033[1;32m Success\033[0;0m ' .format(**self.config)) for worker in self.workers: worker.connection = conn self.node_connected.set() self.node_ready.set() break else: while attempts > 0 and self.main_thread_running.is_set(): try: attempts -= 1 conn = SerialManager( device=str(self.config.get('address', '/dev/ttyUSB1'))) except SerialManagerError: print( '{name} -> Connecting...\t\t\033[1;33m Timeout\033[0;0m ' .format(**self.config)) if attempts > 0: print('{name} -> Preparing Reconnect... \t'.format( **self.config), end='\r', flush=True) else: print( '{name} -> Connection Attempts...\t\033[1;31m Failed\033[0;0m ' .format(**self.config)) self.resetConnection() conn = None time.sleep(15) else: if conn is not None: print( '[{name}] Serial Connection \t\033[1;32m Success\033[0;0m ' .format(**self.config)) for worker in self.workers: worker.connection = conn self.node_connected.set() self.node_ready.set() break return conn
from nanpy import (ArduinoApi, SerialManager) import serial import struct import time import datetime PIN = A0 connection = SerialManager(device='/dev/ttyACM0') Board1 = ArduinoApi(connection=connection) Board1.pinMode(PIN, Board1.INPUT) print "Connecting to Arduino...." time.sleep(1) print "Handshake:Good" def outputResponse (command): value = Board1.analogRead(A0) return value() def inputCommand (): return raw_input('what is your command-->') while 1: command = inputCommand() result = outputResponse(command) if result == 0: Board1.digitalWrite(A0, Board1.HIGH) print "Relay 1 is On"
def moveBot(x): x = x.lower() try: connection = SerialManager() a = ArduinoApi(connection=connection) except: print('Failed To Connect') a.pinMode(m1pin1, a.OUTPUT) a.pinMode(m1pin2, a.OUTPUT) a.pinMode(m2pin1, a.OUTPUT) a.pinMode(m2pin2, a.OUTPUT) a.pinMode(m3pin1, a.OUTPUT) a.pinMode(m3pin2, a.OUTPUT) a.pinMode(m4pin1, a.OUTPUT) a.pinMode(m4pin2, a.OUTPUT) a.pinMode(m1enable, a.OUTPUT) a.pinMode(m2enable, a.OUTPUT) a.pinMode(m3enable, a.OUTPUT) a.pinMode(m4enable, a.OUTPUT) try: if (x == "left"): print("left dhukche") a.analogWrite(m1enable, 200) a.digitalWrite(m1pin1, a.HIGH) a.digitalWrite(m1pin2, a.LOW) a.analogWrite(m2enable, 200) a.digitalWrite(m2pin1, a.HIGH) a.digitalWrite(m2pin2, a.LOW) a.analogWrite(m3enable, 200) a.digitalWrite(m3pin1, a.HIGH) a.digitalWrite(m3pin2, a.LOW) a.analogWrite(m4enable, 200) a.digitalWrite(m4pin1, a.HIGH) a.digitalWrite(m4pin2, a.LOW) sleep(1) updateMovement() elif (x == "right"): print("right dhukche") a.analogWrite(m1enable, 255) a.digitalWrite(m1pin1, a.HIGH) a.digitalWrite(m1pin2, a.LOW) a.analogWrite(m2enable, 150) a.digitalWrite(m2pin1, a.LOW) a.digitalWrite(m2pin2, a.HIGH) a.analogWrite(m3enable, 255) a.digitalWrite(m3pin1, a.HIGH) a.digitalWrite(m3pin2, a.LOW) a.analogWrite(m4enable, 150) a.digitalWrite(m4pin1, a.LOW) a.digitalWrite(m4pin2, a.HIGH) sleep(1) updateMovement() elif (x == "front"): print("front dhukche") a.analogWrite(m1enable, 250) a.digitalWrite(m1pin1, a.HIGH) a.digitalWrite(m1pin2, a.LOW) a.analogWrite(m2enable, 100) a.digitalWrite(m2pin1, a.HIGH) a.digitalWrite(m2pin2, a.LOW) a.analogWrite(m3enable, 250) a.digitalWrite(m3pin1, a.HIGH) a.digitalWrite(m3pin2, a.LOW) a.analogWrite(m4enable, 100) a.digitalWrite(m4pin1, a.HIGH) a.digitalWrite(m4pin2, a.LOW) sleep(1) updateMovement() elif (x == "back"): print("dhukche") a.analogWrite(m1enable, 200) a.digitalWrite(m1pin1, a.LOW) a.digitalWrite(m1pin2, a.HIGH) a.analogWrite(m2enable, 200) a.digitalWrite(m2pin1, a.LOW) a.digitalWrite(m2pin2, a.HIGH) a.analogWrite(m3enable, 200) a.digitalWrite(m3pin1, a.LOW) a.digitalWrite(m3pin2, a.HIGH) a.analogWrite(m4enable, 200) a.digitalWrite(m4pin1, a.LOW) a.digitalWrite(m4pin2, a.HIGH) sleep(1) updateMovement() else: a.digitalWrite(m1pin1, a.LOW) a.digitalWrite(m1pin2, a.LOW) a.digitalWrite(m2pin1, a.LOW) a.digitalWrite(m2pin2, a.LOW) a.digitalWrite(m3pin1, a.LOW) a.digitalWrite(m3pin2, a.LOW) a.digitalWrite(m4pin1, a.LOW) a.digitalWrite(m4pin2, a.LOW) except: pass
#for voice in voices: # engine.setProperty('voice',voice.id) # print voice.id # Servo input function servo = Servo(2) # Finger 1 servo2 = Servo(3) # Finger 2 servo3 = Servo(4) # Finger 3 servo4 = Servo(5) # Finger 4 servo5 = Servo(6) # Finger 5 servo6 = Servo(9) # Finger 6 try: Handfinger = SerialManager( '/dev/ttyACM0', 115200) # Hand serial checker and hand shake connection Handcontrol = ArduinoApi(connection=Handfinger) engine.say("Hardware serial connected 100 percent") engine.runAndWait() for i in progressbar.progressbar(range(100)): time.sleep(0.02) except: print("Connection error please check the serial communication") try: Sensorserial = serial.Serial( "/dev/ttyUSB0", 115200) # Serial communication for the sensors serial engine.say("Sensors serial connected 100 percent") engine.runAndWait() for i in progressbar.progressbar(range(100)): time.sleep(0.02) except: print("Sensors serial failure please check the sensors serial port")
import time from nanpy import (ArduinoApi, SerialManager) default_connection = SerialManager(device='/dev/ttyUSB1') api = ArduinoApi(default_connection) pin = int(input('Enter Soil Sensor Pin: ')) api.pinMode(pin, api.INPUT) loop = 10 while loop > 0: resistance = api.analogRead(pin) print('Resistance: ', resistance) loop -=1 time.sleep(5)
from nanpy import ArduinoApi, SerialManager, wire from nanpy.i2c import I2C_Master import robotmath import math # Connects the arduino and the raspberry pi through serial try: connection = SerialManager(device='COM4') # connection = SerialManager() Arduino = ArduinoApi(connection=self.connection) except: print 'Error: No Arduino found...' class MPU6050(object): MPU_address = 0x68 minVal = 265 maxVal = 402 def __init__(self): self.master = I2C_Master(wire.Wire(connection=connection)) self.master.send(self.MPU_address, [0x6B, 0]) def getAngle(self, axis): data = self.master.request(self.MPU_address, 14) accX = data[0] << 8 | data[1] accY = data[2] << 8 | data[3] accZ = data[4] << 8 | data[5] xAngle = robotmath.map(accX, minVal, maxVal, -90, 90)
def clicked_valve(self): valve_4 = 'A3' return valve_4 """ ######### Raspberry - Arduino setup ############ """ from nanpy import (ArduinoApi, SerialManager) from time import sleep from datetime import datetime try: connectMain = SerialManager(device='/dev/ttyACM1') m = ArduinoApi(connection=connectMain) except: print("Main connection failed!") try: connectLaser = SerialManager(device='/dev/ttyACM2') l = ArduinoApi(connection=connectLaser) except: print("Laser connection failed!") """ ############## Main Arduino code ############### """ # totalTrial = 90 valveDelay = 70 reward = False
def bulb50(): connection = SerialManager(device='/dev/ttyACM0') a = ArduinoApi(connection=connection) bulb = 10 a.pinMode(bulb, a.OUTPUT)
def nanpy_connect(): connection = SerialManager(device='/dev/ttyUSB0') arduinoObject = ArduinoApi(connection=connection) return arduinoObject
PINS = { 'direction': 4, 'step': 5, 'sleep': 6, 'dispense': 3, 'reset': 2, 'photocell': 5, # A5 'limit': 7, 'ms1': 9, 'ms2': 10, 'ms3': 12, 'gate': 11 } CONNECTION = SerialManager(device='/dev/ttyUSB0') A = ArduinoApi(connection=CONNECTION) SERVO = Servo(PINS['gate']) JOBS = [] SCHED = sched.scheduler(time.time, time.sleep) def toggle(a): time.sleep(SLEEP_TIME) # .75 if a.digitalRead(PINS['sleep']) == a.HIGH: print("Sleeping") a.digitalWrite(PINS['sleep'], a.LOW) elif a.digitalRead(PINS['sleep']) == a.LOW: print("Awake") a.digitalWrite(PINS['sleep'], a.HIGH) print("STATE TOGGLE")
from ocrtextout import ocr_msg WorkDay = [] today = datetime.date.today() WorkDay.append(today) cam = cv2.VideoCapture(1) cv2.namedWindow("OCR capture text read") img_counter = 0 Ultrasonics = 0 try: connection = SerialManager() Hardwarecontrol = ArduinoApi(connection=connection) except: print("Hardware unit error please check") def capture_pictures(): cv2.imshow('img1',frame) # display the image was capture cv2.imwrite('img1'+ str(WorkDay[0]) + '.jpg',frame) while True: ret, frame = cam.read() cv2.imshow("ocr seccondcamera", frame) Ultrasonics = Hardwarecontrol.analogRead(2) # Reading the analogvalue from the sensor that deteted the opject if not ret: break k = cv2.waitKey(1) if k%256 ==27:
from nanpy import ArduinoApi, SerialManager arduino = ArduinoApi(connection=SerialManager()) from time import sleep import logging logger = logging.getLogger(__name__) class DigitalOut(object): states = ["OFF", "ON"] def __init__(self, pin, name="name", pinType=None, id=None): logger.debug("pin:{0}, name:{1}, pinType:{2}".format( pin, name, pinType)) self.pin = pin self.state = self.getState() self.stateString = self.getStateString() arduino.pinMode(pin, arduino.OUTPUT) if pinType == None: pinType = self.__class__.__name__ self.name = "{} Pin ({}, {})".format(name, pinType, pin) # print "Initializating {}".format(self.name) def off(self): arduino.digitalWrite(self.pin, arduino.LOW) self.state = False logger.debug("{} turned {}".format(self.getName(), self.getStateString()))
from Tkinter import * # Import Tkinter to display the window option control mannual #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #Intro openning speech of the arm engine = pyttsx.init() # Openning the speech function of the arm engine.setProperty('rate', 140) #rate of the speech function system functionallize engine.say("Roboic Arm version VX-S now operating" ) # Say intro speech function of the robotic arm engine.runAndWait() # System run and wait for the run #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # Base serial connection try: #Base connection function connectionBase = SerialManager( '/dev/ttyACM0', 115200) # Serial connection function for the base joint base = ArduinoApi( connection=connectionBase) # Connection base estrablished except: print("Serial Base error please reconnect again") engine.say("Serial base error please recheck the serial connection") engine.runAndWait() # Shouder serial connection try: #Shoudler connection function connectionShoulder = SerialManager('/dev/ttyACM1', 115200) # Seri$ Shoulder = ArduinoApi(connection=connectionShoulder) # Connection base $ except: print("Serial Shoulder error please reconnect again") engine.say("Serial Shoulder error please recheck the serial connect") engine.runAndWait() # Elbow serial connection try: #Elbow connection function connectionElbow = SerialManager('/dev/ttyACM2', 115200) # Seri$
''' import microgear.client as microgear # microgear unit function for the IoT import time import logging # logging data import csv import pandas # Pandas importer function for the system data transfer import os # Operating system to control the software to open when needed sensor1 = 0 # Back sensor of the autonomouse car sensor2 = 0 # Front sensor of the autonomouse car sensor3 = 0 # Activation sensors for the robot # Data key set function and value Data_1_key = " " Data_2_value = " " try: connection = SerialManager() motorunit = ArduinoApi(connection=connection) #Connection astrablished except: print("Motor unit control ") # Beacon function input for the positioning of the robot try: connection1 = SerialManager( "/dev/ttyUSB0", 115200) # Serial input of the Third wireless MCU Wmcu = ArduinoApi(connection=connection1) # Connection connected except: print("Wireless message reciever MCU connection lost") #try: # sensor_msg = serial.Serial("/dev/ttyUSB0",115200) #except: # print("Sensor read message error please check the sensor unit") # Backward function for the robot to move back and detect obstable
Project name: Autonomouse Robotics vision ''' import serial from nanpy import (ArduinoApi, SerialManager) from ocrtextout import ocr_msg, pid # OCR text read out function, PID for the process id to kill processing function from autocapturefunction import gpid from Autonomouscameraman import gpidd import time import os # Operating system to control the software to open when needed sensor1 = 0 # Back sensor of the autonomouse car sensor2 = 0 # Front sensor of the autonomouse car sensor3 = 0 # Activation sensors for the robot ocr_msg_text = " " # Text message ocr try: connection = SerialManager() motorunit = ArduinoApi(connection=connection) #Connection astrablished except: print("Motor unit control ") #try: # sensor_msg = serial.Serial("/dev/ttyUSB0",115200) #except: # print("Sensor read message error please check the sensor unit") # Backward function for the robot to move back and detect obstable def Backward_active(sensor1, SpeedStart, SpeedEnd, timechange): if int(sensor1) >= 50: motorunit.analogWrite(6, 0) motorunit.analogWrite(10, 0) motorunit.analogWrite(4, 0) motorunit.analogWrite(3, 0)
from flask import Flask, render_template, request from nanpy import (ArduinoApi, SerialManager) from time import sleep #from flask website from nanpy import Stepper import time import RPi.GPIO as GPIO from std_msgs.msg import String app = Flask(__name__) #placeholder for current module (app.py) #instance of flask app MOTOR_AMOUNT = [0, 1, 2, 3, 4] try: #trying to establish connection to the arduino connection = SerialManager( device='/dev/ttyACM0') #automatically finds the arduino connected a = ArduinoApi(connection=connection) #instance of the arduinoapi object except: print("Failed to connect to Arduino") #* 0 = Thumb #* 1 = Pinky #* 2 = Ring #* 3 = Middle #* 4 = Index GPIO.setmode(GPIO.BCM) Motor1A = 16 #DC motor pins Motor1B = 20 Motor1E = 21
def __init__(self, pin, connection=default_connection): self.pin = pin self.connection = connection self.api = ArduinoApi(connection) return
def connectMotor(self): try: connection = SerialManager(self.devicePath) #CHANGE THIS self.motorSerial = ArduinoApi(connection=connection) except Exception as e: raise e
def init(): a = ArduinoApi() a.pinMode(6, a.INPUT)
# -*- coding: utf-8 -*- # Mesure de la resistance d'une CTN et calcul de la température # Calcul de la température à partir de la relation de Steinhart-Hart from nanpy import ArduinoApi # Gestion de l'Arduino from nanpy import SerialManager # Gestion port série from time import sleep # Importation de sleep(seconde) from math import log Vcc = 5.0 # Tension d'alimentation Ro = 10000 # Résistance du pont A = 1.0832e-3 # Coeff. de Steinhart-Hart B = 2.1723e-4 # ... C = 3.2770e-7 # ... port = SerialManager(device='/dev/ttyACM0' ) # Sélection du port série (exemple : device = 'COM6') uno = ArduinoApi(connection=port) # Déclaration de la carte Arduino while True: U = uno.analogRead(0) * 5 / 1023 # Lecture la tension sur A0 R = Ro * U / (Vcc - U) # Calcul de la résistance T = (1.0 / (A + B * log(R) + C * log(R)**3)) T = T - 273.15 # Calcul de la température print("R = ", R, "T = ", T) # Affichage sleep(1) # Temporisation d'une seconde port.close() # Fermeture du port série
from nanpy import (ArduinoApi, SerialManager, Servo) import time, threading import globalConfig # Initiates the Arduino link serialConnection = SerialManager() arduino = None try: arduino = ArduinoApi(connection=serialConnection) print("Arduino link correctly established") except: print("Arduino link unreachable") # The 13 LED is embedded on most of Arduino boards def toggleLED(): if arduino is not None: arduino.pinMode(13, arduino.OUTPUT) arduino.digitalWrite(13, 1) time.sleep(5) arduino.digitalWrite(13, 0) def moveRobot(): if arduino is not None: # Sets pin definition constants M1_pin_direction = 4 # Left motor, forward/backward M2_pin_direction = 7 # Right motor, forward/backward M1_pin_speed = 5 M2_pin_speed = 6 SERVO_pin = 16 # Sets pins initialization
from nanpy import (ArduinoApi, SerialManager) import time 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
def main(): # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(FACE_DETECTION_STATUS_PIN, GPIO.OUT) # Serial connection setup (for the servos) connection = SerialManager() ArduinoApi(connection=connection) servo_x = Servo(SERVO_X_ARDUINO_PIN) servo_y = Servo(SERVO_Y_ARDUINO_PIN) # Threaded Video stream setup vs = create_video_stream(CAMERA_RESOLUTION, CAMERA_FRAMERATE, CAMERA_ROTATION) camera_center = map(lambda x: x / 2, CAMERA_RESOLUTION) # from camera resolution # Face detection Haar cascade file face_cascade = cv2.CascadeClassifier( '/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml') # Initial pan-tilt angles angle_x = 90 angle_y = 90 servo_x.write(angle_x) servo_y.write(angle_y) def stop(): vs.stop() GPIO.output(FACE_DETECTION_STATUS_PIN, False) GPIO.cleanup() connection.close() def exit_handler(signum, frame): stop() print "\nBye!" sys.exit(0) # Clean manual stop signal.signal(signal.SIGINT, exit_handler) while True: try: # grab the frame from the threaded video stream frame = vs.read() # Convert to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Look for faces in the image faces = face_cascade.detectMultiScale(gray, 1.5, 2) if faces is not (): # Display face detection on a led GPIO.output(FACE_DETECTION_STATUS_PIN, True) # Look for the biggest face biggest_face = get_biggest_face(faces) # Compute pan-tilt angle to adjust centring ax, ay = get_compensation_angle(biggest_face, camera_center, CAMERA_RESOLUTION, CAMERA_ANGLE_OF_VIEW) # Update angles values angle_x = angle_x + ax angle_y = angle_y + ay servo_x.write(angle_x) servo_y.write(angle_y) else: GPIO.output(FACE_DETECTION_STATUS_PIN, False) except Exception as e: print e stop() sys.exit(1)