class SensorSuite:
    """This is a class that will get all the sensor information that we need
    """
    def __init__(self):
        self.connected = False

        self.x = 0
        self.y = 0
        self.z = 0

        self.ultrasonic = None

    def get_position(self):
        return (self.x, self.y, self.z)

    def update_z(self):
        while self.connected:
            self.z = self.ultrasonic.measure()
            sleep(0.01)

    def connect(self):
        self.connected = True
        self.ultrasonic = Ultrasonic()

        Thread(target=self.update_z).start()

    def disconnect(self):
        self.connected = False
        sleep(0.1)

        self.ultrasonic.disconnect()
        self.ultrasonic = None
Esempio n. 2
0
    def __init__(self):
        # Set channels to the number of servo channels on your kit.
        # 8 for FeatherWing, 16 for Shield/HAT/Bonnet.
        self.kit = ServoKit(channels=16)
        logging.debug('Setting channel to 16')
        self.z = 0
        logging.debug('Set to 90 degree')
        time.sleep(5)
        self.x = 0
        self.y = 0
        self.xValue = 0
        self.yValue = 0
        self.rotateFistElbowAngle = 0
        self.rotateAngle = 0
        self.xComplete = False
        self.yComplete = False
        self.camera = Camera()
        self.color = "orange"
        self.robot = Robot()
        self.ultrasonic = Ultrasonic()
        self.Y_limit = {"Lower": 360, "Upper": 363}
        self.X_limit = {"Lower": 314, "Upper": 316}
        self.dictColor = {"orange": (114, 61, 27), "green": (50, 168, 82)}

        # for the api
        self.color_coordinates = {}
Esempio n. 3
0
    def __init__(self,
                 reverse_mot1=False,
                 reverse_mot2=False,
                 fix_rotate=False,
                 derivative_fix=0):
        """ Initialize the DualHBridge L293D. Allows you to reverse/tune the 
            spinning commands for the motors when the underlaying plateform does not 
            move proprely when calling forward() or backward()

          :param reverse_mot1: switch the forward/backward commands for motor 1
          :param reverse_mot2: switch the forward/backward commands for motor 2
          :param fix_rotate: set this True when the robot turn left instead of turning right as requested
          :param derivative_fix: use +3 to speedup right motor when forward() does bend the path to the right. 
                                 use -3 to slow down the right motor when forward() bend the path to the left."""
        mot1 = (self.MOT1_PINS[1],
                self.MOT1_PINS[0]) if reverse_mot1 else self.MOT1_PINS
        mot2 = (self.MOT2_PINS[1],
                self.MOT2_PINS[0]) if reverse_mot2 else self.MOT2_PINS
        if not fix_rotate:
            super(MotorSkin, self).__init__(mot1, self.MOT1_PWM, mot2,
                                            self.MOT2_PWM, derivative_fix)
        else:
            # Robot is apparently rotating the wrong way... this is because
            # motor1 has been wired in place of the motor 2.
            super(MotorSkin, self).__init__(mot2, self.MOT2_PWM, mot1,
                                            self.MOT1_PWM, derivative_fix)

        self.ultrason = Ultrasonic(self.TRIGGER_PIN, self.ECHO_PIN)

        for pin in ('X18', 'X19', 'X20', 'X21'):
            self._switches.append(
                pyb.Pin(pin, pyb.Pin.IN, pull=pyb.Pin.PULL_UP))
Esempio n. 4
0
def main(argv):

    for sig in (SIGABRT, SIGILL, SIGINT, SIGSEGV, SIGTERM):
        signal(sig, clean)

    # --- IP of esp
    esp_ip = "129.69.209.119"  #placeholder
    broker_port = 1883
    #Read other measure interval from parameter data
    paramArray = json.loads(argv[0])
    for param in paramArray:
        if not ('name' in param and 'value' in param):
            continue
        elif param["name"] == "esp_ip":
            esp_ip = param["value"]

    configFileName = "connections.txt"
    topics = []
    brokerIps = []
    configExists = False

    configFile = os.path.join(os.getcwd(), configFileName)

    while (not configExists):
        configExists = os.path.exists(configFile)
        time.sleep(1)

    # BEGIN parsing file
    fileObject = open(configFile)
    fileLines = fileObject.readlines()
    fileObject.close()

    for line in fileLines:
        pars = line.split('=')
        topic = pars[0].strip('\n').strip()
        ip = pars[1].strip('\n').strip()
        topics.append(topic)
        brokerIps.append(ip)

    # END parsing file
    hostname = brokerIps[0]
    topic_pub = topics[0]
    topic_splitted = topic_pub.split('/')
    component = topic_splitted[0]
    component_id = topic_splitted[1]

    # --- Create ESP12e instance
    global esp
    esp = ESP12e_Push(esp_ip, hostname, broker_port, topic_pub)
    esp.start()

    # --- Create Ultrasonic sensor instance
    ultrasonic = Ultrasonic(hostname, broker_port, topic)

    while ultrasonic.getLastValue() == None:
        ultrasonic.updateLastValue()
        time.sleep(1)

    while True:
        time.sleep(1)
