From a498a1f984b1bc8701e0f403e0e349f59dfc2d6e Mon Sep 17 00:00:00 2001 From: Unknown Date: Mon, 9 Mar 2020 21:08:49 -0400 Subject: [PATCH] Convert endstop debounce_ms to a uint32 to avoid potential overflow bug --- Firmware/MotorControl/endstop.cpp | 4 ++-- Firmware/MotorControl/endstop.hpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Firmware/MotorControl/endstop.cpp b/Firmware/MotorControl/endstop.cpp index f8fc4480..d4be0f41 100644 --- a/Firmware/MotorControl/endstop.cpp +++ b/Firmware/MotorControl/endstop.cpp @@ -10,14 +10,14 @@ void Endstop::update() { GPIO_TypeDef* gpio_port = get_gpio_port_by_pin(config_.gpio_num); bool last_pin_state = pin_state_; pin_state_ = HAL_GPIO_ReadPin(gpio_port, gpio_pin); - float now = axis_->loop_counter_ * current_meas_period; + uint32_t now = static_cast(axis_->loop_counter_ * current_meas_period); if (pin_state_ != last_pin_state) { debounce_timer_ = now; } if (config_.enabled) { if ((now - debounce_timer_) >= (config_.debounce_ms * 0.001f)) { // Debounce timer expired, take the new pin state endstop_state_ = config_.is_active_high ? pin_state_ : !pin_state_; // endstop_state is the logical state - debounce_timer_ = now - (config_.debounce_ms * 0.001f); // Ensure timer doesn't have overflow issues + debounce_timer_ = config_.debounce_ms; // Ensure timer doesn't have overflow issues } else { endstop_state_ = endstop_state_; // Do nothing } diff --git a/Firmware/MotorControl/endstop.hpp b/Firmware/MotorControl/endstop.hpp index eb1e3c8e..b5c6e6d8 100644 --- a/Firmware/MotorControl/endstop.hpp +++ b/Firmware/MotorControl/endstop.hpp @@ -5,7 +5,7 @@ class Endstop { public: struct Config_t { float offset = 0; - float debounce_ms = 50.0f; + uint32_t debounce_ms = 50; uint16_t gpio_num = 0; bool enabled = false; bool is_active_high = false; @@ -42,6 +42,6 @@ class Endstop { private: bool pin_state_ = false; float pos_when_pressed_ = 0.0f; - volatile float debounce_timer_ = 0; + uint32_t debounce_timer_ = 0; }; #endif \ No newline at end of file