Example #1
0
    def __init__(self):
        if env == "prod":

            log.debug("Using %s configuration" % self.CONTROLLER_BOARD)

            self.SERVO_H = AngularServo(self.HEAD_HORIZONTAL_PIN,
                                        min_angle=-80,
                                        max_angle=80)
            self.SERVO_V = AngularServo(self.HEAD_VERTICAL_PIN,
                                        min_angle=-80,
                                        max_angle=80)

            ##Digital devices
            self.forward_left_device = None
            self.forward_right_device = None
            self.backward_left_device = None
            self.backward_right_device = None

            self.wheel_right_step = None
            self.wheel_left_step = None
            self.wheel_right_heading = None
            self.wheel_left_heading = None
            self.wheel_right_enabled = None
            self.wheel_left_enabled = None

            self.pwm_left = None
            self.pwm_right = None

            if self.CONTROLLER_BOARD == "v1":
                self.forward_left_device = DigitalOutputDevice(
                    self.FORWARD_LEFT_PIN, True, False)
                self.forward_right_device = DigitalOutputDevice(
                    self.FORWARD_RIGHT_PIN, True, False)
                self.backward_left_device = DigitalOutputDevice(
                    self.BACKWARD_LEFT_PIN, True, False)
                self.backward_right_device = DigitalOutputDevice(
                    self.BACKWARD_RIGHT_PIN, True, False)
                self.pwm_left = PWMOutputDevice(self.PWM_LEFT_PIN, True, False,
                                                self.FRECUENCY)
                self.pwm_right = PWMOutputDevice(self.PWM_RIGHT_PIN, True,
                                                 False, self.FRECUENCY)

            if self.CONTROLLER_BOARD == "v2":
                self.wheel_right_step = DigitalOutputDevice(
                    self.WHEEL_RIGHT_STEP, True, False)
                self.wheel_left_step = DigitalOutputDevice(
                    self.WHEEL_LEFT_STEP, True, False)
                self.wheel_right_heading = DigitalOutputDevice(
                    self.WHEEL_RIGHT_HEADING, True, False)
                self.wheel_left_heading = DigitalOutputDevice(
                    self.WHEEL_LEFT_HEADING, True, False)
                self.wheel_right_enabled = DigitalOutputDevice(
                    self.WHEEL_RIGHT_ENABLED, True, False)
                self.wheel_left_enabled = DigitalOutputDevice(
                    self.WHEEL_LEFT_ENABLED, True, False)

        self.current_horizontal_head_pos = 0
        self.current_vertical_head_pos = 0
        self.center_head()
        self._counting_steps = 0
        self._current_steps = 0
        self._stepper_current_step = 0
Example #2
0
        def __init__(self):
                self.GPIO_led_R1 = 14
                self.GPIO_led_Y1 = 15
                self.GPIO_led_G1 = 4
                self.GPIO_led_B1 = 17
                self.GPIO_btn_B1 = 18
                self.MTR_pump1 = 1
                
                self.GPIO_wtr_tgd = 21
                self.GPIO_wtr_t01 = 20
                self.GPIO_wtr_t02 = 19
                self.GPIO_wtr_t03 = 16
                self.GPIO_wtr_t04 = 13
                self.GPIO_wtr_t05 = 12
                self.GPIO_wtr_t06 = 6
                self.GPIO_wtr_t07 = 5
                self.GPIO_wtr_t08 = 7
                self.GPIO_wtr_t09 = 8
                self.GPIO_wtr_t10 = 11
                self.GPIO_wtr_t11 = 9
                self.GPIO_wtr_t12 = 10
                self.GPIO_wtr_t13 = 25
                
                self.GPIO_wtr_pgd = 22
                self.GPIO_wtr_p01 = 23
                
                # Setup the water level indicator