Esempio n. 5
0
    def __init__(self):

        super().__init__("Distance Error")
        self.setPollingPeriod(1)

        self._meter = Ultrasonic(DistanceErrorApp.GPIO_TRIGGER,
                                 DistanceErrorApp.GPIO_ECHO)
Esempio n. 6
0
def sensorTest():
    ZumoButton().wait_for_press()
    sensor = Ultrasonic()
    count = 0
    while count < 5:
        sensor.update()
        print(sensor.get_value())
        count += 1
Esempio n. 7
0
def distance():
    us = Ultrasonic()
    button = ZumoButton()
    while True:
        button.wait_for_press()
        us.update()
        reading = us.get_value()
        print(reading)
        time.sleep(0.6)
Esempio n. 8
0
    def get_distance_value(self):
        """
        Shortcut for getting distance
        :return: Distance
        """

        ultra = Ultrasonic()
        ultra.update()
        value = ultra.get_value()

        return value
Esempio n. 9
0
def explorer(dist=10):
    ZumoButton().wait_for_press()
    m = Motors(); u = Ultrasonic()
    while u.update() > dist:
        m.forward(.2,0.2)
    m.backward(.1,.5)
    m.left(.5,3)
    m.right(.5,3.5)
    sleep(2)
    while u.update() < dist*5:
        m.backward(.2,0.2)
    m.left(.75,5)
Esempio n. 10
0
def explorer(dist=10):
    ZumoButton().wait_for_press()
    m = Motors(); u = Ultrasonic()
    while u.update() > dist:
        m.forward(.2,0.2)
    m.backward(.1,.5)
    m.left(.5,3)
    m.right(.5,3.5)
    sleep(2)
    while u.update() < dist*5:
        m.backward(.2,0.2)
    m.left(.75,5)
Esempio n. 11
0
def explorer(dist=10):
    m = Motors()
    u = Ultrasonic()
    while u.update() > dist:
        m.forward(0.2, 0.2)
    m.backward(.1, 0.5)
    m.left(.5, 3)
    m.right(.5, 3.5)
    sleep(2)
    while u.update() < dist * 5:
        m.backward(.2, 0.2)
    m.left(.75, 5)
Esempio n. 12
0
    def calculateFront(self):

        u_sensor = Ultrasonic()
        u_sensor.update()
        distance = u_sensor.get_value()
        if distance < 5:
            self.pri_value = 1000

        else:
            self.pri_value = 0

        return self.pri_value
Esempio n. 13
0
def dancer():
    ZumoButton().wait_for_press()
    m = Motors()

    u = Ultrasonic()
    print(u.getvalue())

    m.forward(.2, 3)
    m.backward(.2, 3)
    m.right(.5, 3)
    m.left(.5, 3)
    m.backward(.3, 2.5)
    m.set_value([.5, .1], 10)
    m.set_value([-.5, -.1], 10)
Esempio n. 14
0
class UltrasonicSensob(Sensob):
    def __init__(self):
        super(UltrasonicSensob, self).__init__()
        self.sensor = Ultrasonic()
        self.sensors.append(self.sensor)

    def get_value(self):
        ''' returnerer en verdi = avstand i cm'''
        return self.value

    def update(self):
        self.sensor.update()
        self.value = self.sensor.get_value()
        return self.value
Esempio n. 15
0
def my():
    wp.wiringPiSetupGpio()
    wp.wiringPiSetup()
    uls = Ultrasonic(20, 21)
    tesla = Tesla_motor(23, 18, 25, 24)
    tesla.allStop()
    while 1:
        distance = uls.distance()
        print(distance)
        if distance > 30:
            tesla.forwardDrive()
        #sleep(5)
        else:
            tesla.allStop()
