Exemplo n.º 1
0
def main(args):
    global pisugar, paper, ui
    buzzer = Buzzer(pin=16)

    buzzer.play(sound=buzzer.alert, blocking=False, repeat=100)

    ui.build = buildCustomUI
    ui.start()

    vbeacon.startScanning()
    vbeacon.startAdvertising()
    print("--------------------------\nDEBUG 1: " +
          (str)(vbeacon.isAdvertising) + "\n-----------------------")

    done = False
    while not done:
        try:
            beaconsNearby = vbeacon.getNearbyBeacons()

            print("-------------------------------------")
            print(f" {len(beaconsNearby)} beacons nearby")
            print("-------------------------------------")

            for beacon in beaconsNearby:
                print(f"{beacon}")

            time.sleep(1.0)
        except KeyboardInterrupt:
            done = True

    vbeacon.stopAdvertising()
    vbeacon.stopScanning()
Exemplo n.º 2
0
def captureInfoCam():
    GPIO.setwarnings(False) # Ignore warning for now
    GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
                    
    subprocess.call(['fswebcam -r 640x480 --no-banner /home/pi/Desktop/image.jpg', '-1'], shell=True)

    #Azure
    face_uri = "https://raspberrycp.cognitiveservices.azure.com/vision/v1.0/analyze?visualFeatures=Faces&language=en"
    pathToFileInDisk = r'/home/pi/Desktop/image.jpg'
    with open( pathToFileInDisk, 'rb' ) as f:
        data = f.read()
        
    headers = { "Content-Type": "application/octet-stream" ,'Ocp-Apim-Subscription-Key': '7e9cfbb244204fb994babd6111235269'}
    try:
        response = requests.post(face_uri, headers=headers, data=data)
        faces = response.json()
        
        #pprint(faces)
        age = faces['faces'][0].get('age')
        gender = faces['faces'][0].get('gender')
        
        datosUsuario = [age, gender]
        return datosUsuario
    except requests.exceptions.ConnectionError:
        return None
    except IndexError:
        buzzer=Buzzer(13)
        buzzer.buzz(seconds=0.5)
        return None
    else:
        return datosUsuario
Exemplo n.º 3
0
    def __init__(self):
        super().__init__()

        #initialization
        self.CLASSES = [
            "background", "aeroplane", "bicycle", "bird", "boat", "bottle",
            "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse",
            "motorbike", "person", "pottedplant", "sheep", "sofa", "train",
            "tvmonitor"
        ]
        self.COLORS = np.random.uniform(0, 255, size=(len(self.CLASSES), 3))

        # python3 pi_object_detection.py --prototxt MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
        self.args = {
            "prototxt": "MobileNetSSD_deploy.prototxt.txt",
            "model": "MobileNetSSD_deploy.caffemodel",
            "confidence": 0
        }

        #load serialized model from disk (neural network model)
        print("[INFO] loading model...")
        #IDK
        self.net = cv2.dnn.readNetFromCaffe(self.args["prototxt"],
                                            self.args["model"])

        #init input queue (frames), output queues (detections) + list of actual
        #detections returned by child process
        self.inputQueue = Queue(
            maxsize=1)  #populated by parent, processed by child
        self.outputQueue = Queue(
            maxsize=1
        )  #populated by child, processed by parent (output from processing input)
        self.detections = None

        #construct child process *independent* from main process of execution
        print("[INFO] starting process...")
        p = Process(target=self.classify_frame,
                    args=(
                        self.net,
                        self.inputQueue,
                        self.outputQueue,
                    ))
        p.daemon = True
        p.start()

        # init video stream, allow camera warmup + init FPS counter
        print("[INFO] starting stream...")
        # cap=cv2.VideoCapture(0)
        # vs = VideoStream(usePiCamera=True).start()
        time.sleep(1.0)
        self.fps = FPS().start()
        self.area = 0
        self.my_priority_queue = PriorityQueue(maxsize=0)

        self.buzzer = Buzzer()
Exemplo n.º 4
0
 def __init__(self, config):
     self.__config = config
     self.__navegador = Navegador(self.__config)
     self.__sensorDeObjetos = SensorDeObjetos(
         config.DomoPatronAReconocer, config.DomoCamaraId,
         config.DomoMostrarEnVentanaReconocimiento,
         config.DomoFotogramasXCaptura)
     self.__testigoLuminoso = Led()
     self.__testigoSonoro = Buzzer()
     if self.__config.DomoMostrarEnVentanaCentrado:
         cv.NamedWindow(self.__windowName, 1)
     self.__debugMode = self.__config.DomoDebugMode
Exemplo n.º 5
0
def main():
    try:
        os.nice(-15)
    except OSError:
        print("Process priority could not be decreased!")

    EntryHR = OuterHandReader.OHandReader(12, 18, 1)
    print("Entry Hand Reader Initialized!")
    ExitHR = ExitHandReader.ExitHandReader(32, 31)
    print("Exit Hand Reader Initialized!")
    MD = MaskDetector.MaskDetector(headless=False)
    print("Mask Detector Initialized!")
    door = Door()
    print("Door Initialized!")
    B = Buzzer(33)

    while True:
        controller.STATE = controller.DORMANT
        while controller.STATE == controller.DORMANT:
            if (ExitHR.read()):
                controller.STATE = controller.UNLOCKED
                print("The door is unlocked!")
                B.positiveresponse()
                door.exit()
                sleep(1)
            sleep(0.1)

        controller.STATE = controller.VERIFICATION
        print("Verification state")
        MD.start_display()
        while controller.STATE == controller.VERIFICATION:
            result = EntryHR.read()
            if (HAND_APPROVED == result):
                print("Checking face mask.")
                result = MD.last_label()
                if result == "Mask":
                    print("Greetings. The door is unlocked.")
                    #controller.STATE = controller.UNLOCKED
                    B.positiveresponse()
                    door.entrance()
                elif result == "Improper Mask":
                    print(
                        "Please wear your mask properly. When you do, have your hand measured again. Thank you!"
                    )
                    B.ringwarning()
                else:
                    print(
                        "You do not have a mask on! Please leave the door front area!"
                    )
                    B.ringerror()
                    #controller.STATE = controller.LOCKED

        sleep(5)
