/** * @file motorControl.h * @author Alexander Klein (alex@kleiax.de) * @brief Inherits a class to control a motor with pwm signal. * @version 0.1 * @date 2021-12-09 * * @copyright Copyright (c) 2021 * */ #ifndef MOTOR_CONTROL_H #define MOTOR_CONTROL_H #include #include #include #include #include "component.h" /** * @brief A class which use PWM to control the power of DC Motor * You can control the acceleration of the motor, for example to * prevent a damage on your H-Bridge. */ class MotorControl : public Component { public: MotorControl(); /** * @brief Initialize the motorController * * @param pwmPin The output pin for the signal on the esp. * @param pwmChannel One of the pwm channels from the esp. * @param dir_1 First direction pin for the H-Bridge. * @param dir_2 Second direction pin for the H-Bridge. */ void init(uint8_t pwmPin, uint8_t pwmChannel, uint8_t dir_1, uint8_t dir_2); /** * @brief Set the Target Power * * If the given power is greater than 100 or smaller than -100, then * this function only print an error to consol. * * @param power power in percent */ void setTargetPower(int8_t power); /** * @brief Stops the motor like setTargetPower() to 0 * */ void stop(); /** * @brief Stops the motor immediately * */ void emergencyStop(); /** * @brief Get the current power * * @return int8_t percent of power (-100 to 100) */ int8_t getPower() const { return this->power; }; /** * @brief Get the target power * * @return int8_t percent of power (-100 to 100) */ int8_t getTargetPower() const { return this->targetPower; }; uint16_t getDutycycle() const { return this->dutycycle; } bool isTargetPowerReached() const; bool isAccelerationPositive() const; bool isAccelerationNegative() const; private: void run() override; void setRealPower(int8_t power); void increasePower(int8_t power); static constexpr uint8_t loopDelay = 10; static constexpr uint16_t pwmFreq = 16000; static constexpr uint8_t pwmRes = 8; static constexpr uint8_t powerSteps = 2; // A total of 20 levels ( 100 / SPEED_STEPS ) * RUN_MOTOR_CONTROL_DELAY = 500ms static constexpr uint8_t maxPwmMin = 80; static constexpr uint8_t maxPwmVal = 250; static constexpr uint8_t minPwmVal = 55; // Max 98% of 2^PWM_RES int8_t targetPower = 0; int8_t power = 0; uint8_t direction = 0; // 0 = stop, 1 = forward, 2 = backward uint8_t pwmPin = 0; uint8_t pwmChannel = 0; uint16_t dutycycle = 0; uint8_t dir_1 = 0; uint8_t dir_2 = 0; }; #endif // MOTOR_CONTROL_H