Esempio n. 16
0
def loop():
    global lcd
    lcd = LCD()
    us = Ultrasonic(GPIO_TRIGGER, GPIO_ECHO)
    while True:
        distance = us.distance()
        if distance:
            lcd.message('distance:\n                ')
            print('distance:%0.2fcm' % distance)
            #lcd.clear()
            lcd.message('distance:\n%0.2fcm' % distance)
        else:
            print('Error')
        time.sleep(0.2)
Esempio n. 17
0
def explorer(dist=10):
    ZumoButton().wait_for_press()
    m = Motors()
    u = Ultrasonic()
    print(u.sensor_get_value())
    while u.sensor_get_value() > dist:
        m.forward(.2, 0.2)
        print(u.value)
    m.backward(.1, .5)
    m.left(.5,3)
    m.right(.5, 3.5)
    sleep(2)
    while u.sensor_get_value() < dist*5:
        m.backward(.2, 0.2)
    m.left(.75, 5)
Esempio n. 18
0
    def setup(self):
        # LineBehavior
        rs = ReflectanceSensors()
        rsob = ReflectanceSensob(rs)
        lineb = FollowLineBehavior(self, [rsob], False, 0.7)
        self.add_behavior(lineb)
        self.activate_behavior(lineb)
        self.add_sensob(rsob)

        # Forward Behavior
        forwardb = ForwardBehavior(self, [rsob], False, 0.2)
        self.add_behavior(forwardb)
        self.activate_behavior(forwardb)

        # Follow green flask
        my_camera = Camera()
        self.followgreensensob = GreenDirectionSensob(my_camera)
        followgreenb = FollowGreenFlask(self, [self.followgreensensob, rsob],
                                        False, 1.0)
        self.add_behavior(followgreenb)
        self.activate_behavior(followgreenb)
        self.add_sensob(self.followgreensensob)

        # Avoid Collision
        us = Ultrasonic()
        ir = IRProximitySensor()
        self.irob = IRProximitySensob(ir)
        self.usob = UltrasonicSensob(us)
        self.add_sensob(self.irob)
        self.add_sensob(self.usob)
        avoidb = AvoidCollisionBehavior(self, [self.usob, self.irob, rsob],
                                        False, 1.0)
        self.add_behavior(avoidb)
        self.activate_behavior(avoidb)
Esempio n. 19
0
def start():
    bbcon = BBCON()
    arb = Arbitrator(bbcon)
    motor = Motors()
    reflect_sens = ReflectanceSensors(False)
    cam = Camera()
    ir = IR()
    ultra = Ultrasonic()

    bbcon.add_motobs(motor)
    bbcon.set_arb(arb)
    bbcon.add_behaviour(AvoidObj(bbcon, ultra, ir))
    bbcon.add_behaviour(Behaviour_line_follower(bbcon, reflect_sens))
    bbcon.add_behaviour(fub(bb=bbcon))
    #behaviour avoid blue, has to be added last, do not change this, will screw up bbcon code
    bbcon.add_behaviour(Behaviour_avoid_blue(bb=bbcon, cam=cam, ultra=ultra))
    bbcon.add_sensob(reflect_sens)
    bbcon.add_sensob(ir)
    bbcon.add_sensob(ultra)
    #cam has to be added last, will screw up bbcon code if not
    bbcon.add_sensob(cam)

    butt = ZumoButton()
    butt.wait_for_press()
    print("Start zumo")

    while True:
        bbcon.run_one_timestep()
Esempio n. 20
0
    def get_sensor_values(self, sensor_class):
        """
        Helper function to get values afflicted with a sensor
        :param sensor_class: Class of the sensor
        :return: Values or None
        """
        ultra = Ultrasonic()
        ultra.update()

        sensor = self.get_sensor(sensor_class)

        if sensor is not None:
            return self.sensors[sensor]

        else:
            return None
Esempio n. 21
0
def trackTest():
    ZumoButton().wait_for_press()
    motor = Motors()
    ultra = Ultrasonic()
    camera = Camera()


    stuck = CheckStuck()
    motob = Motob(motor)
    arbitrator = Arbitrator(motob=motob)

    sensob = Sensob()
    sensob.set_sensors([ultra, camera])

    bbcon = BBCON(arbitrator=arbitrator, motob=motob)
    b = TrackObject(priority=1, sensobs=[sensob])
    bbcon.set_checkStucker(stuck)
    bbcon.add_behavior(b)

    bbcon.activate_behavior(0)
    bbcon.add_sensob(sensob)

    timesteps = 0
    while timesteps < 25:

        bbcon.run_one_timestep()
        timesteps += 1
