diff --git a/src/modules/rc_update/RCUpdateTest.cpp b/src/modules/rc_update/RCUpdateTest.cpp index 2b51dbaca50..7768fe99d56 100644 --- a/src/modules/rc_update/RCUpdateTest.cpp +++ b/src/modules/rc_update/RCUpdateTest.cpp @@ -32,6 +32,7 @@ ****************************************************************************/ #include +#include #include "rc_update.h" using namespace rc_update; @@ -344,3 +345,15 @@ TEST_F(RCUpdateTest, PayloadPower3WaySwitchNegativeThresholds) checkPayloadPowerSwitch(-0.501f, -0.75f, -0.25f, 1); // Slightly above on_threshold -> SWITCH_POS_ON checkPayloadPowerSwitch(-1.f, -0.75f, -0.25f, 1); // Above on_threshold -> SWITCH_POS_ON } + +TEST(RCUpdateParamConversionTest, FloatToInt32RoundsAndClamps) +{ + // Nominal values round to the nearest integer instead of storing raw float bytes + EXPECT_EQ(float_to_param_int32(2.f), 2); + EXPECT_EQ(float_to_param_int32(2.6f), 3); + EXPECT_EQ(float_to_param_int32(-3.4f), -3); + + // Out-of-range values are clamped into the representable INT32 range (no UB) + EXPECT_EQ(float_to_param_int32(1e20f), 2147483520); + EXPECT_EQ(float_to_param_int32(-1e20f), INT32_MIN); +} diff --git a/src/modules/rc_update/rc_update.cpp b/src/modules/rc_update/rc_update.cpp index aa237932452..d8bbbdc864e 100644 --- a/src/modules/rc_update/rc_update.cpp +++ b/src/modules/rc_update/rc_update.cpp @@ -348,7 +348,21 @@ void RCUpdate::set_params_from_rc() _rc_parameter_map.value0[i] + _rc_parameter_map.scale[i] * rc_val, _rc_parameter_map.value_min[i], _rc_parameter_map.value_max[i]); - param_set(_parameter_handles.rc_param[i], ¶m_val); + const param_t handle = _parameter_handles.rc_param[i]; + + // RC tuning always computes a float. Convert to the target type so an + // INT32 parameter stores the numeric value, not the raw float bytes. + if (param_type(handle) == PARAM_TYPE_INT32) { + // Reject non-finite input, then convert so an INT32 parameter stores + // the numeric value instead of the raw float bytes. + if (PX4_ISFINITE(param_val)) { + const int32_t int_val = float_to_param_int32(param_val); + param_set(handle, &int_val); + } + + } else { + param_set(handle, ¶m_val); + } } } } diff --git a/src/modules/rc_update/rc_update.h b/src/modules/rc_update/rc_update.h index 7fa0fdd6eab..4106d1d1083 100644 --- a/src/modules/rc_update/rc_update.h +++ b/src/modules/rc_update/rc_update.h @@ -65,6 +65,16 @@ using namespace time_literals; namespace rc_update { +/** + * Convert an RC-tuned value to a well-defined INT32: rounds to nearest and + * clamps into the representable INT32 float range so the cast is defined for + * any finite input. Callers must reject non-finite values first. + */ +inline int32_t float_to_param_int32(float value) +{ + return static_cast(math::constrain(roundf(value), -2147483648.f, 2147483520.f)); +} + /** ** class RCUpdate *