Exemplo n.º 6
0
	def __init__(self):
		threading.Thread.__init__(self)
		self.shutdown_flag = threading.Event()
		self.motor = Motorcontroller()
		self.buzzer = Buzzer()
		self.xbee = Xbee()
		self.decoder = Decoder()
		self.servo1 = 96
		self.servo2 = 75
		self.joycalc = Joystick()
		self.motor.setServo1(self.servo1)
		self.motor.setServo2(self.servo2)
		self.lastSavedTime = 0
Exemplo n.º 7
0
    def detected(self, pin):
        settings = DbClass().getDataFromDatabase('settings')[0]
        print("motion detected")

        if settings[1]:
            print('start recording')

            if settings[4]:
                print('led')
                LedLamp().flikker_bg(5)

            if settings[3]:
                print('alarm')
                Buzzer().alarm_bg(5)

            if settings[5]:
                print('email send')
Exemplo n.º 8
0
    def __init__(self):
        self.advertLoop = None
        self.advertiser = None
        self.ad_manager = None
        self.advertThread = None

        self.scanThread = None
        self.scanExit = True
        self.scanMutex = threading.Lock()
        self.beaconList = {}

        self.company_id = 0x004c
        self.beacon_type = [0x02, 0x15]
        self.uuid = uuid.UUID('{2f234454-cf6d-4a0f-adf2-f4911ba9ffa6}')
        self.tx_power = [0xb3]
        self.major = 0
        self.minor = 0

        self.deviceSettings = {}
        self.pisugar = PiSugar2()
        self.buzzer = Buzzer(16)
Exemplo n.º 9
0
from Buzzer import Buzzer
import time

buzz1 = Buzzer(24)
buzz1.on()
time.sleep(1)
buzz1.off()
time.sleep(1)
buzz1.toggle()
if buzz1.is_on():
    print("on")
elif buzz1.is_off():
    print("off")
time.sleep(1)
buzz1.toggle()
if buzz1.is_on():
    print("on")
elif buzz1.is_off():
    print("off")
time.sleep(1)
buzz1.beep()
time.sleep(5)
buzz1.beep(2, 20)
time.sleep(5)
Exemplo n.º 10
0
from time import sleep

#configurations
distance_threshold = 20  #in CM
blink_beep_speed = Speed.FAST

#variables
picture_taken = False

#objects
sensor = UltrasonicSensor(19, 26)
email = Email()
camera = Camera()
grn_led = LED(13)
red_led = LED(6)
buzzer = Buzzer(5)


#methods
def blink_red():
    red_led.blink(5, blink_beep_speed)


def blink_green():
    grn_led.blink(5, blink_beep_speed)


def beep_buzzer():
    buzzer.beep(5, blink_beep_speed)

Exemplo n.º 11
0
import RPi.GPIO as GPIO
import time
from LED import LED
from Knop import Knop
from Buzzer import Buzzer

GPIO.setmode(GPIO.BCM)

# knop1_ingedrukt = 1
# knop2_ingedrukt = 1
# knop3_ingedrukt = 1
# knop4_ingedrukt = 1

led = LED(25)
buzzer = Buzzer(23)
buttons = [21, 20, 16, 12]

# GPIO.setup(led,GPIO.OUT)
# GPIO.setup(buzzer,GPIO.OUT)

# p = GPIO.PWM(buzzer,261)

knop1 = Knop(buttons[0])
knop2 = Knop(buttons[1])
knop3 = Knop(buttons[2])
knop4 = Knop(buttons[3])
# GPIO.add_event_detect(button, GPIO.RISING, actie, 400)

# def led_knipperen():
#     GPIO.output(led,GPIO.HIGH)
#     time.sleep(0.5)
Exemplo n.º 12
0
import RPi.GPIO as GPIO  # Importing RPi library to use the GPIO pins
from time import *  # Used for sleep method
from bluetooth import *  # Imports libraries that supports Bluetooth
from AlphaBot import AlphaBot
from Buzzer import Buzzer
from Rgb import Rgb
from Temperature import Temperature
import instructions  # Methods where String commands are translated into separate instructions

# ----------------------------------------- INITIALIZATION -------------------------------------------------------------

Ab = AlphaBot(
)  # Instance of AlphaBot created    | delivers EcliBot movement methods
b = Buzzer(
    23)  # Instance of Buzzer created      | buzzer can be switched on/off
t = Temperature(
    11,
    18)  # Instance of Temperature created | temperature can be red from sensor
rgb = Rgb(
    5, 19, 16
)  # Instance of Rgb created         | LED diode can turns red, green, blue, or off

commands = []  # List designed for storing instructions for EcliBot
step = 0  # Counter, used for keeping track the number of Strings received

GPIO.setmode(
    GPIO.BCM)  # Referring to the pins by the "Broadcom SOC channel" number
GPIO.setwarnings(False)  # Disable warnings

# ----------------------------------------- CUSTOMIZED MOVE METHODS ----------------------------------------------------
Exemplo n.º 13
0
        logger.debug(msg.topic + ": '" + str(msg.payload) + "'")
    except:
        logger.info("Error!")