Esempio n. 22
0
def main():
    # initialisering
    ZumoButton().wait_for_press()
    bbcon = BBCON()
    us = Ultrasonic()

    ir_sensob = Sensob(
        ReflectanceSensors(True))  # True betyr med auto-kalibrering
    usonic_sensob = Sensob(us)
    camera_sensob = Sensob(sensor=Camera(), sensor2=us)

    avoid_borders = Avoid_borders(ir_sensob, bbcon)
    walk_randomly = Walk_randomly(None, bbcon)
    clean = Clean(usonic_sensob, bbcon)
    approach = Approach(usonic_sensob, bbcon)
    take_photo = Take_photo(camera_sensob, bbcon)

    # setup
    bbcon.add_sensob(ir_sensob)  # legger til IR sensob
    bbcon.add_sensob(usonic_sensob)  # legger til Ultrasonic sensob
    #bbcon.add_sensob(camera_sensob)    # legger til Ultrasonic/camera sensob

    bbcon.add_behavior(avoid_borders)  # legger til avoid_borders
    bbcon.add_behavior(walk_randomly)  # legger til walk_randomly
    #bbcon.add_behavior(clean)          # legger til clean
    bbcon.add_behavior(approach)  # legger til approach
    bbcon.add_behavior(take_photo)  # legger til take_photo

    bbcon.activate_behavior(avoid_borders)
    bbcon.activate_behavior(walk_randomly)
    bbcon.activate_behavior(approach)
    #bbcon.activate_behavior(take_photo)

    while True:
        bbcon.run_one_timestep()
Esempio n. 23
0
def lineCollision():
    reflect = ReflectanceSensors()
    ZumoButton().wait_for_press()
    motor = Motors()
    stuck = CheckStuck()
    ultra = Ultrasonic()
    proxim = IRProximitySensor()
    sensobCol = Sensob()
    sensobCol.set_sensors([ultra, proxim])
    motob = Motob(motor=motor)
    sensobLine = Sensob()
    sensobLine.set_sensors([reflect])

    arb = Arbitrator(motob=motob)
    bbcon = BBCON(arbitrator=arb, motob=motob)
    bbcon.set_checkStucker(stuck)
    line = LineFollow(1, [sensobLine])
    col = CollisionAvoidance(1, [sensobCol])
    bbcon.add_behavior(line)
    bbcon.add_behavior(col)
    bbcon.add_sensob(sensobCol)
    bbcon.add_sensob(sensobLine)

    count = 0
    while count < 20:
        bbcon.run_one_timestep()
        count += 1
Esempio n. 24
0
    def startup(self):
        # add sensor objects
        cam = Sensob(Camera())
        ultrasonic = Sensob(Ultrasonic())
        ir_sensor = Sensob(ReflectanceSensors())
        self.add_sensob(cam)
        self.add_sensob(ultrasonic)
        self.add_sensob(ir_sensor)

        # add behaviors
        sb = StandardBehavior(self)
        self.add_behavior(sb)
        self.activate_behavior(sb)
        cb = CameraBehavior(self)
        self.add_behavior(cb)
        self.activate_behavior(cb)
        ub = UltraBehavior(self)
        self.add_behavior(ub)
        self.activate_behavior(ub)
        ir = IRBehavior(self)
        self.add_behavior(ir)
        self.activate_behavior(ir)

        button = ZumoButton()
        button.wait_for_press()
        self._running = True
        while self._running:
            self.run_one_timestep()
            # wait
            time.sleep(0.001)
Esempio n. 25
0
def main():
    motob = Motob()
    bbcon = Bbcon(motob)
    arbitrator = Arbitrator(bbcon)
    bbcon.set_arbitrator(arbitrator)

    # sensorer og sensob
    ult_sensor = Ultrasonic()
    ref_sensor = ReflectanceSensors(auto_calibrate=False)
    reflectance_sensob = ReflectanceSensob(ref_sensor)
    ultrasonic_sensob = UltrasonicSensob(ult_sensor)
    camera_sensob = CameraSensob(None, color=0)

    #behaviors
    dont_crash = DontCrash(bbcon, ultrasonic_sensob)
    follow_line = FollowLine(bbcon, reflectance_sensob)
    find_object = FindColoredObject(bbcon, camera_sensob)

    bbcon.add_behavior(dont_crash)
    bbcon.add_behavior(follow_line)
    bbcon.add_behavior(find_object)
    try:
        ZumoButton().wait_for_press()
        while not bbcon.object_found:  # Kjører helt til vi finner objektet
            bbcon.run_one_timestep()
    except KeyboardInterrupt:
        motob.motor.stop()
    finally:
        GPIO.cleanup()
