2323import edu .wpi .first .math .estimator .DifferentialDrivePoseEstimator ;
2424import edu .wpi .first .math .geometry .Pose2d ;
2525import edu .wpi .first .math .geometry .Rotation2d ;
26+ import edu .wpi .first .math .geometry .Twist2d ;
2627import edu .wpi .first .math .kinematics .ChassisSpeeds ;
2728import edu .wpi .first .math .kinematics .DifferentialDriveKinematics ;
2829import edu .wpi .first .math .kinematics .DifferentialDriveWheelSpeeds ;
2930import edu .wpi .first .wpilibj .DriverStation ;
3031import edu .wpi .first .wpilibj .DriverStation .Alliance ;
3132import edu .wpi .first .wpilibj2 .command .Command ;
33+ import edu .wpi .first .wpilibj2 .command .Commands ;
3234import edu .wpi .first .wpilibj2 .command .SubsystemBase ;
3335import edu .wpi .first .wpilibj2 .command .sysid .SysIdRoutine ;
3436import frc .robot .Constants ;
@@ -98,6 +100,14 @@ public void periodic() {
98100 Logger .processInputs ("Drive" , inputs );
99101
100102 // Update gyro angle
103+ // Use the angle delta from the kinematics and module deltas
104+ Twist2d twist =
105+ kinematics .toTwist2d (
106+ getLeftPositionMeters () - lastLeftPositionMeters ,
107+ getRightPositionMeters () - lastRightPositionMeters );
108+ rawGyroRotation = rawGyroRotation .plus (new Rotation2d (twist .dtheta ));
109+ lastLeftPositionMeters = getLeftPositionMeters ();
110+ lastRightPositionMeters = getRightPositionMeters ();
101111
102112 // Update odometry
103113 poseEstimator .update (rawGyroRotation , getLeftPositionMeters (), getRightPositionMeters ());
@@ -171,13 +181,13 @@ public void addVisionMeasurement(Pose2d visionPose, double timestamp) {
171181 /** Returns the position of the left wheels in meters. */
172182 @ AutoLogOutput
173183 public double getLeftPositionMeters () {
174- return inputs .leftPositionRad * wheelRadiusMeters ;
184+ return inputs .leftPositionRad * wheelRadiusMeters - this . offsetLeft ;
175185 }
176186
177187 /** Returns the position of the right wheels in meters. */
178188 @ AutoLogOutput
179189 public double getRightPositionMeters () {
180- return inputs .rightPositionRad * wheelRadiusMeters ;
190+ return inputs .rightPositionRad * wheelRadiusMeters - this . offsetRight ;
181191 }
182192
183193 /** Returns the velocity of the left wheels in meters/second. */
@@ -196,4 +206,17 @@ public double getRightVelocityMetersPerSec() {
196206 public double getCharacterizationVelocity () {
197207 return (inputs .leftVelocityRadPerSec + inputs .rightVelocityRadPerSec ) / 2.0 ;
198208 }
209+
210+ private double offsetLeft = 0.0 ;
211+ private double offsetRight = 0.0 ;
212+
213+ public Command resetEncoders () {
214+ return Commands .runOnce (
215+ () -> {
216+ io .resetEncoders ();
217+ this .offsetLeft += this .getLeftPositionMeters ();
218+ this .offsetRight += this .getRightPositionMeters ();
219+ },
220+ this );
221+ }
199222}
0 commit comments