Пример #1
0
def main():
    try:
        """
        * Allocate a new Phidget Channel object
        """
        try:
            ch = DCMotor()
        except PhidgetException as e:
            sys.stderr.write("Runtime Error -> Creating DCMotor: \n\t")
            DisplayError(e)
            raise
        except RuntimeError as e:
            sys.stderr.write("Runtime Error -> Creating DCMotor: \n\t" + e)
            raise
        """
        * Set matching parameters to specify which channel to open
        """
        #You may remove this line and hard-code the addressing parameters to fit your application
        #channelInfo = AskForDeviceParameters(ch)

        ch.setDeviceSerialNumber(473647)
        ch.setHubPort(-1)
        ch.setIsHubPortDevice(False)
        ch.setChannel(0)
        """
        * Add event handlers before calling open so that no events are missed.
        """
        print("\n--------------------------------------")
        print("\nSetting OnAttachHandler...")
        ch.setOnAttachHandler(onAttachHandler)

        print("Setting OnDetachHandler...")
        ch.setOnDetachHandler(onDetachHandler)

        print("Setting OnErrorHandler...")
        ch.setOnErrorHandler(onErrorHandler)

        print("\nSetting OnVelocityUpdateHandler...")
        ch.setOnVelocityUpdateHandler(onVelocityUpdateHandler)
        """
        * Open the channel with a timeout
        """
        print("\nOpening and Waiting for Attachment...")

        try:
            ch.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch)
            raise EndProgramSignal("Program Terminated: Open Failed")

        print(
            "--------------------\n"
            "\nInput a desired velocity/acceleration value and press ENTER\n"
            'Velocity Syntax: "v100" will set the motor speed to 100% in the positive direction \n'
            'and calling "v-52" will set the motor speed to 52% in the negative direction \n'
            '\nAcceleration Syntax: "a25" will set the motor acceleration to 25dty/s^2'
            "\nThe motor cannot accelerate any faster than 62.5 dty/s^2 or slower than 0.28 dty/s^2\n"
            '\nTo enter cyclic mode, press "c" or "C" and the program will run with stored parameters'
            '\nTo modify the cyclic mode parameters, edit this python file and edit the variables at'
            '\nthe top of the file.\n'
            '\nNote: Due to some limitations within Python, once cyclic mode is engaged the only'
            '\nway to quit cyclic mode is to use Control + C (Command + C on a Mac). This ends the'
            '\nentire program, and will stop the motor instantly. For this reason, if please consider'
            '\nusing a small number of cycles so that you do not have to wait for them all to finish\n'
            '\nInput "Q" and press ENTER to come to a hard stop\n'
            '\nInput "S" and press ENTER to come to a soft stop\n')

        end = False

        while (end != True):
            buf = sys.stdin.readline(100)
            if not buf:
                continue

            if (buf[0] == 'Q' or buf[0] == 'q'):
                end = True
                continue

            if (buf[0] == 'v' or buf[0] == 'V'):  #set velocity of the motor
                try:
                    velocity = float(buf[1:])
                except ValueError as e:
                    print("Input must be a number, or Q to quit.")
                    continue

                if (velocity > 100.0):
                    velocity = 100.0
                    print("WARNING: MAXIMUM velocity is +/- 100%")

                if (velocity < -100.0):
                    velocity = -100.0
                    print("WARNING: MAXIMUM velocity is +/- 100%")

                print("Setting DCMotor TargetVelocity to " + str(velocity) +
                      "%")
                ch.setTargetVelocity(velocity / 100)

            elif (buf[0] == 'a'
                  or buf[0] == 'A'):  #set acceleration of the motor
                try:
                    acceleration = float(buf[1:])
                except ValueError as e:
                    print(
                        "Input must be a number, V for velocity, A for acceleration or Q to quit."
                    )
                    continue

                if (acceleration > 62.5):
                    acceleration = 62.5
                    print("WARNING: Maximum acceleration is 62.5 dty/s^2")

                if (acceleration < 0.28):
                    acceleration = 0.28
                    print("WARNING: Minimum acceleration is 0.28 dty/s^2")

                print("Setting DCMotor Acceleration to " + str(acceleration) +
                      " dty/s^2")
                ch.setAcceleration(acceleration)

            elif (buf[0] == 'c' or buf[0] == 'C'):
                print("Entering Cycle Mode")
                for i in range(n):
                    print("Beginning cycle " + str(i + 1))
                    print("Setting Velocity to " + str(omega_1) + "%")
                    ch.setTargetVelocity(omega_1 / 100)
                    time.sleep(t_half)
                    #calculate acceleration
                    ch.setAcceleration(
                        abs(((omega_1 / 100) - (omega_2 / 100)) / t_0))
                    print("Setting Velocity to " + str(omega_2) + "%")
                    ch.setTargetVelocity(omega_2 / 100)
                    time.sleep(t_0)
                    time.sleep(t_1)
                    print("Setting Velocity to " + str(omega_1) + "%")
                    ch.setTargetVelocity(omega_1 / 100)
                    time.sleep(t_0)
                    time.sleep(t_half)
                print("Exiting Cycle Mode")
                print("Velocity currently set to " +
                      str(ch.getVelocity() * 100) + "%")

            elif (buf[0] == 's' or buf[0] == 'S'):
                print("Initiating Soft Stop")
                ch.setAcceleration(ch.getMinAcceleration())
                ch.setTargetVelocity(0)
                while (ch.getVelocity() > 0):
                    time.sleep(0.1)
                print("Motor Stopped")
                end = True
                continue

            else:
                print("WARNING: Invalid Command")
        '''
        * Perform clean up and exit
        '''

        #clear the VelocityUpdate event handler
        ch.setOnVelocityUpdateHandler(None)

        print("Cleaning up...")
        ch.close()
        print("\nExiting...")
        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        traceback.print_exc()
        print("Cleaning up...")
        #clear the VelocityUpdate event handler
        ch.setOnVelocityUpdateHandler(None)
        ch.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        #clear the VelocityUpdate event handler
        ch.setOnVelocityUpdateHandler(None)
        ch.close()
        return 1
    finally:
        pass