Esempio n. 26
0
class MotorSkin(DualHBridge):
    """ Specifics for 2 bidirectional motor driving (with speed control via PWM) """

    MOT1_PINS = (pyb.Pin.board.X6, pyb.Pin.board.X5)
    MOT1_PWM = {'pin': pyb.Pin.board.X3, 'timer': 5, 'channel': 3}

    MOT2_PINS = (pyb.Pin.board.X7, pyb.Pin.board.X8)
    MOT2_PWM = {'pin': pyb.Pin.board.X4, 'timer': 5, 'channel': 4}

    (TRIGGER_PIN, ECHO_PIN) = (pyb.Pin.board.Y5, pyb.Pin.board.Y6)

    ultrason = None
    _switches = []

    def __init__(self,
                 reverse_mot1=False,
                 reverse_mot2=False,
                 fix_rotate=False,
                 derivative_fix=0):
        """ Initialize the DualHBridge L293D. Allows you to reverse/tune the 
            spinning commands for the motors when the underlaying plateform does not 
            move proprely when calling forward() or backward()

          :param reverse_mot1: switch the forward/backward commands for motor 1
          :param reverse_mot2: switch the forward/backward commands for motor 2
          :param fix_rotate: set this True when the robot turn left instead of turning right as requested
          :param derivative_fix: use +3 to speedup right motor when forward() does bend the path to the right. 
                                 use -3 to slow down the right motor when forward() bend the path to the left."""
        mot1 = (self.MOT1_PINS[1],
                self.MOT1_PINS[0]) if reverse_mot1 else self.MOT1_PINS
        mot2 = (self.MOT2_PINS[1],
                self.MOT2_PINS[0]) if reverse_mot2 else self.MOT2_PINS
        if not fix_rotate:
            super(MotorSkin, self).__init__(mot1, self.MOT1_PWM, mot2,
                                            self.MOT2_PWM, derivative_fix)
        else:
            # Robot is apparently rotating the wrong way... this is because
            # motor1 has been wired in place of the motor 2.
            super(MotorSkin, self).__init__(mot2, self.MOT2_PWM, mot1,
                                            self.MOT1_PWM, derivative_fix)

        self.ultrason = Ultrasonic(self.TRIGGER_PIN, self.ECHO_PIN)

        for pin in ('X18', 'X19', 'X20', 'X21'):
            self._switches.append(
                pyb.Pin(pin, pyb.Pin.IN, pull=pyb.Pin.PULL_UP))

    def distance(self):
        """ Read distance in cm from Ultrasonic sensor """
        return self.ultrason.distance_in_cm()

    def button_pin(self, button_nr):
        """ Return Pin for a user button 1 to 4 (SW1..SW4) """
        return self._switches[button_nr - 1]

    def button_pressed(self, button_nr):
        """ Check if a user button is pressed """
        return self._switches[button_nr - 1].value() == 0
Esempio n. 27
0
def test():
    ZumoButton().wait_for_press()
    ultra = Ultrasonic()
    m = Motors()
    ultra.update()
    tall = ultra.get_value()
    print("tall: ", tall)
    while tall < 5.0:
        m.backward(0.2, 1)
        print(tall)
        ultra.update()
        tall = ultra.get_value()
    print(tall)
Esempio n. 28
0
    def __init__(self, debug=False):
        self.motor = Motors()
        self.behaviors = []
        self.debug = debug

        self.sensobs = {
            Camera(img_width=IMG_WIDTH, img_height=IMG_HEIGHT): None,
            Ultrasonic(): None,
            ReflectanceSensors(): None
        }
        self.arbitrator = None
