コード例 #1
0
def gamepad(q):
    """ gamepad takes a Queue and puts all events on it """
    print "gamepad starting up"
    gp = Gamepad()
    for event in gp.get_events():
        print "gamepad: read {} and queued".format(event)
        q.put(event)
コード例 #2
0
    def __init__(self, grbl):
        self.step_size = 0.1  # mm
        self.max_feedrate = 1000
        self.loop_delay = 0.02

        self.jogging = False
        self.stepping = False
        self.grbl = grbl

        self.gamepad = Gamepad()

        # Feed hold
        self.gamepad.on('l1', lambda *a: grbl.send(b'!'))

        # Resume cycle
        self.gamepad.on('l2', lambda *a: grbl.send(b'~'))

        self.gamepad.on('btn11', self.toggle_stepping)  # left axis btn
        self.gamepad.on('select', lambda *a: grbl.soft_reset())
        self.gamepad.on('start', lambda *a: grbl.unlock())
        self.gamepad.on('dpady', self.on_dpady)

        # zero X-axis work coordinates
        self.gamepad.on('btn2', lambda *a: grbl.set_active_coord_system(x=0))

        # zero Y-axis work coordinates
        self.gamepad.on('btn1',
                        lambda *a: self.grbl.set_active_coord_system(y=0))

        # zero Z-axis work coordinates
        self.gamepad.on('btn3',
                        lambda *a: self.grbl.set_active_coord_system(z=0))
コード例 #3
0
ファイル: cli.py プロジェクト: oralekin/gamepad
def main(args=None):
    """Console script for gamepad."""

    controller = Gamepad()
    controller.watch_all()

    click.echo("Connect a gamepad and start mashing buttons!")

    input("Press ENTER to quit\n\n")

    return 0
コード例 #4
0
ファイル: main.py プロジェクト: matt-duke/Submarine
    def __init__(self):
        super().__init__()

        self.stream = VideoStream()
        self.winId = self.stream.winId()
        self.setCentralWidget(self.stream)

        self.resize(500, 500)

        self.gamepad = Gamepad()

        self.hud = HUD(self)
コード例 #5
0
ファイル: main.py プロジェクト: wangqiaoli/arduino-quadcopter
 def createGamepad(self):
     if self.gamepad == None:
         print("Connecting gamepad...")
         self.gamepad = Gamepad(0)
         if self.gamepad.enabled():
             self.gamepad.connectButton(0, self.addMinThrottle)
             self.gamepad.connectButton(1, self.removeMinThrottle)
             self.gamepad.connectButton(6, self.stop)
             self.gamepad.connectButton(7, self.start)
             self.gamepad.connectButton(3, self.disableGamepad)
             self.gamepad_timer = PyQt5.QtCore.QTimer()
             self.gamepad_timer.timeout.connect(self.checkGamepad)
             self.setGamepadFrequency()  # This method starts gamepad_timer
         else:
             self.gamepad.close()
             self.gamepad = None
     else:
         print("Gamepad already exists!")
コード例 #6
0
ファイル: main.py プロジェクト: matt-duke/Submarine
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.stream = VideoStream()
        self.winId = self.stream.winId()
        self.setCentralWidget(self.stream)

        self.resize(500, 500)

        self.gamepad = Gamepad()

        self.hud = HUD(self)

        #flags = QtCore.Qt.WindowFlags(QtCore.Qt.FramelessWindowHint)# | QtCore.Qt.WindowStaysOnTopHint)
        #self.setWindowFlags(flags)

    def start(self):
        #self.stream.start()
        self.gamepad.start()

    def resizeEvent(self, e):
        self.hud.resize(self.size())
コード例 #7
0
def main():
    gamepad = Gamepad()
    motors = Motors()

    iks = []

    for i in range(4):
        iks.append(DeltaIK())

    controller = ManualController(iks)

    angles = 8 * [0.0]
    kPs = 8 * [0.1]

    frametime = 1.0 / 30.0

    print("Ready.")

    while True:
        try:
            s = time.time()

            if not gamepad.process_events():
                print("Controller disconnected, waiting for reconnect...")

                while not gamepad.reconnect():
                    time.sleep(0.5)

                print("Controller reconnected.")

            if gamepad.is_a_down():
                print("Shutdown button (A) has been pressed, shutting down...")
                break

            pad_y = gamepad.get_left_thumbstick_y()

            controller.step(pad_y, frametime)

            # Map IK leg results to motors
            for i in range(4):
                angles[legMap[i]
                       [0]] = legDirs[i][0] * (iks[i].angle -
                                               (np.pi / 2.0 - iks[i].A))
                angles[legMap[i]
                       [1]] = legDirs[i][1] * (iks[i].angle +
                                               (np.pi / 2.0 - iks[i].A))

            motors.sendCommands(angles, kPs)

            time.sleep(max(0, frametime - (time.time() - s)))
        except Exception as e:
            print(e)
            break

    print("-- Program at End --")
コード例 #8
0
def main():
    logging.basicConfig(format='%(message)s', level=logging.INFO)

    # read options from rc file
    cfg = rcfile('sky-pointer')
    port = int(cfg.get('port', 10001))
    iface = cfg.get('iface', '0.0.0.0')
    serial = cfg.get('serial', SERIAL_PORT)
    joystick = cfg.get('joystick', JOYSTICK_DEV)

    # override some options with command line arguments
    parser = argparse.ArgumentParser(
        description='Sky-pointing laser controller')
    parser.add_argument('--port',
                        '-p',
                        type=int,
                        default=port,
                        help='Listenging TCP port (default: %d)' % port)
    parser.add_argument('--iface',
                        '-i',
                        default=iface,
                        help='Listenging network interface (default: %s)' %
                        iface)
    parser.add_argument('--serial',
                        '-s',
                        default=serial,
                        help='Serial port (default: %s)' % serial)
    parser.add_argument('--joystick',
                        '-j',
                        default=joystick,
                        help='Joystick device (default: %s)' % joystick)
    args = parser.parse_args()

    ptr = Pointer(args.serial)
    pad = Gamepad(ptr, args.joystick)

    server = Server(ptr, args.iface, args.port)
    logging.info("Server listening on port %d" % args.port)

    pad_thread = threading.Thread(target=pad.loop)
    pad_thread.daemon = True
    pad_thread.start()

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        logging.info("Closing")
コード例 #9
0
ファイル: main.py プロジェクト: debnera/arduino-quadcopter
 def createGamepad(self):
     if self.gamepad == None:
         print("Connecting gamepad...")
         self.gamepad = Gamepad(0)
         if self.gamepad.enabled():
             self.gamepad.connectButton(0, self.addMinThrottle)
             self.gamepad.connectButton(1, self.removeMinThrottle)
             self.gamepad.connectButton(6, self.stop)
             self.gamepad.connectButton(7, self.start)
             self.gamepad.connectButton(3, self.disableGamepad)
             self.gamepad_timer = PyQt5.QtCore.QTimer()
             self.gamepad_timer.timeout.connect(self.checkGamepad)
             self.setGamepadFrequency() # This method starts gamepad_timer
         else:
             self.gamepad.close()
             self.gamepad = None
     else:
         print("Gamepad already exists!")