mqtt.on_connect = on_connect
mqtt.on_disconnect = on_disconnect
mqtt.on_message = on_message
mqtt.will_set(SERVICE_NAME + "/state/status", "OFF", 1, True)
mqtt.reconnect_delay_set(min_delay=1, max_delay=60)
mqtt.connect(BROKER_ADDRESS, BROKER_PORT, 60)  # connect to broker
mqtt.publish(SERVICE_NAME + "/state/status", "ON", 1, True)

# Modules
pixels = Pixels(mqtt, SERVICE_NAME, DEBUG)
buzzer = Buzzer(mqtt, SERVICE_NAME, DEBUG)
cameraServo = CameraServo(mqtt, SERVICE_NAME, DEBUG)
infrared_receiver = InfraredReceiver(mqtt, SERVICE_NAME, DEBUG)
infrared_sensor = InfraredSensor(mqtt, SERVICE_NAME, DEBUG)
joystick = Joystick(mqtt, SERVICE_NAME, DEBUG)
obstacle_avoidance = ObstacleAvoidance(mqtt, SERVICE_NAME, DEBUG)
trSensor = TRSensor(mqtt, SERVICE_NAME, 5, DEBUG)
ultrasonic = Ultrasonic(mqtt, SERVICE_NAME, DEBUG)
wheels = Wheels(mqtt, SERVICE_NAME, DEBUG)

# Setup IR Sensor
infrared_receiver.buzzer = buzzer
infrared_receiver.camera_servo = cameraServo
infrared_receiver.pixels = pixels
infrared_receiver.wheels = wheels
 def run(self):
     Buzzer()
Exemplo n.º 15
0
POS_CHAVE = 23
RELE = 24

######### State Machine Variables ##########
current_state = 0
passwd = "33"
codigo_veiculo = "33"
codigo_motorista = ""
codigo_linha = ""
date_time = []
############################################

######### Instances of the Modules #########
lcd = Lcd()
keypad = Keypad()
buzzer = Buzzer()
gprs = GPRS("179.188.3.201", 9091)
#gprs = GPRS()
############################################

############ Rfid variables  ###############
CARDS = ["[154, 99, 3, 197, 63]", "[151, 25, 214, 53, 109]"]
KEYCHAINS = ["[213, 1, 9, 136, 85]", "[5, 214, 17, 136, 74]"]

DRIVERS_ID = [100, 101]
LINE_ID = [222, 223]

RFID_PRESENT = True
if RFID_PRESENT:
    rfid = Rfid()