#                self.wtrLevel = LEDBarGraph(self.GPIO_led_R1, self.GPIO_led_Y1, self.GPIO_led_G1, pwm=True)
                
                # Setup the Pump Water Level Sensor
                # _pumpWtrLevelGnd should remain ON the entire time
                self._pumpWtrLevelGnd = DigitalOutputDevice(self.GPIO_wtr_pgd, True, True)
                self.pumpWtrLevel = DigitalInputDevice(self.GPIO_wtr_p01)
                
                # Setup the tree water level indicator
                # _treeWtrLevelGnd should remain ON the entire time
                self._treeWtrLevelGnd = DigitalOutputDevice(self.GPIO_wtr_tgd, True, True)

                self.treeWtrLevel01 = DigitalInputDevice(self.GPIO_wtr_t01)
                self.treeWtrLevel02 = DigitalInputDevice(self.GPIO_wtr_t02)
                self.treeWtrLevel03 = DigitalInputDevice(self.GPIO_wtr_t03)
                self.treeWtrLevel04 = DigitalInputDevice(self.GPIO_wtr_t04)
                self.treeWtrLevel05 = DigitalInputDevice(self.GPIO_wtr_t05)
                self.treeWtrLevel06 = DigitalInputDevice(self.GPIO_wtr_t06)
                self.treeWtrLevel07 = DigitalInputDevice(self.GPIO_wtr_t07)
                self.treeWtrLevel08 = DigitalInputDevice(self.GPIO_wtr_t08)
                self.treeWtrLevel09 = DigitalInputDevice(self.GPIO_wtr_t09)
                self.treeWtrLevel10 = DigitalInputDevice(self.GPIO_wtr_t10)
                self.treeWtrLevel11 = DigitalInputDevice(self.GPIO_wtr_t11)
                self.treeWtrLevel12 = DigitalInputDevice(self.GPIO_wtr_t12)
                self.treeWtrLevel13 = DigitalInputDevice(self.GPIO_wtr_t13)
                
                # Setup the pump status indicator and manual override button
                self.pumpStsLED = LED(self.GPIO_led_B1)
                self.pumpBtn = Button(self.GPIO_btn_B1, True)
                
                # create a default object, no changes to I2C address or frequency
                self.mtrHat = Adafruit_MotorHAT(addr=0x60)
                
                self.pump = self.mtrHat.getMotor(self.MTR_pump1)
                
                # We should always run at max speed
                self.pump.setSpeed(255)
                
                self.pumpSts = False
Example #3
0
#!/usr/bin/env python3

import datetime as dt
import time

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()
Example #4
0
from gpiozero import DigitalOutputDevice, InputDevice, LED, Buzzer
from time import sleep

leds = { "green": LED(13), "red": LED(12) }
for led in leds:
    leds[led].off()

orange = { "tx": DigitalOutputDevice(26), "rx": InputDevice(20) }

buzzer = Buzzer(24)

try:
    orange["tx"].value = 1
    while True:
        leds["green"].value = orange["rx"].value
        leds["red"].value = not orange["rx"].value
        buzzer.value = not orange["rx"].value
        print(orange["rx"].value)
        sleep(.3)
except KeyboardInterrupt:
    print("bye")
    buzzer.off()
    for led in leds:
        leds[led].off()
        
Example #5
0
from gpiozero import PWMOutputDevice
from gpiozero import DigitalOutputDevice
import time

PWM_DRIVE_A = 21  # ENA - H-Bridge enable pin
FORWARD_A_PIN = 26  # IN1 - Forward Drive
REVERSE_A_PIN = 19  # IN2 - Reverse Drive

motorA = PWMOutputDevice(PWM_DRIVE_A, True, 0, 1000)

forwardA = DigitalOutputDevice(FORWARD_A_PIN)
reverseA = DigitalOutputDevice(REVERSE_A_PIN)


def forward():
    forwardA.value = True
    reverseA.value = False
    motorA = 0.5


def reverse():
    reverseA.value = True
    forwardA.value = False
    motorA = 0.5


if __name__ == "__main__":
    while True:
        forward()
        time.sleep(5)
        reverse()
Example #6
0
	def __init__(self,gpio):
		self.output=DigitalOutputDevice(gpio)
Example #7
0
button_2_4 = Button(pin=pin_button_2_4,
                    pull_up=None,
                    active_state=True,
                    bounce_time=debounce)
button_2_5_0 = Button(pin=pin_button_2_5_0,
                      pull_up=None,
                      active_state=True,
                      bounce_time=debounce)
button_2_5_1 = Button(pin=pin_button_2_5_1,
                      pull_up=None,
                      active_state=True,
                      bounce_time=debounce)

#Definieren der Objecte des ersten Relai Moduls
relai_1_1 = DigitalOutputDevice(pin=pin_relai_1_1,
                                active_high=True,
                                initial_value=False,
                                pin_factory=None)