コード例 #10
0
ファイル: main.py プロジェクト: schmidma/PiCopter
class Main():
    def __init__(self, GUI, DEBUG, fps, stick_sens, saveFile):
        self.GUI = GUI
        self.DEBUG = DEBUG
        self.max_fps = fps
        self.stick_sens = stick_sens
        self.saveFile = saveFile
        
        pygame.init()
        
        self.clock = pygame.time.Clock()
    
        self.run = True
        self.started = False
    
        self.main_throttle = 0
        self.throttle = [0,0,0,0]

        self.holdPosition = 0
        self.holdHeight = 0
        self.isGamepad = 1
        
        self.gamepad = Gamepad()
        self.gamepad_axes = [0,0,0]
        self.gamepad_throttle = 0
        
        self.bno = BNO()
        
        self.m1 = Motor(15)
        self.m2 = Motor(27)
        self.m3 = Motor(10)
        self.m4 = Motor(7)
        
        self.motors = [self.m1, self.m2, self.m3, self.m4]
        
        if self.GUI:
            self.gui = Gui()
        
        if self.GUI:
            self.gui.showMessage("Press 'start'-Button to start!")
        
        if self.DEBUG:
            # Print system status and self test result.
            status, self_test, error = self.bno.get_system_status()
            print("DEBUG: System status: {0}".format(status))
            print("DEBUG: Self test result (0x0F is normal): 0x{0:02X}".format(self_test))
            # Print out an error if system status is in error mode.
            if status == 0x01:
                print("DEBUG: System error: {0}".format(error))
                print("DEBUG: See datasheet section 4.3.59 for the meaning.")
            
            # Print BNO055 software revision and other diagnostic data.
            sw, bl, accel, mag, gyro = self.bno.get_revision()
            print("DEBUG: Software version:   {0}".format(sw))
            print("DEBUG: Bootloader version: {0}".format(bl))
            print("DEBUG: Accelerometer ID:   0x{0:02X}".format(accel))
            print("DEBUG: Magnetometer ID:    0x{0:02X}".format(mag))
            print("DEBUG: Gyroscope ID:       0x{0:02X}\n".format(gyro))
            
        self.load()
        
        if self.DEBUG:
            print("DEBUG: READY!")
        
        self.loop()
        
    def eventHandler(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                if self.DEBUG:
                    print("DEBUG: SHUTDOWN")
                pygame.quit()
                if self.GUI:
                    curses.endwin()
                sys.exit()
            elif event.type == JOYBUTTONDOWN:
                self.gamepad.handleButtonDown(event.button)
            elif event.type == JOYBUTTONUP:
                self.gamepad.handleButtonUp(event.button)
        
    def getGamepadValues(self):
        self.gamepad_throttle = self.gamepad.getThrottle()
        self.gamepad_axes = self.gamepad.getAxis()
        
        
    def checkCalibButtons(self):
        if self.gamepad.isSave:
            if self.DEBUG:
                print("DEBUG: Save Calibration-Data")
            self.save()
            if self.DEBUG:
                print("DEBUG: Data saved")
        
        if self.gamepad.isCalib:
            if self.DEBUG:
                print("DEBUG: calibrate BNO")
            
            self.bno.calibrateBNO()
            
            if self.DEBUG:
                print("DEBUG: new offset: {0}".format(self.bno.offset))
        
    def save(self):
        if self.DEBUG:
            print("DEBUG: Open File: "+self.saveFile)
        f = open(os.path.abspath(self.saveFile), "w")
        f.write(str(self.bno.offset))
        f.write("\n")
        f.write(str(self.gamepad.offset))
        f.close()
        self.gamepad.isSave = False
        
    def load(self):
        if self.DEBUG:
            print("DEBUG: Open File: "+self.saveFile)
        try:
            f = open(os.path.abspath(self.saveFile), "r")
        except IOError:
            if self.DEBUG:
                print("DEBUG: No SaveFile - Nothing to load")
            return
        
        if self.DEBUG:
            print("DEBUG: Loading...")
        
        loaded = f.read().replace(" ", "").split("\n")
        loaded = [loaded[0][1:-1].split(","), loaded[1][1:-1].split(",")]
        
        self.bno.offset = [float(loaded[0][0]), float(loaded[0][1]), float(loaded[0][2])]
        self.gamepad.offset = [float(loaded[1][0]), float(loaded[1][1]), float(loaded[1][2])]
        
        if self.DEBUG:
            print("Loaded! - bno-offset: {0} - gamepad-offset: {1}".format(self.bno.offset, self.gamepad.offset))
        
        f.close()
        
    def start_motors(self):
        if self.DEBUG:
            print("DEBUG: Calibrate Throttle!")
            
        if self.GUI:
            self.gui.hideMessage()
            self.gui.showMessage("Calibrate Throttle!")
        
        while self.gamepad.getThrottle()<=50:
            pygame.event.pump()
        
        while self.gamepad.getThrottle()!=0:
            pygame.event.pump()
        
        if self.DEBUG:
            print("DEBUG: Initializing motors")
            
        for m in self.motors:
            m.start()
        
        self.started = True
        
        if self.DEBUG:
            print("DEBUG: STARTED!")
        
        if self.GUI:
            self.gui.hideMessage()
    
    def stop_motors(self):
        if self.DEBUG:
            print("DEBUG: stopping motors")
            
        for m in self.motors:
            m.stop()
        
        self.started = False
        
        if self.DEBUG:
            print("DEBUG: STOPPED!")
            print("DEBUG: READY!")
            
        if self.GUI:
            self.gui.showMessage("Press 'start'-Button to start!")
        
    def changeMotorSpeed(self):
        self.throttle = [0,0,0,0]
        self.getGamepadValues()
        
        self.bno.tick()
        
        if (self.gamepad.isBNO):
            if self.DEBUG:
                print('DEBUG: Heading={0:0.2F} Roll={1:0.2F} Pitch={2:0.2F}'.format(self.bno.heading, self.bno.roll, self.bno.pitch))
            pitch = self.bno.pitch
            roll = self.bno.roll
            
            if pitch > 10:
                pitch = 10
            elif pitch < -10:
                pitch = -10
            if roll > 10:
                roll = 10
            elif roll < -10:
                roll = -10
                
            self.throttle[0] += pitch-roll
            self.throttle[1] += pitch+roll
            self.throttle[2] += -pitch+roll
            self.throttle[3] += -pitch-roll

        #Pad-Motor-Steuerung
        self.throttle[0] += -self.gamepad_axes[0]*self.stick_sens+self.gamepad.offset[0] + self.gamepad_axes[1]*self.stick_sens+self.gamepad.offset[1] - self.gamepad.offset[2]
        self.throttle[1] += -self.gamepad_axes[0]*self.stick_sens+self.gamepad.offset[0] - self.gamepad_axes[1]*self.stick_sens-self.gamepad.offset[1] + self.gamepad.offset[2]
        self.throttle[2] += +self.gamepad_axes[0]*self.stick_sens-self.gamepad.offset[0] - self.gamepad_axes[1]*self.stick_sens-self.gamepad.offset[1] - self.gamepad.offset[2]
        self.throttle[3] += +self.gamepad_axes[0]*self.stick_sens-self.gamepad.offset[0] + self.gamepad_axes[1]*self.stick_sens+self.gamepad.offset[1] + self.gamepad.offset[2]
        
        self.throttle = [int(self.gamepad_throttle+self.throttle[i]) for i in range(4)]
        
        for i in range(4):
            if self.throttle[i] > 100:
                self.throttle[i] = 100
            elif self.throttle[i] < 0:
                self.throttle[i] = 0
            self.motors[i].setW(self.throttle[i])
            
    def loop(self):
        while self.run:
            self.clock.tick(self.max_fps)
            
            pygame.event.pump()
            self.eventHandler()
            
            if self.GUI:
                self.gui.guiTick(self.clock.get_fps(), self.throttle, self.gamepad.isStart, self.gamepad.isBNO, [self.bno.heading, self.bno.pitch, self.bno.roll])
            
            if self.gamepad.isStart:
                if not self.started:
                    self.start_motors()
                self.changeMotorSpeed()
            else:
                self.checkCalibButtons()
                if self.started:
                    self.stop_motors()
コード例 #11
0
    def __init__(self, root):
        super().__init__()

        self.root = root
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)

        self.setup_video_frame()

        bottom_frame = Frame(root, relief=RAISED, borderwidth=1)
        bottom_frame.pack(fill=BOTH, expand=True)

        left_analog_frame = Frame(bottom_frame, relief=RAISED, borderwidth=1)
        digital_frame = Frame(bottom_frame,
                              relief=RAISED,
                              borderwidth=1,
                              width=150)
        right_analog_frame = Frame(bottom_frame, relief=RAISED, borderwidth=1)

        left_analog_frame.pack(fill=BOTH, expand=True, side='left')
        digital_frame.pack(fill=BOTH, expand=True, side='left')
        right_analog_frame.pack(fill=BOTH, expand=True, side='left')

        digital_button_wrapper = Frame(digital_frame)
        digital_button_wrapper.pack(fill=NONE)
        digital_button_wrapper.place(relx=.5, rely=.5, anchor="c")

        # Digital buttons
        btn_font = font.Font(weight='bold')
        self.up_button = Button(digital_button_wrapper,
                                text=u'\u2191',
                                font=btn_font)
        self.up_button.pack(side=TOP, padx=5, pady=5)
        self.down_button = Button(digital_button_wrapper,
                                  text=u'\u2193',
                                  font=btn_font)
        self.down_button.pack(side=BOTTOM, padx=5, pady=5)
        self.left_button = Button(digital_button_wrapper,
                                  text=u'\u2190',
                                  font=btn_font)
        self.left_button.pack(side=LEFT, padx=5, pady=5)
        self.right_button = Button(digital_button_wrapper,
                                   text=u'\u2192',
                                   font=btn_font)
        self.right_button.pack(side=RIGHT, padx=5, pady=5)

        # Left analog bar
        self.left_analog = Scale(left_analog_frame, from_=10, to=-10)
        self.left_analog.set(0)
        self.left_analog.pack()
        self.left_analog.place(relx=.5, rely=.5, anchor="c")

        # Right analog bar
        self.right_analog = Scale(right_analog_frame, from_=10, to=-10)
        self.right_analog.set(0)
        self.right_analog.pack()
        self.right_analog.place(relx=.5, rely=.5, anchor="c")

        self.gamepad_thread = Gamepad(self)

        self.orig_color = self.up_button.cget('background')
        self.start_gamepad()