Esempio n. 29
0
class CamUltra():
    def __init__(self):
        self.camera = Camera()
        self.range = 30
        self.ultrasensor = Ultrasonic()

    def update(self):
        print('Updating CamUltra')
        self.distance = self.ultrasensor.update()
        print('dist = ', self.distance)
        if self.distance < self.range:
            print('Taking a picture in CamUltra')
            s = 1
            self.image = Imager(image=self.camera.update())
        else:
            self.image = False

    def reset(self):
        self.ultrasensor.reset()
        self.camera.reset()
Esempio n. 30
0
 def __init__(self):
     self.sensors = {
         'camera': Camera(img_width=IMG_WIDTH, img_height=IMG_HEIGHT),
         'ultrasonic': Ultrasonic(),
         'reflectance': ReflectanceSensors()
     }
     self.values = {
         'camera': None,
         'ultrasonic': None,
         'reflectance': None,
     }
Esempio n. 31
0
def main():
    '''
    Makes a LED to blink according to the distance meassured
    by an ultrasonic sensor.
    Finish when user press a toggle key.
    '''

    blinker = Blinker(27, MAX_DELAY)  #P8.17
    ultrasonic = Ultrasonic(66, 69)  #P8.7, P8.9
    key = Gpio(65, Gpio.IN)  #P8.18

    try:

        print("Ready. Press toggle key to start.")

        #Wait for key down event
        while key.getValue() == Gpio.LOW:

            sleep(0.2)

        #Wait for key up event
        while key.getValue() == Gpio.HIGH:

            sleep(0.2)

        print("Started. Press toggle key again to finish.")
        blinker.start()

        while key.getValue() == Gpio.LOW:
            dist = ultrasonic.read()
            delay = calculateDelay(dist)
            blinker.setDelay(delay)
            sleep(0.2)

        print("Bye!")

    finally:
        key.cleanup()
        blinker.stop()
        blinker.cleanup()
        ultrasonic.cleanup()
Esempio n. 32
0
class CamUltra():

    def __init__(self):
        self.camera = Camera()
        self.range = 30
        self.ultrasensor = Ultrasonic()

    def update(self):
        print('Updating CamUltra')
        self.distance = self.ultrasensor.update()
        print('dist = ', self.distance)
        if self.distance<self.range:
            print('Taking a picture in CamUltra')
            s = 1
            self.image = Imager(image=self.camera.update())
        else:
            self.image = False

    def reset(self):
        self.ultrasensor.reset()
        self.camera.reset()
Esempio n. 33
0
class MotorSkin( DualHBridge ):
    """ Specifics for 2 bidirectional motor driving (with speed control via PWM) """

    MOT1_PINS = ( pyb.Pin.board.X6, pyb.Pin.board.X5 )
    MOT1_PWM = {'pin' : pyb.Pin.board.X3, 'timer' : 5, 'channel' : 3 }   

    MOT2_PINS = ( pyb.Pin.board.X7, pyb.Pin.board.X8 )
    MOT2_PWM = {'pin' : pyb.Pin.board.X4, 'timer' : 5, 'channel' : 4 }  

    (TRIGGER_PIN,ECHO_PIN) = (pyb.Pin.board.Y5, pyb.Pin.board.Y6)

    ultrason = None
    _switches = []
    
    def __init__( self, reverse_mot1 = False, reverse_mot2 = False, fix_rotate = False, derivative_fix = 0 ):
        """ Initialize the DualHBridge L293D. Allows you to reverse/tune the 
            spinning commands for the motors when the underlaying plateform does not 
            move proprely when calling forward() or backward()

          :param reverse_mot1: switch the forward/backward commands for motor 1
          :param reverse_mot2: switch the forward/backward commands for motor 2
          :param fix_rotate: set this True when the robot turn left instead of turning right as requested
          :param derivative_fix: use +3 to speedup right motor when forward() does bend the path to the right. 
                                 use -3 to slow down the right motor when forward() bend the path to the left."""
        mot1 = ( self.MOT1_PINS[1], self.MOT1_PINS[0] ) if reverse_mot1 else self.MOT1_PINS
        mot2 = ( self.MOT2_PINS[1], self.MOT2_PINS[0] )  if reverse_mot2 else self.MOT2_PINS
        if not fix_rotate:
            super( MotorSkin, self ).__init__( mot1, self.MOT1_PWM, mot2, self.MOT2_PWM, derivative_fix )
        else:
            # Robot is apparently rotating the wrong way... this is because
            # motor1 has been wired in place of the motor 2.
            super( MotorSkin, self).__init__( mot2, self.MOT2_PWM, mot1, self.MOT1_PWM, derivative_fix )

        self.ultrason = Ultrasonic( self.TRIGGER_PIN, self.ECHO_PIN )

        for pin in ('X18','X19','X20','X21'):
            self._switches.append( pyb.Pin( pin, pyb.Pin.IN, pull=pyb.Pin.PULL_UP) )


    def distance( self ):
      """ Read distance in cm from Ultrasonic sensor """
      return self.ultrason.distance_in_cm()

    def button_pin( self, button_nr ):
      """ Return Pin for a user button 1 to 4 (SW1..SW4) """
      return self._switches[ button_nr-1 ]

    def button_pressed( self, button_nr ):
      """ Check if a user button is pressed """
      return self._switches[ button_nr-1 ].value() == 0
