Hi Everyone. How can I improve my code for my flywheel? I looked up how to code for a flywheel and people used Take Back Half instead of PID but I don’t get the Take Back Half thing. So I used a PID code. Is there a way to optimize my code? And is my code even rational?

Thanks,

```
#pragma config(Sensor, dgtl2, FlywheelEncoder, sensorQuadEncoder)
#pragma config(Motor, port1, FlywheelMotor, tmotorVex393HighSpeed_HBridge, openLoop)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
long CurrentFlywheelSpeed;//In RPM
long CurrentFlywheelEncoder = SensorValue(FlywheelEncoder);
long FlywheelDeltaTime = time1[T1];
long TargetFlywheelSpeed;//In RPM
long FlywheelError;
long FlywheelPreviousError;
long Integral;
long Derivative;
long Kp = 0;//Placeholder
long Ki = 0;//Placeholder
long Kd = 0;//Placeholder
long FinalPIDSpeed;
long MotorTargetFlywheelSpeed;//range of -127 to 127
long FlywheelTolerance = abs(200)//200 RPM Tolerable Range of Flywheel speed difference (in RPM)
void CurrentFlywheel()//Finds out Current Flywheelspeed
{
while(true)
{
clearTimer(T1);//Timer starts
CurrentFlywheelSpeed = CurrentFlywheelEncoder/FlywheelDeltaTime;//Calculates Flywheel Speed from Encoder/Time it takes
}
}
void TargetFlywheel(int HighFlag, int LowFlag)
{
while(true)
{
if((HighFlag) == 1 )
{
TargetFlywheelSpeed = 3000;//Placeholder for Speed in RPM High flag
}
else if((LowFlag) == 1)
{
TargetFlywheelSpeed = 2500;//Placeholder for Speed in RPM Low flag
}
else
{
TargetFlywheelSpeed = 0;//Flywheel Stop
}
}
}
task FlywheelPID()
{
FlywheelError = TargetFlywheelSpeed - CurrentFlywheelSpeed;//Calculate Error Proportion
FlywheelPreviousError = FlywheelError;//Previous Error
Integral = Integral + FlywheelError*FlywheelDeltaTime;//Integral Calculation
if(FlywheelError == 0)//No Error makes no Integral
{
Integral = 0;
}
else if(Integral < abs(127))//Integral Outside usable Range then Integral goes to max inside range
{
Integral = 127;
}
Derivative = (FlywheelError - FlywheelPreviousError)/FlywheelDeltaTime;//Derivative Calculation
FinalPIDSpeed = Kp*FlywheelError + Ki*Integral + Kd*Derivative;//Final Speed Calculation
motor[FlywheelMotor] = FinalPIDSpeed;//Send to Motors
}
task FlywheelMtr()
{
while(true)
{
MotorTargetFlywheelSpeed = 127/4000*TargetFlywheelSpeed;
//Motor Speed Calculation as 127 is motor maximum capacity and 4000RPM is maximum
if(SensorValue(FlywheelEncoder) < (TargetFlywheelSpeed + FlywheelTolerance)*360)
{
motor[FlywheelMotor] = MotorTargetFlywheelSpeed;
}
//When Flywheel runs less than Target and tolerance, run mtoor
else if(SensorValue(FlywheelEncoder) > (TargetFlywheel + FlywheelTolerance)*360)
{
motor[FlywheelMotor] = 50;//Stays on for warm up
}
//If flywheel is faster than wanted, make motor slower
}
}
```