コード例 #12
0
ファイル: main.py プロジェクト: wangqiaoli/arduino-quadcopter
class FunctionalGUI(Ui_Form):
    '''
    -----------------INITIALIZATION--------------------------------------------
    '''
    def __init__(self, window):
        super().__init__()
        self.ser = None
        self.read_timer = None
        self.gamepad_timer = None
        self.gamepad = None
        self.bytes = 0  # Used to track the amount of bytes sent
        self.packets = 0  # Used to track the amount of packets sent
        self.setupUi(window)
        self.setButtons()
        self.createGamepad()

    def setButtons(self):
        self.throttle_send_btn.clicked.connect(self.sendThrottle)
        self.throttle_reset_btn.clicked.connect(self.resetThrottle)
        self.angles_send_btn.clicked.connect(self.sendAngles)
        self.angles_reset_btn.clicked.connect(self.resetAngles)

        self.mode_raw_btn.clicked.connect(self.mode_raw)
        self.mode_rate_btn.clicked.connect(self.mode_rate)
        self.mode_angle_btn.clicked.connect(self.mode_angle)
        self.start_btn.clicked.connect(self.start)
        self.stop_btn.clicked.connect(self.stop)
        self.serial_open_btn.clicked.connect(self.openConnection)

        self.pid_send_btn.clicked.connect(self.sendPID)
        self.yaw_reset_btn.clicked.connect(self.resetYaw)

        self.gamepad_connect_btn.clicked.connect(self.createGamepad)
        self.gamepad_apply_btn.clicked.connect(self.setGamepadFrequency)

    '''
    -----------------GAMEPAD---------------------------------------------------
    '''

    def createGamepad(self):
        if self.gamepad == None:
            print("Connecting gamepad...")
            self.gamepad = Gamepad(0)
            if self.gamepad.enabled():
                self.gamepad.connectButton(0, self.addMinThrottle)
                self.gamepad.connectButton(1, self.removeMinThrottle)
                self.gamepad.connectButton(6, self.stop)
                self.gamepad.connectButton(7, self.start)
                self.gamepad.connectButton(3, self.disableGamepad)
                self.gamepad_timer = PyQt5.QtCore.QTimer()
                self.gamepad_timer.timeout.connect(self.checkGamepad)
                self.setGamepadFrequency()  # This method starts gamepad_timer
            else:
                self.gamepad.close()
                self.gamepad = None
        else:
            print("Gamepad already exists!")

    def setGamepadFrequency(self):
        if self.gamepad != None:
            self.gamepad_timer.stop()
            freq = self.gamepad_frequency_spinBox.value()
            interval = 1000 / freq  # Milliseconds
            self.gamepad_timer.start(interval)
            print("Gamepad updating rate is now", freq,
                  "({:f} ms)".format(interval))
        else:
            print("Gamepad doesn't exist!")

    def checkGamepad(self):
        if self.gamepad != None:
            self.gamepad.update()
            y, p, r = self.gamepad.getYPR()
            throttle = self.gamepad.getThrottle()
            self.changeYPR(y, p, r)
            self.changeThrottle(throttle)
            if self.angles_sendOnChange_bool.isChecked():
                self.sendAngles()
            if self.throttle_sendOnChange_bool.isChecked():
                self.sendThrottle()

    def disableGamepad(self):
        print("Disabling gamepad")
        self.resetThrottle()
        if self.gamepad != None:
            self.gamepad.close()
            self.gamepad = None

    '''
    -----------------BUTTONS---------------------------------------------------
    '''

    # --------------Primary control--------------------------------------------

    def changeYPR(self, yaw, pitch, roll):
        self.yaw_doubleSpinBox.setValue(yaw * self.yaw_max_spinbox.value())
        self.pitch_doubleSpinBox.setValue(pitch *
                                          self.pitch_max_spinbox.value())
        self.roll_doubleSpinBox.setValue(roll * self.roll_max_spinbox.value())

    def changeThrottle(self, throttle_input):
        # Input goes from 0 to 1
        self.throttle_spinBox.setValue(throttle_input *
                                       self.throttle_max_spinBox.value())

    def addMinThrottle(self):
        prev = self.throttle_offset_spinBox.value()
        increment = self.throttle_offset_step_spinBox.value()
        self.throttle_offset_spinBox.setValue(prev + increment)
        print("Setting default throttle to:",
              self.throttle_offset_spinBox.value())

    def removeMinThrottle(self):
        prev = self.throttle_offset_spinBox.value()
        increment = self.throttle_offset_step_spinBox.value()
        self.throttle_offset_spinBox.setValue(prev - increment)
        if self.throttle_offset_spinBox.value() < 0:
            self.throttle_offset_spinBox.setValue(0)
        print("Setting default throttle to:",
              self.throttle_offset_spinBox.value())

    def sendAngles(self):
        y = self.yaw_doubleSpinBox.value(
        ) + self.yaw_offset_doubleSpinBox.value()
        p = self.pitch_doubleSpinBox.value(
        ) + self.pitch_offset_doubleSpinBox.value()
        r = self.roll_doubleSpinBox.value(
        ) + self.roll_offset_doubleSpinBox.value()
        string = 'y' + str(y)
        string += 'p' + str(p)
        string += 'r' + str(r)
        self.send(string)

    def sendThrottle(self):
        thr = self.throttle_spinBox.value(
        ) + self.throttle_offset_spinBox.value()
        string = 't' + str(thr)
        self.send(string)

    # --------------Secondary control------------------------------------------

    def start(self):
        self.send(chr(17))
        print("Activating engines")

    def stop(self):
        #self.resetAngles()
        self.resetThrottle()
        self.send(chr(20))  #DC4
        print("Disabling engines")

    def resetYaw(self):
        '''
        Resets the yaw axis of copter to zero.
        '''
        self.send('r')
        print("Resetting yaw axis")

    def mode_raw(self):
        '''
        Starts the raw controlling mode.
        Angles correspond to motor powers without PID.
        '''
        self.send('m2')
        print("Switching to raw control")

    def mode_rate(self):
        '''
        Starts the rate controlling mode.
        Angles correspond to angular rates.
        '''
        self.send('m1')
        print("Switching to rate control")

    def mode_angle(self):
        '''
        Starts the angle controlling mode.
        Angles correspond to actual orientation of the copter.
        '''
        self.send('m0')
        print("Switching to angle control")

    def resetAngles(self):
        self.yaw_doubleSpinBox.setValue(0)
        self.pitch_doubleSpinBox.setValue(0)
        self.roll_doubleSpinBox.setValue(0)
        self.yaw_offset_doubleSpinBox.setValue(0)
        self.pitch_offset_doubleSpinBox.setValue(0)
        self.roll_offset_doubleSpinBox.setValue(0)
        self.sendAngles()

    def resetThrottle(self):
        self.throttle_offset_spinBox.setValue(0)
        self.throttle_spinBox.setValue(0)
        self.sendThrottle()

    # --------------Other commands---------------------------------------------
    def sendPID(self):
        self.send('p' + str(self.pid_rollpitch_p.value()))
        self.send('i' + str(self.pid_rollpitch_i.value()))
        self.send('w' + str(self.pid_yaw_p.value()))
        print("All pid values sent!")

    # ----------------GUI------------------------------------------------------
    '''
    -----------------SERIAL STUFF----------------------------------------------
    '''

    def openConnection(self):
        print("Opening bluetooth connection...")
        self.ser = serial.Serial(
            port=None,
            baudrate=115200,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.EIGHTBITS,
            writeTimeout=2)  # Wait maximum 2 seconds on write
        if (self.read_timer == None):
            self.read_timer = PyQt5.QtCore.QTimer()
        self.read_timer.timeout.connect(self.readSerial)
        self.read_timer.start(100)
        for i in range(10):
            try:
                print("Trying port", i)
                self.ser.port = '/dev/rfcomm' + str(i)
                self.ser.open()
                print("Bluetooth open!")
                return  # Success!
            except serial.serialutil.SerialException:
                print("Cannot open bluetooth at port", i)
        self.ser = None  # Opening failed

    def send(self, message):
        if (self.ser != None):
            message = chr(2) + message  #STX
            message += chr(3)  #ETX
            self.packets += 1
            self.bytes += len(message)
            self.data_label.setText(str(self.bytes))
            self.packet_label.setText(str(self.packets))
            try:
                self.ser.write(message.encode())
            except serial.serialutil.SerialTimeoutException:
                print("WARNING: Write timeout exceeded!")
                print("WARNING: Bluetooth disconnected")
                self.ser = None

    def readSerial(self):
        if (self.ser != None):
            while (self.ser.inWaiting() > 0):
                try:
                    c = self.ser.read(1).decode()
                    print("{:}".format(c), end='')
                    if (c == chr(5)):
                        self.send(chr(6))
                except UnicodeDecodeError:
                    print("UnicodeDecodeError: Received bad data")
        else:
            self.read_timer.stop()

    '''
コード例 #13
0
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import board
import digitalio
import analogio
import usb_hid

from gamepad import Gamepad

gp = Gamepad(usb_hid.devices)

# Create some buttons. The physical buttons are connected
# to ground on one side and these and these pins on the other.
button_pins = (board.D2, board.D3, board.D4, board.D5)

# Map the buttons to button numbers on the Gamepad.
# gamepad_buttons[i] will send that button number when buttons[i]
# is pushed.
gamepad_buttons = (1, 2, 8, 15)

buttons = [digitalio.DigitalInOut(pin) for pin in button_pins]
for button in buttons:
    button.direction = digitalio.Direction.INPUT
    button.pull = digitalio.Pull.UP

# Connect an analog two-axis joystick to A4 and A5.
ax = analogio.AnalogIn(board.A4)
ay = analogio.AnalogIn(board.A5)

コード例 #14
0
class Window(Frame):
    def __init__(self, root):
        super().__init__()

        self.root = root
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)

        self.setup_video_frame()

        bottom_frame = Frame(root, relief=RAISED, borderwidth=1)
        bottom_frame.pack(fill=BOTH, expand=True)

        left_analog_frame = Frame(bottom_frame, relief=RAISED, borderwidth=1)
        digital_frame = Frame(bottom_frame,
                              relief=RAISED,
                              borderwidth=1,
                              width=150)
        right_analog_frame = Frame(bottom_frame, relief=RAISED, borderwidth=1)

        left_analog_frame.pack(fill=BOTH, expand=True, side='left')
        digital_frame.pack(fill=BOTH, expand=True, side='left')
        right_analog_frame.pack(fill=BOTH, expand=True, side='left')

        digital_button_wrapper = Frame(digital_frame)
        digital_button_wrapper.pack(fill=NONE)
        digital_button_wrapper.place(relx=.5, rely=.5, anchor="c")

        # Digital buttons
        btn_font = font.Font(weight='bold')
        self.up_button = Button(digital_button_wrapper,
                                text=u'\u2191',
                                font=btn_font)
        self.up_button.pack(side=TOP, padx=5, pady=5)
        self.down_button = Button(digital_button_wrapper,
                                  text=u'\u2193',
                                  font=btn_font)
        self.down_button.pack(side=BOTTOM, padx=5, pady=5)
        self.left_button = Button(digital_button_wrapper,
                                  text=u'\u2190',
                                  font=btn_font)
        self.left_button.pack(side=LEFT, padx=5, pady=5)
        self.right_button = Button(digital_button_wrapper,
                                   text=u'\u2192',
                                   font=btn_font)
        self.right_button.pack(side=RIGHT, padx=5, pady=5)

        # Left analog bar
        self.left_analog = Scale(left_analog_frame, from_=10, to=-10)
        self.left_analog.set(0)
        self.left_analog.pack()
        self.left_analog.place(relx=.5, rely=.5, anchor="c")

        # Right analog bar
        self.right_analog = Scale(right_analog_frame, from_=10, to=-10)
        self.right_analog.set(0)
        self.right_analog.pack()
        self.right_analog.place(relx=.5, rely=.5, anchor="c")

        self.gamepad_thread = Gamepad(self)

        self.orig_color = self.up_button.cget('background')
        self.start_gamepad()

    def setup_video_frame(self):
        self.video_thread = VideoClient()
        self.video_thread.start()

    def update_left_analog(self, value):
        self.left_analog.set(value)

    def update_right_analog(self, value):
        self.right_analog.set(value)

    def update_digital(self, value):
        def paint_buttons(button1, button2, index):
            if value[index] == 0:
                button1.configure(bg=self.orig_color)
                button2.configure(bg=self.orig_color)
            elif value[index] == -1:
                button1.configure(bg='cyan')
                button2.configure(bg=self.orig_color)
            else:
                button1.configure(bg=self.orig_color)
                button2.configure(bg='cyan')

        paint_buttons(self.left_button, self.right_button, 0)
        paint_buttons(self.down_button, self.up_button, 1)

    def set_status(self, value):
        self.root.title('{} - {}'.format(TITLE, value))

    def on_closing(self):
        self.gamepad_thread.stop()
        self.gamepad_thread.join()
        self.video_thread.stop()
        self.video_thread.join()
        sleep(1)
        self.root.destroy()

    def start_gamepad(self):
        self.gamepad_thread.start()
コード例 #15
0
"""
Author: Leo Vidarte <http://nerdlabs.com.ar>

This is free software,
you can redistribute it and/or modify it
under the terms of the GPL version 3
as published by the Free Software Foundation.

"""

from gamepad import Gamepad
from serial import Serial

serial = Serial('/dev/ttyUSB0', 9600)
gamepad = Gamepad(serial)


def move(event):
    print 'move', event.state.get_axes()


def move_x(event):
    print 'move-x', event.state.x


def move_y(event):
    print 'move-y', event.state.y


def move_left(event):
    print 'move-left', event.state.x
コード例 #16
0
    | (1 << BUTTON_DOWN)
    | (1 << BUTTON_LEFT)
    | (1 << BUTTON_UP)
    | (1 << BUTTON_SEL)
)

i2c = busio.I2C(board.SCL, board.SDA)

ss = adafruit_seesaw.Seesaw(i2c)

ss.pin_mode_bulk(button_mask, ss.INPUT_PULLUP)

last_game_x = 0
last_game_y = 0

g = Gamepad(usb_hid.devices)

while True:
    x = ss.analog_read(2)
    y = ss.analog_read(3)

    game_x = range_map(x, 0, 1023, -127, 127)
    game_y = range_map(y, 0, 1023, -127, 127)
    if last_game_x != game_x or last_game_y != game_y:
        last_game_x = game_x
        last_game_y = game_y
        print(game_x, game_y)
        g.move_joysticks(x=game_x, y=game_y)

    buttons = (BUTTON_RIGHT, BUTTON_DOWN, BUTTON_LEFT, BUTTON_UP, BUTTON_SEL)
    button_state = [False] * len(buttons)
コード例 #17
0
 def InitializeGamepad(self, request, context):
     client_uuid_str = str(uuid.uuid4())
     print(f"Creating client with uuid {client_uuid_str}")
     self.gamepads[client_uuid_str] = Gamepad(uuid=client_uuid_str)
     return gamepad_pb2.ClientID(client_id=client_uuid_str)
コード例 #18
0
ファイル: moving.py プロジェクト: lvidarte/arduino-gamepad
"""
Author: Leo Vidarte <http://nerdlabs.com.ar>

This is free software,
you can redistribute it and/or modify it
under the terms of the GPL version 3
as published by the Free Software Foundation.

"""

import time
from gamepad import Gamepad
from serial import Serial

serial = Serial('/dev/ttyUSB0', 9600)
gamepad = Gamepad(serial)

"""
this is the way to repeat some code on
the following events

 * move-left
 * move-right
 * move-up
 * move-down
"""

def move(event):
    while gamepad.is_holding(event):
        print 'move',
        if event.is_move_left():
コード例 #19
0
ファイル: full.py プロジェクト: manasdas17/arduino-gamepad
from gamepad import Gamepad
from serial import Serial

serial = Serial('/dev/ttyUSB0', 9600)
gamepad = Gamepad(serial)

def move(event):
    print 'move', event.state.get_axes()

def move_x(event):
    print 'move-x', event.state.x

def move_y(event):
    print 'move-y', event.state.y

def move_left(event):
    print 'move-left', event.state.x

def move_right(event):
    print 'move-right', event.state.x

def move_up(event):
    print 'move-up', event.state.y

def move_down(event):
    print 'move-down', event.state.y

def move_center(event):
    print 'move-center', event.state.get_axes()

def switch(event):
コード例 #20
0
ファイル: main.py プロジェクト: debnera/arduino-quadcopter
class FunctionalGUI(Ui_Form):

    '''
    -----------------INITIALIZATION--------------------------------------------
    '''

    def __init__(self, window):
        super().__init__()
        self.ser = None
        self.read_timer = None
        self.gamepad_timer = None
        self.gamepad = None
        self.bytes = 0 # Used to track the amount of bytes sent
        self.packets = 0 # Used to track the amount of packets sent
        self.setupUi(window)
        self.setButtons()
        self.createGamepad()

    def setButtons(self):
        self.throttle_send_btn.clicked.connect(self.sendThrottle)
        self.throttle_reset_btn.clicked.connect(self.resetThrottle)
        self.angles_send_btn.clicked.connect(self.sendAngles)
        self.angles_reset_btn.clicked.connect(self.resetAngles)

        self.mode_raw_btn.clicked.connect(self.mode_raw)
        self.mode_rate_btn.clicked.connect(self.mode_rate)
        self.mode_angle_btn.clicked.connect(self.mode_angle)
        self.start_btn.clicked.connect(self.start)
        self.stop_btn.clicked.connect(self.stop)
        self.serial_open_btn.clicked.connect(self.openConnection)

        self.pid_send_btn.clicked.connect(self.sendPID)
        self.yaw_reset_btn.clicked.connect(self.resetYaw)

        self.gamepad_connect_btn.clicked.connect(self.createGamepad)
        self.gamepad_apply_btn.clicked.connect(self.setGamepadFrequency)



    '''
    -----------------GAMEPAD---------------------------------------------------
    '''

    def createGamepad(self):
        if self.gamepad == None:
            print("Connecting gamepad...")
            self.gamepad = Gamepad(0)
            if self.gamepad.enabled():
                self.gamepad.connectButton(0, self.addMinThrottle)
                self.gamepad.connectButton(1, self.removeMinThrottle)
                self.gamepad.connectButton(6, self.stop)
                self.gamepad.connectButton(7, self.start)
                self.gamepad.connectButton(3, self.disableGamepad)
                self.gamepad_timer = PyQt5.QtCore.QTimer()
                self.gamepad_timer.timeout.connect(self.checkGamepad)
                self.setGamepadFrequency() # This method starts gamepad_timer
            else:
                self.gamepad.close()
                self.gamepad = None
        else:
            print("Gamepad already exists!")

    def setGamepadFrequency(self):
        if self.gamepad != None:
            self.gamepad_timer.stop()
            freq = self.gamepad_frequency_spinBox.value()
            interval = 1000 / freq # Milliseconds
            self.gamepad_timer.start(interval)
            print("Gamepad updating rate is now", freq, "({:f} ms)".format(interval))
        else:
            print("Gamepad doesn't exist!")

    def checkGamepad(self):
        if self.gamepad != None:
            self.gamepad.update()
            y, p, r = self.gamepad.getYPR()
            throttle = self.gamepad.getThrottle()
            self.changeYPR(y, p, r)
            self.changeThrottle(throttle)
            if self.angles_sendOnChange_bool.isChecked():
                self.sendAngles()
            if self.throttle_sendOnChange_bool.isChecked():
                self.sendThrottle()

    def disableGamepad(self):
        print("Disabling gamepad")
        self.resetThrottle()
        if self.gamepad != None:
            self.gamepad.close()
            self.gamepad = None

    '''
    -----------------BUTTONS---------------------------------------------------
    '''

    # --------------Primary control--------------------------------------------

    def changeYPR(self, yaw, pitch, roll):
        self.yaw_doubleSpinBox.setValue(yaw * self.yaw_max_spinbox.value())
        self.pitch_doubleSpinBox.setValue(pitch * self.pitch_max_spinbox.value())
        self.roll_doubleSpinBox.setValue(roll * self.roll_max_spinbox.value())

    def changeThrottle(self, throttle_input):
        # Input goes from 0 to 1
        self.throttle_spinBox.setValue(throttle_input * self.throttle_max_spinBox.value())

    def addMinThrottle(self):
        prev = self.throttle_offset_spinBox.value()
        increment = self.throttle_offset_step_spinBox.value()
        self.throttle_offset_spinBox.setValue(prev + increment)
        print("Setting default throttle to:", self.throttle_offset_spinBox.value())

    def removeMinThrottle(self):
        prev = self.throttle_offset_spinBox.value()
        increment = self.throttle_offset_step_spinBox.value()
        self.throttle_offset_spinBox.setValue(prev - increment)
        if self.throttle_offset_spinBox.value() < 0:
            self.throttle_offset_spinBox.setValue(0)
        print("Setting default throttle to:", self.throttle_offset_spinBox.value())

    def sendAngles(self):
        y = self.yaw_doubleSpinBox.value() + self.yaw_offset_doubleSpinBox.value()
        p = self.pitch_doubleSpinBox.value() + self.pitch_offset_doubleSpinBox.value()
        r = self.roll_doubleSpinBox.value() + self.roll_offset_doubleSpinBox.value()
        string = 'y' + str(y)
        string += 'p' + str(p)
        string += 'r' + str(r)
        self.send(string)

    def sendThrottle(self):
        thr = self.throttle_spinBox.value() + self.throttle_offset_spinBox.value()
        string = 't' + str(thr)
        self.send(string)

    # --------------Secondary control------------------------------------------

    def start(self):
        self.send(chr(17))
        print("Activating engines")

    def stop(self):
        #self.resetAngles()
        self.resetThrottle()
        self.send(chr(20)) #DC4
        print("Disabling engines")

    def resetYaw(self):
        '''
        Resets the yaw axis of copter to zero.
        '''
        self.send('r')
        print("Resetting yaw axis")

    def mode_raw(self):
        '''
        Starts the raw controlling mode.
        Angles correspond to motor powers without PID.
        '''
        self.send('m2')
        print("Switching to raw control")

    def mode_rate(self):
        '''
        Starts the rate controlling mode.
        Angles correspond to angular rates.
        '''
        self.send('m1')
        print("Switching to rate control")

    def mode_angle(self):
        '''
        Starts the angle controlling mode.
        Angles correspond to actual orientation of the copter.
        '''
        self.send('m0')
        print("Switching to angle control")

    def resetAngles(self):
        self.yaw_doubleSpinBox.setValue(0)
        self.pitch_doubleSpinBox.setValue(0)
        self.roll_doubleSpinBox.setValue(0)
        self.yaw_offset_doubleSpinBox.setValue(0)
        self.pitch_offset_doubleSpinBox.setValue(0)
        self.roll_offset_doubleSpinBox.setValue(0)
        self.sendAngles()

    def resetThrottle(self):
        self.throttle_offset_spinBox.setValue(0)
        self.throttle_spinBox.setValue(0)
        self.sendThrottle()


    # --------------Other commands---------------------------------------------
    def sendPID(self):
        self.send('p' + str(self.pid_rollpitch_p.value()))
        self.send('i' + str(self.pid_rollpitch_i.value()))
        self.send('w' + str(self.pid_yaw_p.value()))
        print("All pid values sent!")


    # ----------------GUI------------------------------------------------------



    '''
    -----------------SERIAL STUFF----------------------------------------------
    '''


    def openConnection(self):
        print("Opening bluetooth connection...")
        self.ser = serial.Serial(
        port=None,
        baudrate=115200,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        writeTimeout=2) # Wait maximum 2 seconds on write
        if (self.read_timer == None):
            self.read_timer = PyQt5.QtCore.QTimer()
        self.read_timer.timeout.connect(self.readSerial)
        self.read_timer.start(100)
        for i in range(10):
            try:
                print("Trying port", i)
                self.ser.port = '/dev/rfcomm' + str(i)
                self.ser.open()
                print("Bluetooth open!")
                return # Success!
            except serial.serialutil.SerialException:
                print("Cannot open bluetooth at port", i)
        self.ser = None # Opening failed


    def send(self, message):
        if (self.ser != None):
            message = chr(2) + message  #STX
            message += chr(3) #ETX
            self.packets += 1
            self.bytes += len(message)
            self.data_label.setText(str(self.bytes))
            self.packet_label.setText(str(self.packets))
            try:
                self.ser.write(message.encode())
            except serial.serialutil.SerialTimeoutException:
                print("WARNING: Write timeout exceeded!")
                print("WARNING: Bluetooth disconnected")
                self.ser = None

    def readSerial(self):
        if (self.ser != None):
            while (self.ser.inWaiting() > 0):
                try:
                    c = self.ser.read(1).decode()
                    print("{:}".format(c), end='')
                    if (c == chr(5)):
                        self.send(chr(6))
                except UnicodeDecodeError:
                    print("UnicodeDecodeError: Received bad data")
        else:
            self.read_timer.stop()

    '''
