Since both leftTargetPWM and leftActualPWM are uint8_t values, the result will also be an uint8_t value. IfDepending on the sumtype of the two values would be larger than 255variables, the result willaddition could overflow and wrapbefore the division is performed, which would result in an unexpected result, possibly leading to badly behaving motor speed. Only after that will
While it divide by 2. A safer way wouldmight actually be safe here due to divide each value by two firstinteger promotion rules, you could explicitly convert the values to a type that you know is safe for the given operation:
leftActualPWM = (static_cast<uint16_t>(leftTargetPWM / 2) + leftActualPWM) / 2;
But that way you will lose one bit of precision. You can also cast one of the values to uint16_tOr if possible, so the result will be anas Toby Speight suggested, use C++20's uint16_t valuestd::midpoint():
leftActualPWM = (static_cast<uint16_t>std::midpoint(leftTargetPWM) +, leftActualPWM) / 2;;
IfAlternatively, if the CPU in your Arduino has hardware support for floating point operations, I would rather store most variables as float, and only convert to uint8_t PWM values right before calling analogWrite().