4 #include "../../utilities/Utilities.hpp"
9 const unsigned long kStopAttemptInterval = 100;
10 const uint8_t kMaxStopAttempts = 3;
19 , mOdometerLeft(odometer)
20 , mOdometerRight(odometer)
30 , mOdometerLeft(odometerLeft)
31 , mOdometerRight(odometerRight)
44 if (!areOdometersAttached())
53 if (areOdometersDirectional() && mCruiseControlEnabled)
62 auto newSpeedAtOppositeDirection = mTargetSpeed * speed < 0;
63 auto changeOfDirectionWhileCruiseControl = mCruiseControlEnabled && newSpeedAtOppositeDirection;
68 auto carShouldStop = carWantsToStop && !carIsAlreadyStopped;
69 if (changeOfDirectionWhileCruiseControl || carShouldStop)
78 if (!mCruiseControlEnabled)
85 void DistanceCar::brake()
89 auto currentSpeed = mCruiseControlEnabled ? mPreviousControlledSpeed : mTargetSpeed;
95 for (
auto attempt = 0; attempt < kMaxStopAttempts; attempt++)
99 auto distanceTravelled =
getDistance() - initialDistance;
100 if (distanceTravelled == 0)
107 mPreviousControlledSpeed = 0;
108 mIntegratedError = 0;
114 if (!areOdometersAttached() || !mCruiseControlEnabled)
120 if (currentTime < mPreviousUpdate + mFrequency)
124 mPreviousUpdate = currentTime;
138 if (!areOdometersDirectional() && mTargetSpeed < 0)
140 actualSpeed = -actualSpeed;
142 auto controlledSpeed = controlMotorSpeed(mPreviousControlledSpeed, mTargetSpeed, actualSpeed);
146 if (!areOdometersDirectional() && (controlledSpeed * actualSpeed < 0))
159 mPreviousControlledSpeed = controlledSpeed;
162 float DistanceCar::controlMotorSpeed(
const float& previousSpeed,
163 const float& targetSpeed,
164 const float& currentSpeed)
166 float error = targetSpeed - currentSpeed;
167 mIntegratedError += error;
168 float correction = (mProportional * error) + (mIntegral * mIntegratedError)
169 + (mDerivative * (error - mPreviousError));
170 mPreviousError = error;
179 return areOdometersAttached() ? (mOdometerLeft.
getSpeed() + mOdometerRight.
getSpeed()) / 2
185 mCruiseControlEnabled =
false;
191 unsigned long frequency)
193 mCruiseControlEnabled =
true;
194 mProportional = proportional;
195 mIntegral = integral;
196 mDerivative = derivative;
197 mFrequency = frequency;
200 bool DistanceCar::areOdometersAttached()
205 bool DistanceCar::areOdometersDirectional()
212 if (mCruiseControlEnabled)