コード例 #21
0
ファイル: moving.py プロジェクト: lvidarte/arduino-gamepad
"""
Author: Leo Vidarte <http://nerdlabs.com.ar>

This is free software,
you can redistribute it and/or modify it
under the terms of the GPL version 3
as published by the Free Software Foundation.

"""

import time
from gamepad import Gamepad
from serial import Serial

serial = Serial('/dev/ttyUSB0', 9600)
gamepad = Gamepad(serial)
"""
this is the way to repeat some code on
the following events

 * move-left
 * move-right
 * move-up
 * move-down
"""


def move(event):
    while gamepad.is_holding(event):
        print 'move',
        if event.is_move_left():
コード例 #22
0
ファイル: main.py プロジェクト: schmidma/PiCopter
    def __init__(self, GUI, DEBUG, fps, stick_sens, saveFile):
        self.GUI = GUI
        self.DEBUG = DEBUG
        self.max_fps = fps
        self.stick_sens = stick_sens
        self.saveFile = saveFile
        
        pygame.init()
        
        self.clock = pygame.time.Clock()
    
        self.run = True
        self.started = False
    
        self.main_throttle = 0
        self.throttle = [0,0,0,0]

        self.holdPosition = 0
        self.holdHeight = 0
        self.isGamepad = 1
        
        self.gamepad = Gamepad()
        self.gamepad_axes = [0,0,0]
        self.gamepad_throttle = 0
        
        self.bno = BNO()
        
        self.m1 = Motor(15)
        self.m2 = Motor(27)
        self.m3 = Motor(10)
        self.m4 = Motor(7)
        
        self.motors = [self.m1, self.m2, self.m3, self.m4]
        
        if self.GUI:
            self.gui = Gui()
        
        if self.GUI:
            self.gui.showMessage("Press 'start'-Button to start!")
        
        if self.DEBUG:
            # Print system status and self test result.
            status, self_test, error = self.bno.get_system_status()
            print("DEBUG: System status: {0}".format(status))
            print("DEBUG: Self test result (0x0F is normal): 0x{0:02X}".format(self_test))
            # Print out an error if system status is in error mode.
            if status == 0x01:
                print("DEBUG: System error: {0}".format(error))
                print("DEBUG: See datasheet section 4.3.59 for the meaning.")
            
            # Print BNO055 software revision and other diagnostic data.
            sw, bl, accel, mag, gyro = self.bno.get_revision()
            print("DEBUG: Software version:   {0}".format(sw))
            print("DEBUG: Bootloader version: {0}".format(bl))
            print("DEBUG: Accelerometer ID:   0x{0:02X}".format(accel))
            print("DEBUG: Magnetometer ID:    0x{0:02X}".format(mag))
            print("DEBUG: Gyroscope ID:       0x{0:02X}\n".format(gyro))
            
        self.load()
        
        if self.DEBUG:
            print("DEBUG: READY!")
        
        self.loop()