Пример #2
0
def main():
    try:
        """
        * Allocate a new Phidget Channel object
        """
        try:
            ch = DCMotor()
        except PhidgetException as e:
            sys.stderr.write("Runtime Error -> Creating DCMotor: \n\t")
            DisplayError(e)
            raise
        except RuntimeError as e:
            sys.stderr.write("Runtime Error -> Creating DCMotor: \n\t" + e)
            raise

        """
        * Set matching parameters to specify which channel to open
        """
        #You may remove this line and hard-code the addressing parameters to fit your application
        channelInfo = AskForDeviceParameters(ch)
        
        ch.setDeviceSerialNumber(channelInfo.deviceSerialNumber)
        ch.setHubPort(channelInfo.hubPort)
        ch.setIsHubPortDevice(channelInfo.isHubPortDevice)
        ch.setChannel(channelInfo.channel)   
        
        if(channelInfo.netInfo.isRemote):
            ch.setIsRemote(channelInfo.netInfo.isRemote)
            if(channelInfo.netInfo.serverDiscovery):
                try:
                    Net.enableServerDiscovery(PhidgetServerType.PHIDGETSERVER_DEVICEREMOTE)
                except PhidgetException as e:
                    PrintEnableServerDiscoveryErrorMessage(e)
                    raise EndProgramSignal("Program Terminated: EnableServerDiscovery Failed")
            else:
                Net.addServer("Server", channelInfo.netInfo.hostname,
                    channelInfo.netInfo.port, channelInfo.netInfo.password, 0)
        
        """
        * Add event handlers before calling open so that no events are missed.
        """
        print("\n--------------------------------------")
        print("\nSetting OnAttachHandler...")
        ch.setOnAttachHandler(onAttachHandler)
        
        print("Setting OnDetachHandler...")
        ch.setOnDetachHandler(onDetachHandler)
        
        print("Setting OnErrorHandler...")
        ch.setOnErrorHandler(onErrorHandler)

        #This call may be harmlessly removed
        PrintEventDescriptions()
        
        print("\nSetting OnVelocityUpdateHandler...")
        ch.setOnVelocityUpdateHandler(onVelocityUpdateHandler)
        
        """
        * Open the channel with a timeout
        """
        print("\nOpening and Waiting for Attachment...")
        
        try:
            ch.openWaitForAttachment(5000)
        except PhidgetException as e:
            PrintOpenErrorMessage(e, ch)
            raise EndProgramSignal("Program Terminated: Open Failed")

        print("--------------------\n"
        "\n  | DC motor speed can be controlled by setting its Target Velocity (ie its duty cycle).\n"
        "  | The target velocity can be a number from -1.0 to +1.0, where sign indicates direction of rotation.\n"
        "  | For this example, acceleration has been fixed to 1.0Hz, but can be changed in custom code.\n"

        "\nInput a desired velocity between -1.0 and 1.0 and press ENTER\n"
        "Input Q and press ENTER to quit\n")

        end = False

        while (end != True):
            buf = sys.stdin.readline(100)
            if not buf:
                continue

            if (buf[0] == 'Q' or buf[0] ==  'q'):
                end = True
                continue
            
            try:
                velocity = float(buf)
            except ValueError as e:
                print("Input must be a number, or Q to quit.")
                continue

            if (velocity > 1.0):
                velocity = 1.0
                print("MAXIMUM velocity is +/-1.0")

            if (velocity < -1.0):
                velocity = -1.0
                print("MAXIMUM velocity is +/-1.0")

            print("Setting DCMotor TargetVelocity to " + str(velocity))
            ch.setTargetVelocity(velocity)

        '''
        * Perform clean up and exit
        '''

        #clear the VelocityUpdate event handler 
        ch.setOnVelocityUpdateHandler(None)  

        print("Cleaning up...")
        ch.close()
        print("\nExiting...")
        return 0

    except PhidgetException as e:
        sys.stderr.write("\nExiting with error(s)...")
        DisplayError(e)
        traceback.print_exc()
        print("Cleaning up...")
        #clear the VelocityUpdate event handler 
        ch.setOnVelocityUpdateHandler(None)  
        ch.close()
        return 1
    except EndProgramSignal as e:
        print(e)
        print("Cleaning up...")
        #clear the VelocityUpdate event handler 
        ch.setOnVelocityUpdateHandler(None)  
        ch.close()
        return 1
    finally:
        print("Press ENTER to end program.")
        readin = sys.stdin.readline()