Esempio n. 34
0
    def __init__( self, reverse_mot1 = False, reverse_mot2 = False, fix_rotate = False, derivative_fix = 0 ):
        """ Initialize the DualHBridge L293D. Allows you to reverse/tune the 
            spinning commands for the motors when the underlaying plateform does not 
            move proprely when calling forward() or backward()

          :param reverse_mot1: switch the forward/backward commands for motor 1
          :param reverse_mot2: switch the forward/backward commands for motor 2
          :param fix_rotate: set this True when the robot turn left instead of turning right as requested
          :param derivative_fix: use +3 to speedup right motor when forward() does bend the path to the right. 
                                 use -3 to slow down the right motor when forward() bend the path to the left."""
        mot1 = ( self.MOT1_PINS[1], self.MOT1_PINS[0] ) if reverse_mot1 else self.MOT1_PINS
        mot2 = ( self.MOT2_PINS[1], self.MOT2_PINS[0] )  if reverse_mot2 else self.MOT2_PINS
        if not fix_rotate:
            super( MotorSkin, self ).__init__( mot1, self.MOT1_PWM, mot2, self.MOT2_PWM, derivative_fix )
        else:
            # Robot is apparently rotating the wrong way... this is because
            # motor1 has been wired in place of the motor 2.
            super( MotorSkin, self).__init__( mot2, self.MOT2_PWM, mot1, self.MOT1_PWM, derivative_fix )

        self.ultrason = Ultrasonic( self.TRIGGER_PIN, self.ECHO_PIN )

        for pin in ('X18','X19','X20','X21'):
            self._switches.append( pyb.Pin( pin, pyb.Pin.IN, pull=pyb.Pin.PULL_UP) )
Esempio n. 35
0
filename = 'audio.wav' #sound file

#members
LED = 'P9_16' #LED to show status
TRIG = 'P9_12' #trigger pin on ultrasonic
ECHO = 'P9_14' #echo pin receieve

thresh = 20. #distance threshold for ultrasonic 
status_flag = 0 #within threshold value
val = 0

#setup
GPIO.setup(LED, GPIO.OUT)

rangefinder = Ultrasonic(TRIG, ECHO, thresh)
camera = GoProHero(password='******') #connect to camera
#=========================================================

while(1):
	try:
		status_flag = rangefinder.threshold()
		
		GPIO.output(LED, status_flag)
		status = camera.status()
		if(status_flag == 1 and status['record'] != 'on'):
			camera.command('record','on')
			os.system('aplay ' + filename)
			#print('recording')
		elif(status['record'] != 'off' and status_flag == 0):
			camera.command('record','off')
Esempio n. 36
0
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##

from pyb import delay
from r2wheel import Robot2Wheel                                             
from ultrasonic import Ultrasonic

# Broche pour déclencher le senseur
TRIGGER_PIN = pyb.Pin.board.Y5 
# Broche pour attendre le retour d'echo
ECHO_PIN = pyb.Pin.board.Y6

r2 = Robot2Wheel( reverse_mot2 = True ) 
u = Ultrasonic( TRIGGER_PIN, ECHO_PIN )

MIN_DISTANCE = 20 # Minimum distance 

r2.forward()
while True:
    if u.distance_in_cm() < MIN_DISTANCE:
        r2.halt()
        delay(100)
        r2.right()
        delay( 2500 )
        r2.halt()
        delay(100)
    # If nothing in front then move
    if (r2.state == Robot2Wheel.HALTED) and (u.distance_in_cm() > MIN_DISTANCE): 
        r2.forward()
Esempio n. 37
0
 def __init__(self):
     self.camera = Camera()
     self.range = 30
     self.ultrasensor = Ultrasonic()