lock = Lock()
Exemplo n.º 16
0
    def setup(self):
        
        try:

            # Iterate over the joystick devices.
            print('Available devices:')

            for fn in os.listdir('/dev/input'):
                if fn.startswith('js'):
                    print(('  /dev/input/%s' % (fn)))

            # We'll store the states here.
            axis_states = {}
            button_states = {}

            # These constants were borrowed from linux/input.h
            axis_names = {
                0x00 : 'x',
                0x01 : 'y',
                0x02 : 'z',
                0x03 : 'rx',
                0x04 : 'ry',
                0x05 : 'rz',
                0x06 : 'trottle',
                0x07 : 'rudder',
                0x08 : 'wheel',
                0x09 : 'gas',
                0x0a : 'brake',
                0x10 : 'hat0x',
                0x11 : 'hat0y',
                0x12 : 'hat1x',
                0x13 : 'hat1y',
                0x14 : 'hat2x',
                0x15 : 'hat2y',
                0x16 : 'hat3x',
                0x17 : 'hat3y',
                0x18 : 'pressure',
                0x19 : 'distance',
                0x1a : 'tilt_x',
                0x1b : 'tilt_y',
                0x1c : 'tool_width',
                0x20 : 'volume',
                0x28 : 'misc',
            }
                    
            button_names = {
                0x120 : 'trigger',
                0x121 : 'thumb',
                0x122 : 'thumb2',
                0x123 : 'top',
                0x124 : 'top2',
                0x125 : 'pinkie',
                0x126 : 'base',
                0x127 : 'base2',
                0x128 : 'base3',
                0x129 : 'base4',
                0x12a : 'base5',
                0x12b : 'base6',
                0x12f : 'dead',
                0x130 : 'a',
                0x131 : 'b',
                0x132 : 'c',
                0x133 : 'x',
                0x134 : 'y',
                0x135 : 'z',
                0x136 : 'tl',
                0x137 : 'tr',
                0x138 : 'tl2',
                0x139 : 'tr2',
                0x13a : 'select',
                0x13b : 'start',
                0x13c : 'mode',
                0x13d : 'thumbl',
                0x13e : 'thumbr',
                
                0x220 : 'dpad_up',
                0x221 : 'dpad_down',
                0x222 : 'dpad_left',
                0x223 : 'dpad_right',
                
                # XBox 360 controller uses these codes.
                0x2c0 : 'dpad_left',
                0x2c1 : 'dpad_right',
                0x2c2 : 'dpad_up',
                0x2c3 : 'dpad_down',
            }
                    
            axis_map = []
            button_map = []
                    
            # Open the joystick device.
            fn = '/dev/input/js0'
            if self.DEBUG==True:
                print(('Opening %s...' % fn))
            jsdev = open(fn, 'rb')
            
            # Get the device name.
            #buf = bytearray(63)
            buf = array.array('B', [0] * 64)
            ioctl(jsdev, 0x80006a13 + (0x10000 * len(buf)), buf) # JSIOCGNAME(len)
            js_name = buf.tostring().rstrip(b'\x00').decode('utf-8')
            if self.DEBUG==True:
                print(('Device name: %s' % js_name))
                    
            # Get number of axes and buttons.
            buf = array.array('B', [0])
            ioctl(jsdev, 0x80016a11, buf) # JSIOCGAXES
            num_axes = buf[0]
            
            buf = array.array('B', [0])
            ioctl(jsdev, 0x80016a12, buf) # JSIOCGBUTTONS
            num_buttons = buf[0]
                    
            # Get the axis map.
            buf = array.array('B', [0] * 0x40)
            ioctl(jsdev, 0x80406a32, buf) # JSIOCGAXMAP
                    
            for axis in buf[:num_axes]:
                axis_name = axis_names.get(axis, 'unknown(0x%02x)' % axis)
                axis_map.append(axis_name)
                axis_states[axis_name] = 0.0
                        
            # Get the button map.
            buf = array.array('H', [0] * 200)
            ioctl(jsdev, 0x80406a34, buf) # JSIOCGBTNMAP
                        
            for btn in buf[:num_buttons]:
                btn_name = button_names.get(btn, 'unknown(0x%03x)' % btn)
                button_map.append(btn_name)
                button_states[btn_name] = 0


            # Print out the values
            if self.DEBUG==True:
                print(('%d axes found: %s' % (num_axes, ', '.join(axis_map))))
                print(('%d buttons found: %s' % (num_buttons, ', '.join(button_map))))


            ## CONFIGURE ANALOGUE JOYSTICK "DEAD-ZONES"
            # use these values to increase/decrease the deadzones on the analogues
            pdz=0.100 # Positve Deadzone
            ndz=-0.100 # Negative Deadzone

            ## Init the DCmotors class
            if self.DEBUG==True:
                print("Creating New DC Motor Class...")
            dcm = DCMotors()
            # set speeds up here | use to set speed for DC Motors in the program
            dcm_speed_0=0
            dcm_speed_1=10
            dcm_speed_2=20
            dcm_speed_3=30
            dcm_speed_4=40
            dcm_speed_5=50
            # set initial speeds here
            dcm_initial_speed_x = dcm_speed_1 # Turning (Left/Right)
            dcm_initial_speed_y = dcm_speed_2 # Movement (Forward/Backward)
            # use initial speed values to set the initial Pulse Width Modulation values
            dcm.setPWMAX(dcm_initial_speed_x) # Turning (Left Wheel)
            dcm.setPWMBX(dcm_initial_speed_x) # Turning (Right Wheel)
            dcm.setPWMAY(dcm_initial_speed_y) # Moving Forward/Backward (Left Wheel)
            dcm.setPWMBY(dcm_initial_speed_y) # Moving Forward/Backward (Right Wheel)
            # store "last known" speeds here (starts with the 'initial speed' values)
            dcm_last_known_speed_x=dcm_initial_speed_x # Turning (Left/Right)
            dcm_last_known_speed_y=dcm_initial_speed_y # Movement (Forward/Backward)
            # store the "current" speeds here
            dcm_current_speed_x=dcm_initial_speed_x # Turning (Left/Right)
            dcm_current_speed_y=dcm_initial_speed_y # Movement (Forward/Backward)

            ## Init the PCA9685 class (Servo Motors)
            if self.DEBUG==True:
                print("Creating New Instance Of PCA9685 Class...")
            pwm=PCA9685(0x40, debug=True) # leave these aguments as is, do not change.
            pwm.setPWMFreq(50) #set the frequency | must be 50, do not chnage this!
            #set the initial servo pulses, which "center" the servos before we begin
            pwm.setServoPulse(0,1500) #horizontal | note: the channel (0) is for horizontal
            pwm.setServoPulse(1,1500) #vertical | note: the channel (1) is for vertical
            vslv=1500 # Vertical Servo Last Value | store the last known value for the vertical servo's 'Servo Pulse' | set to 1500 (center) before the main loop starts
            hslv=1500 # Horizontal Servo Last Value | store the last known value for the horizontal servo's 'Servo Pulse' | set to 1500 (center) before the main loop starts
            sspa=700 # Servo Stopping Point A | set the stopping point for the servo's here
            sspb=2300 # Servo Stopping Point B | set the stopping point for the servo's here
            sss=10 # Servo Step Size | set the size of the servo steps here (larger steps will make it move faster)

            ## Init the Buzzer class
            bzr=Buzzer()
            
            # Main event loop
            while True:
                evbuf = jsdev.read(8)
                if evbuf:
                    time, value, type, number = struct.unpack('IhBB', evbuf)
                            
                    if type & 0x80:
                        if self.DEBUG==True:
                            print("(initial)")
                                
                    if type & 0x01:
                        button = button_map[number]
                        if button:
                            button_states[button] = value
                            if value:
                                if self.DEBUG==True:
                                    print(("%s pressed" % (button)))
                            else:
                                if self.DEBUG==True:
                                    print(("%s released" % (button)))

                            ###############################################################
                            # BUTTONS [TRIANGLE, SQUARE, CROSS, CIRCLE] | MISC. FUNCTIONS #
                            ###############################################################
                            if value:

                                ################################
                                # CIRCLE | RECENTER THE SERVOS #
                                ################################
                                if button == "b":
                                    
                                    print("CIRCLE Pushed... Centering Servos Now ^_^)")
                                    # set the servo pulse to the center positions/values for the vertical and horizontal servos
                                    pwm.setServoPulse(0,1500)
                                    pwm.setServoPulse(1,1500)
                                    # make sure the vertical & horizontal servo's last known value is reset to the 'center' position to prevent "jumping behaviour" when panning again
                                    vslv=1500
                                    hslv=1500

                                ##############################################
                                # SQUARE | RESET SPEEDS | TURNING & MOVEMENT #
                                ##############################################
                                elif button == "y":

                                    print("SQUARE Pushed... Resetting Speeds Now ^_^")
                                    ## reset speed code here...
                                    dcm.setPWMAX(dcm_initial_speed_x) # set Pulse Width Modulation For Motor A To Initial Value (Turning Speed)
                                    dcm.setPWMBX(dcm_initial_speed_x) # set Pulse Width Modulation For Motor B To Initial Value (Turning Speed)
                                    dcm.setPWMAY(dcm_initial_speed_y) # set Pulse Width Modulation For Motor A To Initial Value (Movement Speed)
                                    dcm.setPWMBX(dcm_initial_speed_y) # set Pulse Width Modulation For Motor B To Initial Value (Movement Speed)
                                    dcm_last_known_speed_x=dcm_initial_speed_x # update last known movement speed to the initial value (Turning Speed)
                                    dcm_last_known_speed_y=dcm_initial_speed_y # update last known movement speed to the initial value (Movement Speed)

                                #####################
                                # TRIANGLE | BUZZER #
                                #####################
                                elif button == "x":

                                    print("TRIANGLE Pushed... Buzzing Now ^_^")
                                    bzr.ezbuzz() 

                                #############################################################
                                ## speed control (DC Motors) | MOVEMENT (FORWARD/BACKWARD) ##
                                #############################################################

                                ## SLOW DOWN (top left trigger)
                                elif button == "tl":

                                    print ("Top Left Trigger Pushed... Decreasing Speed now...")

                                    # if speed is zero, do nothing... cant slow down any more than that can we..
                                    if dcm_last_known_speed_y == dcm_speed_0:
                                        print("Speed is already 0, we cant go any lower bro...")

                                    # else if speed is 1, slow down to 0
                                    elif dcm_last_known_speed_y == dcm_speed_1:
                                        print("Slowing Down Turning Speed to: ",dcm_speed_0)
                                        dcm.setPWMAY(dcm_speed_0)
                                        dcm.setPWMBY(dcm_speed_0)
                                        dcm_last_known_speed_y=dcm_speed_0 # update last known speed value to the updated one

                                    # else if speed is 2, slow down to 1
                                    elif dcm_last_known_speed_y == dcm_speed_2:
                                        print("Slowing Down Turning Speed to: ",dcm_speed_1)
                                        dcm.setPWMAY(dcm_speed_1)
                                        dcm.setPWMBY(dcm_speed_1)
                                        dcm_last_known_speed_y=dcm_speed_1 # update last known speed value to the updated one
                                        
                                    # else if speed is 3, slow down to 2
                                    elif dcm_last_known_speed_y == dcm_speed_3:
                                        print("Slowing Down Turning Speed to: ",dcm_speed_2)
                                        dcm.setPWMAY(dcm_speed_2)
                                        dcm.setPWMBY(dcm_speed_2)
                                        dcm_last_known_speed_y=dcm_speed_2 # update last known speed value to the updated one

                                    # else if speed is 4, slow down to 3
                                    elif dcm_last_known_speed_y == dcm_speed_4:
                                        print("Slowing Down Turning Speed to: ",dcm_speed_3)
                                        dcm.setPWMAY(dcm_speed_3)
                                        dcm.setPWMBY(dcm_speed_3)
                                        dcm_last_known_speed_y=dcm_speed_3 # update last known speed value to the updated one

                                    # else if speed is 5, slow down to 4
                                    elif dcm_last_known_speed_y == dcm_speed_5:
                                        print("Slowing Down Turning Speed to: ",dcm_speed_4)
                                        dcm.setPWMAY(dcm_speed_4)
                                        dcm.setPWMBY(dcm_speed_4)
                                        dcm_last_known_speed_y=dcm_speed_4 # update last known speed value to the updated one
                                    
                                ## SPEED UP (top left trigger)
                                elif button == "tr":

                                    print ("Top Right Trigger Pushed... Increasing Speed now...")

                                    # if speed is 0, speed up to 1..
                                    if dcm_last_known_speed_y == dcm_speed_0:
                                        print("Speeding Up Turning Speed to: ",dcm_speed_1)
                                        dcm.setPWMAY(dcm_speed_1)
                                        dcm.setPWMBY(dcm_speed_1)
                                        dcm_last_known_speed_y=dcm_speed_1 # update last known speed value to the updated one

                                    # else if speed is 1, speed up to 2
                                    elif dcm_last_known_speed_y == dcm_speed_1:
                                        print("Speeding Up Turning Speed to: ",dcm_speed_2)
                                        dcm.setPWMAY(dcm_speed_2)
                                        dcm.setPWMBY(dcm_speed_2)
                                        dcm_last_known_speed_y=dcm_speed_2 # update last known speed value to the updated one

                                    # else if speed is 2, speed up to 3
                                    elif dcm_last_known_speed_y == dcm_speed_2:
                                        print("Speeding Up Turning Speed to: ",dcm_speed_3)
                                        dcm.setPWMAY(dcm_speed_3)
                                        dcm.setPWMBY(dcm_speed_3)
                                        dcm_last_known_speed_y=dcm_speed_3 # update last known speed value to the updated one

                                    # else if speed is 3, speed up to 4
                                    elif dcm_last_known_speed_y == dcm_speed_3:
                                        print("Speeding Up Turning Speed to: ",dcm_speed_4)
                                        dcm.setPWMAY(dcm_speed_4)
                                        dcm.setPWMBY(dcm_speed_4)
                                        dcm_last_known_speed_y=dcm_speed_4 # update last known speed value to the updated one

                                    # else if speed is 4, speed up to 5
                                    elif dcm_last_known_speed_y == dcm_speed_4:
                                        print("Speeding Up Turning Speed to: ",dcm_speed_5)
                                        dcm.setPWMAY(dcm_speed_5)
                                        dcm.setPWMBY(dcm_speed_5)
                                        dcm_last_known_speed_y=dcm_speed_5 # update last known speed value to the updated one

                                    # else if speed is 5, this is our max, so we wont go any higher...
                                    elif dcm_last_known_speed_y == dcm_speed_5:
                                        print("Speed is already 5, we cant go any higher bro... Maybe consider making a 'Temp Power Boost' function using a different button... L3 maybe? ;)")
                                        
                            else:
                                print(("%s released" % (button))) # this gets fired EVERYTIME a button is "released"
                                        
                    if type & 0x02:
                        axis = axis_map[number]
                        if axis:
                            fvalue = value / 32767.0
                            axis_states[axis] = fvalue
                            if self.DEBUG==True:
                                print(("%s: %.3f" % (axis, fvalue)))

                            ####################################
                            # LEFT ANALOGUE | DC MOTOR CONTROL #
                            ####################################
                            
                            ## forward
                            if axis == "y" and fvalue < ndz:
                                dcm.forward()
                                if self.DEBUG==True:
                                    print("Moving Forward...")
                            elif axis == "y" and fvalue == 0:
                                dcm.stop()
                                if self.DEBUG==True:
                                    print("Stopping...")

                            ## backward
                            elif axis == "y" and fvalue > pdz:
                                dcm.backward()
                                if self.DEBUG==True:
                                    print("Moving Backward...")
                            elif axis == "y" and fvalue == 0:
                                dcm.stop()
                                if self.DEBUG==True:
                                    print("Stopping...")

                            ## left
                            elif axis == "x" and fvalue < ndz:
                                dcm.left()
                                if self.DEBUG==True:
                                    print("Turning Left")
                            elif axis == "x" and fvalue == 0:
                                dcm.stop()
                                if self.DEBUG==True:
                                    print("Stopping...")
                                
                            ## right
                            elif axis == "x" and fvalue > pdz:
                                dcm.right()
                                if self.DEBUG==True:
                                    print("Turning Right")
                            elif axis == "x" and fvalue == 0:
                                dcm.stop()
                                if self.DEBUG==True:
                                    print("Stopping...")

                            ########################################
                            # RIGHT ANALOGUE | SERVO MOTOR CONTROL #
                            ########################################

                            ## up
                            if axis == "ry" and fvalue > pdz:
                                if vslv > sspa and vslv <= sspb: #make sure we are between a reasonable range
                                    vslv=vslv-sss # decrement our servo pulse
                                    if self.DEBUG==True:
                                        print("Panning Servo Up...")
                                        print("vslv:",vslv)
                                    pwm.setServoPulse(1,vslv)
                                    
                            ## down
                            elif axis == "ry" and fvalue < ndz:
                                if vslv >= sspa and vslv < sspb: #make sure we are between a reasonable range
                                    vslv=vslv+sss # increment our servo pulse
                                    if self.DEBUG==True:
                                        print("Panning Servo Down...")
                                        print("vslv:",vslv)
                                    pwm.setServoPulse(1,vslv)

                            ## left
                            elif axis == "rx" and fvalue < ndz:
                                if hslv >= sspa and hslv < sspb: #make sure we are between a reasonable range
                                    hslv=hslv+sss # decrement our servo pulse
                                    if self.DEBUG==True:
                                        print("Panning Servo Left...")
                                        print("hslv:",hslv)
                                    pwm.setServoPulse(0,hslv)
                                
                            ## right
                            elif axis == "rx" and fvalue > pdz:
                                if hslv > sspa and hslv <= sspb: #make sure we are between a reasonable range
                                    hslv=hslv-sss # increment our servo pulse
                                    if self.DEBUG==True:
                                        print("Panning Servo Right...")
                                        print("hslv:",hslv)
                                    pwm.setServoPulse(0,hslv)

                            ############################################################
                            # HAT DIRECTIONAL BUTTONS | DC MOTOR TURNING SPEED CONTROL #
                            ############################################################

                            ### DOWN BUTTON
                            ## SLOW DOWN
                            if axis == "hat0y" and fvalue == 1:

                                print("hat0y (UP) Pushed...")
                                
                                # if speed is zero, do nothing... cant slow down any more than that can we..
                                if dcm_last_known_speed_x == dcm_speed_0:
                                    print("Speed is already 0, we cant go any lower bro...")

                                # else if speed is 1, slow down to 0
                                elif dcm_last_known_speed_x == dcm_speed_1:
                                    print("Slowing Down Turning Speed to: ",dcm_speed_0)
                                    dcm.setPWMAX(dcm_speed_0)
                                    dcm.setPWMBX(dcm_speed_0)
                                    dcm_last_known_speed_x=dcm_speed_0 # update last known speed value to the updated one

                                # else if speed is 2, slow down to 1
                                elif dcm_last_known_speed_x == dcm_speed_2:
                                    print("Slowing Down Turning Speed to: ",dcm_speed_1)
                                    dcm.setPWMAX(dcm_speed_1)
                                    dcm.setPWMBX(dcm_speed_1)
                                    dcm_last_known_speed_x=dcm_speed_1 # update last known speed value to the updated one

                                # else if speed is 3, slow down to 2
                                elif dcm_last_known_speed_x == dcm_speed_3:
                                    print("Slowing Down Turning Speed to: ",dcm_speed_2)
                                    dcm.setPWMAX(dcm_speed_2)
                                    dcm.setPWMBX(dcm_speed_2)
                                    dcm_last_known_speed_x=dcm_speed_2 # update last known speed value to the updated one

                                # else if speed is 4, slow down to 3
                                elif dcm_last_known_speed_x == dcm_speed_4:
                                    print("Slowing Down Turning Speed to: ",dcm_speed_3)
                                    dcm.setPWMAX(dcm_speed_3)
                                    dcm.setPWMBX(dcm_speed_3)
                                    dcm_last_known_speed_x=dcm_speed_3 # update last known speed value to the updated one

                                # else if speed is 5, slow down to 4
                                elif dcm_last_known_speed_x == dcm_speed_5:
                                    print("Slowing Down Turning Speed to: ",dcm_speed_4)
                                    dcm.setPWMAX(dcm_speed_4)
                                    dcm.setPWMBX(dcm_speed_4)
                                    dcm_last_known_speed_x=dcm_speed_4 # update last known speed value to the updated one

                            
                            ### UP BUTTON
                            ## SPEED UP
                            elif axis == "hat0y" and fvalue == -1:

                                print ("hat0y (DOWN) Pushed... Increasing Speed now...")

                                # if speed is 0, speed up to 1..
                                if dcm_last_known_speed_x == dcm_speed_0:
                                    print("Speeding Up Turning Speed to: ",dcm_speed_1)
                                    dcm.setPWMAX(dcm_speed_1)
                                    dcm.setPWMBX(dcm_speed_1)
                                    dcm_last_known_speed_x=dcm_speed_1 # update last known speed value to the updated one

                                # else if speed is 1, speed up to 2
                                elif dcm_last_known_speed_x == dcm_speed_1:
                                    print("Speeding Up Turning Speed to: ",dcm_speed_2)
                                    dcm.setPWMAX(dcm_speed_2)
                                    dcm.setPWMBX(dcm_speed_2)
                                    dcm_last_known_speed_x=dcm_speed_2 # update last known speed value to the updated one

                                # else if speed is 2, speed up to 3
                                elif dcm_last_known_speed_x == dcm_speed_2:
                                    print("Speeding Up Turning Speed to: ",dcm_speed_3)
                                    dcm.setPWMAX(dcm_speed_3)
                                    dcm.setPWMBX(dcm_speed_3)
                                    dcm_last_known_speed_x=dcm_speed_3 # update last known speed value to the updated one

                                # else if speed is 3, speed up to 4
                                elif dcm_last_known_speed_x == dcm_speed_3:
                                    print("Speeding Up Turning Speed to: ",dcm_speed_4)
                                    dcm.setPWMAX(dcm_speed_4)
                                    dcm.setPWMBX(dcm_speed_4)
                                    dcm_last_known_speed_x=dcm_speed_4 # update last known speed value to the updated one

                                # else if speed is 4, speed up to 5
                                elif dcm_last_known_speed_x == dcm_speed_4:
                                    print("Speeding Up Turning Speed to: ",dcm_speed_5)
                                    dcm.setPWMAX(dcm_speed_5)
                                    dcm.setPWMBX(dcm_speed_5)
                                    dcm_last_known_speed_x=dcm_speed_5 # update last known speed value to the updated one

                                # else if speed is 5, this is our max, so we wont go any higher...
                                elif dcm_last_known_speed_x == dcm_speed_5:
                                    print("Speed is already 5, we cant go any higher bro... Maybe consider making a 'Temp Power Boost' function using a different button... L3 maybe? ;)")
                                
                            
        except KeyboardInterrupt:
            print("Program stopped by user...")

        except Exception:
            traceback.print_exc()
            
        finally:
            if self.DEBUG==True:
                print("Setup process complete")