Пример #3
0
        time.sleep(2)
    else:
        for ev in pygame.event.get(pygame.JOYAXISMOTION):
            if ev.axis == STEER_AXIS:
                val = interp(ev.value, [-1, 1], [50,130])
                print("val from joy stick:", val)
                servo_ch.setTargetPosition(val)
            if ev.axis == GEAR_CHANGE_AXIS:
                if ev.value < (-0.7):
                    motor_direction = 1
                    print("dirction changed to Forward")
                elif ev.value > (0.7):
                    motor_direction = -1
                    print("dirction changed to Backward")
            if ev.axis == THROTTLE_AXIS:
                val = interp(ev.value, [-1, 1], [0,1])
                motor_ch.setTargetVelocity(val * motor_direction)

try:
    servo_ch.close()
    motor_ch.close()
except PhidgetException as e:
    print("Phidget Exception %i: %s" % (e.code, e.details))
    print("Press Enter to Exit...\n")
    readin = sys.stdin.read(1)
    exit(1) 
print("Closed RCServo device")
exit(0)
                     
    exit(1)


if(not enc.getEnabled()):
    enc.setEnabled(1)

print("INITIAL POSITION: %d\n" % enc.getPosition());

print("Setting Target Velocity to 1 for 5 seconds...\n")
motorControl.setTargetVelocity(0.1)
time.sleep(10)

print("FINAL POSITION: %d\n" % enc.getPosition());

print("Setting Target Velocity to 0 for 5 seconds...\n")
motorControl.setTargetVelocity(0)
time.sleep(1)

try:
    motorControl.close()
    enc.close()
except PhidgetException as e:
    motorControl.setTargetVelocity(0)
    print("Phidget Exception %i: %s" % (e.code, e.details))
    print("Press Enter to Exit...\n")
    readin = sys.stdin.read(1)
    exit(1) 
print("Closed DCMotor device")
exit(0)