コード例 #23
0
class JogController:
    def __init__(self, grbl):
        self.step_size = 0.1  # mm
        self.max_feedrate = 1000
        self.loop_delay = 0.02

        self.jogging = False
        self.stepping = False
        self.grbl = grbl

        self.gamepad = Gamepad()

        # Feed hold
        self.gamepad.on('l1', lambda *a: grbl.send(b'!'))

        # Resume cycle
        self.gamepad.on('l2', lambda *a: grbl.send(b'~'))

        self.gamepad.on('btn11', self.toggle_stepping)  # left axis btn
        self.gamepad.on('select', lambda *a: grbl.soft_reset())
        self.gamepad.on('start', lambda *a: grbl.unlock())
        self.gamepad.on('dpady', self.on_dpady)

        # zero X-axis work coordinates
        self.gamepad.on('btn2', lambda *a: grbl.set_active_coord_system(x=0))

        # zero Y-axis work coordinates
        self.gamepad.on('btn1',
                        lambda *a: self.grbl.set_active_coord_system(y=0))

        # zero Z-axis work coordinates
        self.gamepad.on('btn3',
                        lambda *a: self.grbl.set_active_coord_system(z=0))

    def start(self):
        self._running = True
        self.thread = Thread(target=self.run)
        self.thread.daemon = True
        self.thread.start()

    def stop(self):
        self._running = False
        self.thread.join()
        del self.thread

    def run(self):
        while self._running:
            if self.gamepad.connected:
                self._do_jog()

    def toggle_stepping(self, *a):
        self.stepping = not self.stepping
        print("stepping: {}".format(self.stepping))

    def cancel_jog(self, *a):
        print("cancel jog (0x85)")
        self.grbl.jog_cancel()
        self.jogging = False

    def on_dpady(self, value, event):
        self.max_feedrate *= (1 - 0.1 * value)
        print("max feedrate: {}".format(self.max_feedrate))

    def _do_jog(self):
        sleep(0.005)

        # create vector from controller inputs (invert Y)

        v = V(
            self.gamepad.axis('lx'),
            -self.gamepad.axis('ly'),
            -self.gamepad.axis('ry'),
        )

        if v.length > 1e-5:
            if self.stepping and self.jogging:
                return
            self.jogging = True
        else:
            if self.jogging:
                self.cancel_jog()
            return

        feedrate = int(v.length * self.max_feedrate)
        step_size_mod = self.step_size * (feedrate / self.max_feedrate)
        delta = v.normal * step_size_mod

        self.grbl.jog(feedrate, x=delta.x, y=delta.y, z=delta.z)