|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# Copyright (c) FIRST and other WPILib contributors. |
| 4 | +# Open Source Software; you can modify and/or share it under the terms of |
| 5 | +# the WPILib BSD license file in the root directory of this project. |
| 6 | +# |
| 7 | + |
| 8 | +import wpilib |
| 9 | +import wpimath.controller |
| 10 | + |
| 11 | + |
| 12 | +class MyRobot(wpilib.TimedRobot): |
| 13 | + """ |
| 14 | + This is a sample program to demonstrate how to use a soft potentiometer and |
| 15 | + a PID controller to reach and maintain position setpoints on an elevator |
| 16 | + mechanism. |
| 17 | + """ |
| 18 | + |
| 19 | + kPotChannel = 1 |
| 20 | + kMotorChannel = 7 |
| 21 | + kJoystickChannel = 3 |
| 22 | + |
| 23 | + # The elevator can move 1.5 meters from top to bottom |
| 24 | + kFullHeightMeters = 1.5 |
| 25 | + |
| 26 | + # Bottom, middle, and top elevator setpoints |
| 27 | + kSetpointMeters = [0.2, 0.8, 1.4] |
| 28 | + |
| 29 | + # proportional, integral, and derivative speed constants |
| 30 | + # DANGER: when tuning PID constants, high/inappropriate values for kP, kI, |
| 31 | + # and kD may cause dangerous, uncontrollable, or undesired behavior! |
| 32 | + kP = 0.7 |
| 33 | + kI = 0.35 |
| 34 | + kD = 0.25 |
| 35 | + |
| 36 | + def robotInit(self): |
| 37 | + self.pidController = wpimath.controller.PIDController(self.kP, self.kI, self.kD) |
| 38 | + # Scaling is handled internally |
| 39 | + self.potentiometer = wpilib.AnalogPotentiometer( |
| 40 | + self.kPotChannel, self.kFullHeightMeters |
| 41 | + ) |
| 42 | + self.elevatorMotor = wpilib.PWMSparkMax(self.kMotorChannel) |
| 43 | + self.joystick = wpilib.Joystick(self.kJoystickChannel) |
| 44 | + |
| 45 | + def teleopInit(self): |
| 46 | + # Move to the bottom setpoint when teleop starts |
| 47 | + self.index = 0 |
| 48 | + self.pidController.setSetpoint(self.kSetpointMeters[self.index]) |
| 49 | + |
| 50 | + def teleopPeriodic(self): |
| 51 | + # Read from the sensor |
| 52 | + position = self.potentiometer.get() |
| 53 | + |
| 54 | + # Run the PID Controller |
| 55 | + pidOut = self.pidController.calculate(position) |
| 56 | + |
| 57 | + # Apply PID output |
| 58 | + self.elevatorMotor.set(pidOut) |
| 59 | + |
| 60 | + # when the button is pressed once, the selected elevator setpoint is incremented |
| 61 | + if self.joystick.getTriggerPressed(): |
| 62 | + # index of the elevator setpoint wraps around. |
| 63 | + self.index = (self.index + 1) % len(self.kSetpointMeters) |
| 64 | + print(f"m_index = {self.index}") |
| 65 | + self.pidController.setSetpoint(self.kSetpointMeters[self.index]) |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + wpilib.run(MyRobot) |
0 commit comments