relai_1_2 = DigitalOutputDevice(pin=pin_relai_1_2,
                                active_high=True,
                                initial_value=False,
                                pin_factory=None)
relai_1_3 = DigitalOutputDevice(pin=pin_relai_1_3,
                                active_high=True,
                                initial_value=False,
                                pin_factory=None)
relai_1_4 = DigitalOutputDevice(pin=pin_relai_1_4,
                                active_high=True,
                                initial_value=False,
                                pin_factory=None)

#Definieren der Objecte des ersten Relai Moduls
 def __init__(self, trigger_pin, echo_pin):
     # Setup devices, an input device and an output device, with pin numbers for the sensor.
     self._trigger = DigitalOutputDevice(trigger_pin)
     self._trigger.value = False
     self._echo = DigitalInputDevice(echo_pin)
Example #9
0
GPIO pin numbers, NOT actual pin number!! (i.e.
GPIO 26 = pin 37
GPIO 19 = pin 35
GPIO 13 = pin 33
GPIO  6 = pin 31
)

#--------------------------------------------#
'''
from lidar_lite import Lidar_Lite
from time import sleep
from gpiozero import DigitalOutputDevice
from threading import Thread

lidarController = [
    DigitalOutputDevice(26),
    DigitalOutputDevice(19),
    DigitalOutputDevice(13),
    DigitalOutputDevice(6)
]

#numbers gathered from experimental data
floorValue = [72, 38, 43, 33]

detectObjects = [False, False, False, False]

offset = 25

lidar = Lidar_Lite()

connected = lidar.connect(1)
Example #10
0
from gpiozero import DigitalOutputDevice
from time import sleep

serial_pin = 22
serial_clock_pin = 23
register_clock_pin = 24

serial_out = DigitalOutputDevice(serial_pin)
serial_clock = DigitalOutputDevice(serial_clock_pin)
register_clock = DigitalOutputDevice(register_clock_pin)

number_values = [
    0b11111100, 0b01100000, 0b11011010, 0b11110010, 0b01100110, 0b10110110,
    0b10111110, 0b11100000, 0b11111110, 0b11110110
]


def shift_bit(bit_value):
    serial_out.value = bit_value
    serial_clock.on()
    sleep(0.001)
    serial_clock.off()


def register_update():
    register_clock.on()
    sleep(0.001)
    register_clock.off()


def shift_byte(byte_value, update=True):
Example #11
0
 def __init__(self, forward, backward, pwm):
     // Disse er inn signalene til h-blokken
     self.forward = DigitalOutputDevice(forward)
     self.backward = DigitalOutputDevice(backward)
     self.pwm = PWMOutputDevice(pwm, True, 0, 1000)
Example #12
0
pwmPin = [14, 23, 25, 1]
dirPin = [15, 24, 8, 7]
f = 5000

if len(sys.argv) == 1:
    print("Berikan arah, speed dan lamanya (detik)")
    sys.exit(-1)

speed = float(sys.argv[2])
arah = int(sys.argv[1])
lama = int(sys.argv[3])

zf = list()
pwm = list()

print("Keempat motor dijalankan selama", lama, "detik dengan kecepatan", speed,
      "%")

for i in range(4):
    zf.append(DigitalOutputDevice(dirPin[i], initial_value=arah))
    pwm.append(PWMOutputDevice(pwmPin[i], initial_value=speed, frequency=f))

sleep(lama)

for i in range(4):
    zf[i].close()
    pwm[i].close()

print("Done...!")
Example #13
0
 def __init__(self, halfid, pin):
     self.halfid = halfid
     self.pin = DigitalOutputDevice(pin)
     self.pinnum = pin
     self.off()
     self.state = False
Example #14
0
from gpiozero import DigitalInputDevice, DigitalOutputDevice
from time import sleep

led_pin = DigitalOutputDevice(7)
button_pin = DigitalInputDevice(23, pull_up=True)

while True:
    print(button_pin.value)

    if button_pin.value == 1:
        led_pin.on()
    else:
        led_pin.off()

    sleep(0.1)
Example #15
0
 def __init__(self):
     self.motor_escape = DigitalOutputDevice(pin=pin_fig.escape_relayswitch)
Example #16
0
#  Press RESET
#    To reboot current game
#	 No change on LED status
#  Hold RESET for 3 seconds
#    To quit current game
#	 LED will BLINK

import RPi.GPIO as GPIO
import time
import os
import socket
from gpiozero import Button, DigitalOutputDevice, LED

resetButton = 2
powerButton = Button(3)
fan = DigitalOutputDevice(4)
led = LED(14)
hold = 2
rebootBtn = Button(resetButton, hold_time=hold)

GPIO.setmode(GPIO.BCM)  # use GPIO numbering
GPIO.setup(resetButton, GPIO.IN, pull_up_down=GPIO.PUD_UP)


#Get CPU Temperature
def getCPUtemp():
    res = os.popen('vcgencmd measure_temp').readline()
    return (res.replace("temp=", "").replace("'C\n", ""))


def retroPiCmd(message):
Example #17
0
                        counter = 0

                except KeyboardInterrupt:
                    print('Interrupted by user')
                    return 1

                except Exception as e:
                    print(str(e))
                    pass


if __name__ == "__main__":
    t_start = time.time()

    # GPIO 17
    hardware_trigger = DigitalOutputDevice(17)
    hardware_trigger.on()

    # GPIO 22
    status_led = DigitalOutputDevice(22)
    status_led.off()

    print('Reading the dbc file ...')
    path = os.path.dirname(os.path.abspath(__file__))
    ICAN_db = cantools.database.load_file(
        os.path.join(
            path, 'MLBevo_Gen2_MLBevo_ICAN_KMatrix_V8.19.05F_20200420_AM.dbc'))
    ECAN_db = cantools.database.load_file(
        os.path.join(
            path,
            'MLBevo_Gen2_MLBevo_ECAN_KMatrix_V8.15.00F_20171109_SE_RDK_merged.dbc'
    if platform.system() == "Windows":

        def simulate():
            print("Running on Windows - Mock Pins generated")
            pin1 = Device.pin_factory.pin(pin_input_1)
            while 1:
                pin1.drive_high()
                sleep(0.01)
                pin1.drive_low()
                sleep(0.99)

        simulator = Thread(target=simulate)
        simulator.start()

    outRel1 = DigitalOutputDevice(pin_relay_1,
                                  active_high=True,
                                  initial_value=False)
    outRel2 = DigitalOutputDevice(pin_relay_2,
                                  active_high=True,
                                  initial_value=False)
    outRel3 = DigitalOutputDevice(pin_relay_3,
                                  active_high=True,
                                  initial_value=False)

    class InOutStatus:
        input1 = 0
        input2 = 0
        input3 = 0
        rel1 = 0
        rel2 = 0
        rel3 = 0
Example #19
0
    def __init__(self,
                 name,
                 channels,
                 calibration,
                 busy,
                 tasks,
                 results,
                 info,
                 power_switch=-1,
                 power_delay=0,
                 daemon=True):
        """Initialize the worker thread.

        Note: calling __init__ does not start the thread, a subsequent call to
        start() is needed to start the thread.

        :param name: a descriptive name for the spectrometer.
        :type name: str
        :param channels: the list of channels
        :param busy: a "lock" which prevents using the spectrometer when it is busy
        :type busy: thread.lock
        :param tasks: a queue into which tasks will be put
        :type tasks: Queue.Queue
        :param results: the results queue from where results will be collected
        :type results: Queue.Queue
        :param info: queue for reporting back info
        :type info: Queue.Queue
        :param power_switch: power switch number, -1 to disable power switch
        :param power_delay: delay powering on by power_delay seconds, default 0
        """

        super().__init__('spectrometer_worker.{}'.format(name),
                         busy,
                         tasks,
                         results,
                         info,
                         daemon=daemon)

        self._serial = name

        # set to true to create dummy spectra
        self._dummy_spectra = False

        # power control
        self._power_switch = None
        if power_switch > -1:
            if DigitalOutputDevice is None:
                self.log.error('gpio output device is not available')
            else:
                self._power_switch = DigitalOutputDevice(power_switch)

        self._power_delay = power_delay

        # the integration times
        self._currentIntegrationTime = {}
        self._auto = {}
        self._channels = channels
        self._calibration = calibration
        for c in self.channels:
            self._currentIntegrationTime[c] = None
            self._auto[c] = None

        self._haveTEC = None

        self._meta = None

        self._maxIntegrationTime = None
        self._minIntegrationTime = None

        self._spec = None
        self._status = None
        self.status = PiccoloSpectrometerStatus.DISCONNECTED
        if self.power_switch is not None and self.power_switch.value == 1:
            self.status = PiccoloSpectrometerStatus.POWERED_OFF

        self.minIntegrationTime = 0
        self.maxIntegrationTime = 10000
        for c in self.channels:
            self.set_currentIntegrationTime(c, self.minIntegrationTime)
            self.set_auto(c, 'n')
Example #20
0
# 10_proximity.py
# From the code for the Box 1 kit for the Raspberry Pi by MonkMakes.com

from gpiozero import DigitalOutputDevice, LED, Button
import time

# This project uses the Capsense technique modelled on this:
# http://playground.arduino.cc/Main/CapacitiveSensor

threshold = 0

# setup the pin modes
send_pin = DigitalOutputDevice(18)
sense_pin = Button(23, pull_up=None, active_state=True)
red_led = LED(24)
send_pin.on()


# return the time taken for the sense pin to flip state as a result of
# the capcitatve effect of being near the sense pin
def step():
    send_pin.off()
    t1 = time.time()
    while sense_pin.value:
        pass
    t2 = time.time()
    time.sleep(0.1)
    send_pin.on()
    time.sleep(0.1)
    return (t2 - t1) * 1000000
Example #21
0
from gpiozero import Servo, DigitalOutputDevice
from xbox import XboxController
from sys import platform
'''Checks platform type, used to achieve different functionality on windows vs pi.'''
WINDOWS = platform == 'win32'
'''Set up gpio outputs if actually on a pi'''
if not WINDOWS:
    motors = {
        'left_drive': Servo(pin='WPI30'),
        'right_drive': Servo(pin='WPI21'),
        'dart': Servo(pin='WPI22'),
        'left_shooter': Servo(pin='WPI23'),
        'right_shooter': Servo(pin='WPI24')
    }

    solenoids = {'kicker': DigitalOutputDevice(pin='WPI25')}


def clamp(value, min_val, max_val):
    """
    Clamps a number between a min and a max value.

    :param value: the value to be clamped
    :param min_val: the minimum
    :param max_val: the maximum
    :return the clamped value
    """
    return max(min(value, max_val), min_val)


def arcade_drive(controller, drive_scale=0.6, debug=False):
Example #22
0
 
Split male PWR+ PWR- RST+ RST- to 2 female connectors,
so that they can be controlled by relays and regular buttons.
"""

from flask import Flask, request
from gpiozero import DigitalOutputDevice
from time import sleep



app = Flask(__name__)
secret = 'somesecret'

# pin numbering: use GPIOXX number instead of board pin number
relayBoot = DigitalOutputDevice(17, active_high=False, initial_value=False) # board pin number 11
relayReboot = DigitalOutputDevice(27, active_high=False, initial_value=False) # 13

@app.route('/')
def hello_world():
    return 'Hello, World!'

@app.route('/boot')
def boot():
    inputSecret = request.args.get('secret')
    if inputSecret == secret:
        relayBoot.on()
        sleep(0.3)
        relayBoot.off()
        return "OK"
    else:
Example #23
0
from gpiozero import DigitalOutputDevice
from gpiozero import PWMOutputDevice

#System
from time import sleep
from signal import pause
from random import randrange

#bluetooth
from bluetooth import *

#Custom Imports
import MoveConstants

#Setup pins
backward = DigitalOutputDevice(MoveConstants.GPIO_BACKWARD_PIN)
frontward = DigitalOutputDevice(MoveConstants.GPIO_FORWARD_PIN)
motor = PWMOutputDevice(MoveConstants.GPIO_MOTOR_PIN)

#Setup BT server
server_sock = BluetoothSocket(RFCOMM)
server_sock.bind(("", PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service(
    server_sock,
    "SampleServer",
Example #24
0
from gpiozero import DigitalOutputDevice
from time import sleep

pinAred = DigitalOutputDevice(17)
pinByellow = DigitalOutputDevice(27)
pinCgreen = DigitalOutputDevice(22)
pinDblack = DigitalOutputDevice(23)

pinEred = DigitalOutputDevice(13)
pinFyellow = DigitalOutputDevice(6)
pinGgreen = DigitalOutputDevice(5)
pinHblack = DigitalOutputDevice(12)

pinAred.off()
pinByellow.on()
pinCgreen.on()
pinDblack.on()
pinEred.off()
pinFyellow.off()
pinGgreen.off()
pinHblack.on()
sleep(1)

pinAred.close()
pinByellow.close()
pinCgreen.close()
pinDblack.close()
pinEred.close()
pinFyellow.close()
pinGgreen.close()
pinHblack.close()
Example #25
0
REVERSE_LEFT_PIN = 19	# IN2 - Reverse Drive
# Motor B, Right Side GPIO CONSTANTS
PWM_DRIVE_RIGHT = 5		# ENB - H-Bridge enable pin
FORWARD_RIGHT_PIN = 13	# IN1 - Forward Drive
REVERSE_RIGHT_PIN = 6	# IN2 - Reverse Drive

IO.setup(LEFT_IR,IO.IN) #GPIO 2 -> Left IR out
IO.setup(RIGHT_IR,IO.IN) #GPIO 3 -> Right IR out

# Initialise objects for H-Bridge GPIO PWM pins
# Set initial duty cycle to 0 and frequency to 1000
driveLeft = PWMOutputDevice(PWM_DRIVE_LEFT, True, 0, 1000)
driveRight = PWMOutputDevice(PWM_DRIVE_RIGHT, True, 0, 1000)

# Initialise objects for H-Bridge digital GPIO pins
forwardLeft = DigitalOutputDevice(FORWARD_LEFT_PIN)
reverseLeft = DigitalOutputDevice(REVERSE_LEFT_PIN)
forwardRight = DigitalOutputDevice(FORWARD_RIGHT_PIN)
reverseRight = DigitalOutputDevice(REVERSE_RIGHT_PIN)

def allStop():
	forwardLeft.value = False
	reverseLeft.value = False
	forwardRight.value = False
	reverseRight.value = False
	driveLeft.value = 0
	driveRight.value = 0

def forwardDrive():
	forwardLeft.value = True
	reverseLeft.value = False
 def __init__(self, trig, echo):
     self.trig = DigitalOutputDevice(trig)
     self.echo = DigitalInputDevice(echo)
     self.hist = []
 def setup_switches(self):
     print('Setup switches')
     for gpio_pin in self.gpio_pins:
         self.output_devices[gpio_pin] = DigitalOutputDevice(gpio_pin)
Example #28
0
# Motor A, Left Side GPIO CONSTANTS
PWM_DRIVE_LEFT = 21		# ENA - H-Bridge enable pin
FORWARD_LEFT_PIN = 26	# IN1 - Forward Drive
REVERSE_LEFT_PIN = 19	# IN2 - Reverse Drive
# Motor B, Right Side GPIO CONSTANTS
#PWM_DRIVE_RIGHT = 5		# ENB - H-Bridge enable pin
#FORWARD_RIGHT_PIN = 13	# IN1 - Forward Drive
#REVERSE_RIGHT_PIN = 6	# IN2 - Reverse Drive
 
# Initialise objects for H-Bridge GPIO PWM pins
# Set initial duty cycle to 0 and frequency to 1000
driveLeft = PWMOutputDevice(PWM_DRIVE_LEFT, True, 0, 1000)
#driveRight = PWMOutputDevice(PWM_DRIVE_RIGHT, True, 0, 1000)
 
# Initialise objects for H-Bridge digital GPIO pins
forwardLeft = DigitalOutputDevice(FORWARD_LEFT_PIN)
reverseLeft = DigitalOutputDevice(REVERSE_LEFT_PIN)
#forwardRight = DigitalOutputDevice(FORWARD_RIGHT_PIN)
#reverseRight = DigitalOutputDevice(REVERSE_RIGHT_PIN)

a=1
 
def allStop():
	forwardLeft.value = False
	reverseLeft.value = False
#	forwardRight.value = False
#	reverseRight.value = False
	driveLeft.value = 0
	#driveRight.value = 0
 
def forwardDrive():
def main():
    """object detection camera inference example."""
    parser = argparse.ArgumentParser()
    countdown = 20
    parser.add_argument(
        '--num_frames',
        '-n',
        type=int,
        dest='num_frames',
        default=None,
        help='Sets the number of frames to run for, otherwise runs forever.')
    args = parser.parse_args()

    servoX = AngularServo(PIN_B)
    servoY = AngularServo(PIN_A)
    relay = DigitalOutputDevice(PIN_C, active_high=True, initial_value=True)
    #relay.blink(n=1)
    relay.blink(on_time=0.05, n=1)

    # Forced sensor mode, 1640x1232, full FoV. See:
    # https://picamera.readthedocs.io/en/release-1.13/fov.html#sensor-modes
    # This is the resolution inference run on.
    with PiCamera(sensor_mode=4, resolution=(1640, 1232),
                  framerate=10) as camera:
        camera.start_preview()

        # Annotator renders in software so use a smaller size and scale results
        # for increased performace.
        annotator = Annotator(camera, dimensions=(320, 240))
        scale_x = 320 / 1640
        scale_y = 240 / 1232

        # Incoming boxes are of the form (x, y, width, height). Scale and
        # transform to the form (x1, y1, x2, y2).
        def transform(bounding_box):
            x, y, width, height = bounding_box
            return (scale_x * x, scale_y * y, scale_x * (x + width),
                    scale_y * (y + height))

        def textXYTransform(bounding_box):
            x, y, width, height = bounding_box
            return (scale_x * x, scale_y * y)

        with CameraInference(object_detection.model()) as inference:
            for result in inference.run():
                objs = object_detection.get_objects(result, 0.3)
                annotator.clear()
                for obj in objs:
                    # blue for person, green for cat, purple for dog, red for anything else
                    outlineColor = "blue" if obj.kind == 1 else "green" if obj.kind == 2 else "purple" if obj.kind == 3 else "red"
                    print(obj.kind)
                    tBoundingBox = transform(obj.bounding_box)
                    annotator.bounding_box(tBoundingBox,
                                           fill=0,
                                           outline=outlineColor)
                    annotator.text(
                        textXYTransform(obj.bounding_box),
                        "person" if obj.kind == 1 else "cat" if obj.kind == 2
                        else "dog" if obj.kind == 3 else "other",
                        color=outlineColor)

                    if len(objs) == 1:
                        x1, y1, x2, y2 = transform(obj.bounding_box)
                        midX = ((x2 - x1) / 2) + x1
                        midY = ((y2 - y1) / 2) + y1
                        servoPosX = remap(midX, 0, 320, 75, -75)
                        servoPosY = remap(midY, 0, 240, -90,
                                          80)  # 90 is low, -90 is high
                        servoPosX = min(90, servoPosX)
                        servoPosX = max(-90, servoPosX)
                        servoPosY = min(90, servoPosY)
                        servoPosY = max(-90, servoPosY)
                        print("x", midX, servoPosX)
                        print("y", midY, servoPosY)
                        servoX.angle = servoPosX
                        servoY.angle = servoPosY

                        countdown -= 1

                        if countdown == -1:
                            # squirt
                            annotator.text((midX, midY),
                                           "Squirt!!",
                                           color=outlineColor)
                            relay.blink(on_time=0.5, n=1)
                            countdown = 20
                        else:
                            annotator.text((midX, midY),
                                           str(countdown),
                                           color=outlineColor)
                if len(objs) == 0:
                    countdown = 20
                annotator.update()

        camera.stop_preview()
Example #30
0
logging.basicConfig(filename=logfile,
                    level=logging.DEBUG,
                    format='%(asctime)s %(message)s',
                    datefmt='%Y-%m-%d, %H:%M:%S,')

serial = i2c(port=1, address=0x3C)
display = ssd1306(serial)
UP_BUTTON = Button(13)
DOWN_BUTTON = Button(26)
LEFT_BUTTON = Button(6)
RIGHT_BUTTON = Button(0)
ACTION_BUTTON = Button(5)
HOME_BUTTON = Button(19)
PIR = MotionSensor(23)
# Camera Mode High => Day Mode, Low => Night Mode
CAMERA_CONTROL = DigitalOutputDevice(21, True, True)

# Work out height of text
text_height = 0
with canvas(display) as draw:
    w, text_height = draw.textsize(" ")

# prev icon (small)
# gap
# icon (large)
# gap
# text
# gap
# next icon (small)
gap = 3
available_height = display.height - 3 * gap - text_height