skullc-peripherals/Peripherals/Inc/peripherals_encoder.hpp
Erki 1d05aac914
All checks were successful
continuous-integration/drone/push Build is passing
Peripherals: make the encoder's full rev count atomic.
2021-07-05 11:44:32 +03:00

98 lines
1.7 KiB
C++

/*
* peripherals_encoder.hpp
*
* Created on: Apr 11, 2021
* Author: erki
*/
#ifndef SKULLC_PERIPHERALS_ENCODER_HPP_
#define SKULLC_PERIPHERALS_ENCODER_HPP_
#include <atomic>
#include <cstdint>
#include <tim.h>
namespace Peripherals
{
class Encoder
{
public:
enum class Dirs : std::uint8_t
{
FORWARD,
BACKWARD
};
Encoder() = delete;
explicit Encoder(TIM_HandleTypeDef* htim, const std::uint32_t channels)
: htim_(htim), channels_(channels)
{}
Encoder(const Encoder&) = delete;
Encoder(Encoder&&) = delete;
Encoder& operator=(const Encoder&) = delete;
Encoder& operator=(Encoder&&) = delete;
void start()
{
HAL_TIM_Base_Start_IT(htim_);
HAL_TIM_Encoder_Start_IT(htim_, channels_);
}
void stop()
{
HAL_TIM_Encoder_Stop_IT(htim_, channels_);
}
void reset()
{
__HAL_TIM_SET_COUNTER(htim_, 0);
full_revolutions_ = 0;
}
void setRevolutionTickCount(const std::uint16_t& count)
{
__HAL_TIM_SET_AUTORELOAD(htim_, count);
}
std::uint16_t getCurrentClicks() const
{
const std::uint16_t val = __HAL_TIM_GET_COUNTER(htim_);
return val;
}
std::int32_t getFullRevolutions() const
{
return full_revolutions_;
}
Dirs getDirection() const
{
if (__HAL_TIM_IS_TIM_COUNTING_DOWN(htim_))
return Dirs::BACKWARD;
else
return Dirs::FORWARD;
}
void timerUpdateEvent()
{
if (!__HAL_TIM_IS_TIM_COUNTING_DOWN(htim_))
full_revolutions_++;
else
full_revolutions_--;
}
private:
TIM_HandleTypeDef* htim_;
std::uint32_t channels_;
std::atomic<std::int32_t> full_revolutions_ = 0;
};
}// namespace Peripherals
#endif /* SKULLC_PERIPHERALS_ENCODER_HPP_ */