After the timed-movement challenge, you'll notice the robot can move for 5 seconds at 50% speed. But if you want the robot to travel a specific distance, using time is not reliable — the distance depends on things like battery voltage. If the voltage is lower or higher, the robot won't travel the same distance every time.
To solve this, we use encoder distance instead.
Updating Robot.h
Open the Simple Auto project you created earlier. Everything else is already set up, so go straight to Robot.h. Remove the Timer.h header, and under private: remove this line:
frc::Timer m_timer;
and replace it with:
double targetDistance = 2.0;
Your updated Robot.h should look like this:
Robot.h
#pragma once
#include <frc/TimedRobot.h>
#include <frc2/command/Command.h>
#include "RobotContainer.h"
#include <frc/Encoder.h>
#include "studica/TitanQuad.h"
#include "Constants.h"
class Robot : public frc::TimedRobot {
public:
void RobotInit() override;
void RobotPeriodic() override;
void DisabledInit() override;
void DisabledPeriodic() override;
void AutonomousInit() override;
void AutonomousPeriodic() override;
void TeleopInit() override;
void TeleopPeriodic() override;
void TestPeriodic() override;
private:
// Motor control object for the wheel
studica::TitanQuad wheel{constant::TITAN_ID, constant::frequency, constant::Wheel};
// Encoder object for measuring wheel rotation
frc::Encoder wheelEncoder{constant::Wheel_VMX[0], constant::Wheel_VMX[1], false, frc::Encoder::k4X};
// Target distance for autonomous movement
double targetDistance = 2.0;
};
Updating Robot.cpp
Now go to Robot.cpp. Add the encoder setup inside RobotInit(). RobotPeriodic() stays the same. In AutonomousInit(), reset the encoder. In AutonomousPeriodic(), set the target distance and motor power.
Robot.cpp
#include "Robot.h"
#include <frc/smartdashboard/SmartDashboard.h>
void Robot::RobotInit()
{
// Example: set how much distance each encoder pulse represents
// You must change this value to match your wheel and encoder setup
wheelEncoder.SetDistancePerPulse(0.01);
}
void Robot::RobotPeriodic()
{
frc::SmartDashboard::PutNumber("wheelEncoder", wheelEncoder.GetDistance());
}
void Robot::DisabledInit() {}
void Robot::DisabledPeriodic() {}
void Robot::AutonomousInit()
{
wheelEncoder.Reset(); // Start measuring from zero
}
void Robot::AutonomousPeriodic()
{
double targetDistance = 2.0; // Distance you want to travel
double currentDistance = wheelEncoder.GetDistance();
if (currentDistance < targetDistance) {
wheel.Set(0.5); // Move wheel at 50% speed
} else {
wheel.Set(0.0); // Stop when target distance is reached
}
}
void Robot::TeleopInit() {}
void Robot::TeleopPeriodic() {}
void Robot::TestPeriodic() {}
#ifndef RUNNING_FRC_TESTS
int main() { return frc::StartRobot<Robot>(); }
#endif