Exemplo n.º 17
0
import RPi.GPIO as GPIO
import time
from flask_socketio import SocketIO, send, emit
from Led import Led
from Buzzer import Buzzer

# //Initialisation de notre GPIO 17 pour recevoir un signal
# //Contrairement à nos LEDs avec lesquelles on envoyait un signal

lightblue = Led(24)
lightred = Led(18)
buzzer = Buzzer(22)


class Mouvement():
    def __init__(self, broche):
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        self.broche = broche
        GPIO.setup(broche, GPIO.IN)

    def mouvement_loop(self, socketio):
        currentstate = 0
        previousstate = 0
        lightblue.on()
        while True:
            currentstate = GPIO.input(self.broche)
            if currentstate == 1 and previousstate == 0:
                previousstate = 1
                lightblue.off()
                lightred.light_blink()
Exemplo n.º 18
0
class Buttons:
    # button 4
    button4 = Button(14)

    # button 3
    button3 = Button(15)

    # button 2
    button2 = Button(18)

    # button 1
    button1 = Button(23)

    mode = "view"

    alarm = None

    prev_pushed = -1
    screen = None

    sound = Buzzer()

    alarm_puzzle = None

    cur_time = None

    def __init__(self):
        self.cur_time = Time.Time()

        self.screen = SevenSegDriver.SevenSegDrive(
            TimeToArray.time_to_array(self.cur_time.get_time()))

        self.cur_time.subscribe_to_time_change(self.screen)

        self.make_alarm()

        self.mode = "view"

        t = Thread(target=self.poll_buttons())
        t.start()

    def make_alarm(self):
        cur_time_e = self.cur_time.get_time().time()
        alarm_time = datetime.time(cur_time_e.hour,
                                   (cur_time_e.minute + 1) % 60, 0)

        print("New Alarm for ", alarm_time)

        if self.alarm is not None:
            self.alarm.unsubscribe(self)

        self.alarm = Alarm.Alarm(alarm_time)
        self.alarm.willRing = True

        self.alarm_puzzle = AlarmPuzzle.alarm_puzzle()

        self.alarm.subscribe(self)

        self.cur_time.subscribe_to_time_change(self.alarm)

    def notify(self, alarm):
        pass
        print("mode is alarm now")
        self.mode = "alarm"
        self.screen.set_mode("alarm", self.alarm_puzzle)

    def poll_buttons(self):
        while True:
            time.sleep(.1)

            if self.mode == "alarm":
                if self.sound.sound is True and self.sound.buzzing is False:
                    self.sound.start()

                # self.screen.set_mode("alarm", self.alarm_puzzle)

                if self.button1.is_pressed:
                    if self.prev_pushed != 1:
                        self.alarm_puzzle.input(1)
                        self.prev_pushed = 1
                        print("1")
                elif self.button2.is_pressed:
                    if self.prev_pushed != 2:
                        self.alarm_puzzle.input(2)
                        self.prev_pushed = 2
                        print("2")
                elif self.button3.is_pressed:
                    if self.prev_pushed != 3:
                        self.alarm_puzzle.input(3)
                        self.prev_pushed = 3
                        print("3")
                elif self.button4.is_pressed:
                    if self.prev_pushed != 4:
                        self.alarm_puzzle.input(4)
                        self.prev_pushed = 4
                        print("4")
                else:
                    self.prev_pushed = -1

                if self.alarm_puzzle.is_solved():
                    self.mode = "view"
                    self.screen.mode = "view"

            if self.mode is "view":
                self.sound.stop()
                if not (self.button1.is_pressed and self.button2.is_pressed):
                    if self.button1.is_pressed:
                        # self.mode = 'change_time'
                        self.make_alarm()
                        print("Button 1 view mode")

                    if self.button2.is_pressed:
                        # self.mode = 'change_alarm'
                        print("Button 2 view mode")
