|
| 1 | +# |
| 2 | +# Copyright (c) FIRST and other WPILib contributors. |
| 3 | +# Open Source Software; you can modify and/or share it under the terms of |
| 4 | +# the WPILib BSD license file in the root directory of this project. |
| 5 | +# |
| 6 | + |
| 7 | +import wpilib.simulation |
| 8 | +from wpimath.system.plant import DCMotor |
| 9 | + |
| 10 | +from pyfrc.physics.core import PhysicsInterface |
| 11 | + |
| 12 | +import typing |
| 13 | + |
| 14 | +if typing.TYPE_CHECKING: |
| 15 | + from robot import MyRobot |
| 16 | + |
| 17 | + |
| 18 | +class PhysicsEngine: |
| 19 | + """ |
| 20 | + Simulates a flywheel |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, physics_controller: PhysicsInterface, robot: "MyRobot"): |
| 24 | + """ |
| 25 | + :param physics_controller: `pyfrc.physics.core.Physics` object |
| 26 | + to communicate simulation effects to |
| 27 | + """ |
| 28 | + |
| 29 | + self.physics_controller = physics_controller |
| 30 | + |
| 31 | + # Motors |
| 32 | + self.flywheelMotor = wpilib.simulation.PWMSim(robot.flywheelMotor.getChannel()) |
| 33 | + |
| 34 | + # Sensors |
| 35 | + self.encoder = wpilib.simulation.EncoderSim(robot.encoder) |
| 36 | + |
| 37 | + # Flywheel |
| 38 | + self.flywheel = wpilib.simulation.FlywheelSim( |
| 39 | + DCMotor.NEO(1), robot.kFlywheelGearing, robot.kFlywheelMomentOfInertia |
| 40 | + ) |
| 41 | + |
| 42 | + def update_sim(self, now: float, tm_diff: float) -> None: |
| 43 | + """ |
| 44 | + Called when the simulation parameters for the program need to be |
| 45 | + updated. |
| 46 | +
|
| 47 | + :param now: The current time as a float |
| 48 | + :param tm_diff: The amount of time that has passed since the last |
| 49 | + time that this function was called |
| 50 | + """ |
| 51 | + |
| 52 | + # To update our simulation, we set motor voltage inputs, update the |
| 53 | + # simulation, and write the simulated velocities to our simulated encoder |
| 54 | + self.flywheel.setInputVoltage( |
| 55 | + self.flywheelMotor.getSpeed() * wpilib.RobotController.getInputVoltage() |
| 56 | + ) |
| 57 | + self.flywheel.update(0.02) |
| 58 | + self.encoder.setRate(self.flywheel.getAngularVelocity()) |
0 commit comments