Exemplo n.º 19
0
 def __init__(self):
     self.fire_detected = False
     self.buzzer = Buzzer()
     self.adc = MCP3008()
Exemplo n.º 20
0
    HAND_APPROVED = 1
    HAND_DENIED = 0
    NOT_HAND = 2
    MAX_PEOPLE = 2

    restart_button = 40
    gpio.setmode(gpio.BOARD)
    gpio.setup(restart_button, gpio.IN, pull_up_down=gpio.PUD_UP)
    gpio.add_event_detect(restart_button,
                          gpio.RISING,
                          callback=restart,
                          bouncetime=200)

    ExitHR = ExitHandReader.ExitHandReader(32, 31)
    print("Exit Hand Reader Initialized!")

    door = Door()
    print("Door Initialized!")
    B = Buzzer(33)
    print("Buzzer Initialized!")
    PC = PeopleCounter.PeopleCounter(23, 24, 21, 22, func=door.close)
    print("People Counter Initialized!")
    EntryHR = OuterHandReader.OHandReader(12, 18, 1, _get_state=PC._get_state)
    print("Entry Hand Reader Initialized!")
    MD = MaskDetector.MaskDetector(headless=False)
    print("Mask Detector Initialized!")
    opsign = sign.sign()

    main()
Exemplo n.º 21
0
if __name__ == "__main__":
    now_Thread = 0
    flags = [False, False, False, False, False, False, False, False, False]
    thread_flags = [False, False, False, False, False]
    GPIO.cleanup()
    sensing_Rover = Sensing_Rover()

    pcf8591 = Pcf8591(0x48)
    gas = Gas(pcf8591, ain=2)
    thermister = Thermistor(pcf8591, ain=1)
    tracking = Tracking(32)
    photoresister = Photoresister(pcf8591, ain=0)
    ultra = HcSr04(trigpin=38, echopin=40)
    queue = queue.Queue()
    rgbLed = RgbLed(16, 18, 22)
    buzzer = Buzzer(35)
    laser = Laser(37)
    lcd = Lcd1602(0x27)

    pca9685 = Pca9685()
    dc_left = DC(11, 12, pca9685)
    dc_right = DC(13, 15, pca9685)
    channel_left = 5
    channel_right = 4
    set_speed = 80

    sv = Sg90(pca9685, 0)  # 5~90도   (default = 12도, 줄어들면 LOWER, 커지면 HIGHER)
    sh = Sg90(pca9685, 1)  # 12~170도   (default = 90도, 줄어들면 RIGHT, 커지면 LEFT)
    sw = Sg90(pca9685, 14)  # 50~130도   (default = 90도, 줄어들면 LEFT, 커지면 RIGHT)
    su = Sg90(pca9685, 15)  # 40~120도   (default = 80도, 줄어들면 RIGHT, 커지면 LEFT)
Exemplo n.º 22
0
#----------------------------
# Imported Modules
#----------------------------
import gesture as ges
from OLED import OLED
from Buzzer import Buzzer
import time

#----------------------------
# Globals
#----------------------------
ledHeader = "getFlag();\n"
display = OLED()
audio = Buzzer()
display.clear()
display.resetCursor()
display.write(ledHeader)
audio.connected()
time.sleep(1)
#----------------------------
# Print Initialization to LED
#----------------------------
buzz = [0]
buzzfinal = [4]
microsec = [16]
for i in range(0, 3):
    message = ledHeader + "Starting\n\t\t\t" + str(3 - i)
    display.clear()
    display.resetCursor()
    display.write(message)
    audio.play(buzz, microsec)