Smartcar Shield
ServoMotor.cpp
Go to the documentation of this file.
1 #include "ServoMotor.hpp"
2 #include "../../../utilities/Utilities.hpp"
3 
4 using namespace smartcarlib::utils;
5 using namespace smartcarlib::constants::motor;
6 
7 ServoMotor::ServoMotor(uint8_t controlPin,
8  int minPulseLength,
9  int idlePulseLength,
10  int maxPulseLength)
11  : kControlPin{ controlPin }
12  , kMinPulseLength{ minPulseLength }
13  , kIdlePulseLength{ idlePulseLength }
14  , kMaxPulseLength{ maxPulseLength }
15  , mAttached{ false }
16 {
17 }
18 
19 void ServoMotor::setSpeed(int speed)
20 {
21  if (!mAttached)
22  {
23  Servo::attach(kControlPin, kMinPulseLength, kMaxPulseLength);
24  mAttached = true;
25  }
26 
28  // The pulses duration might not be symmetrically distributed around the
29  // idle speed so we need to split the mapping between the positive and the
30  // negative values
31  if (speed < kIdleMotorSpeed)
32  {
33  Servo::writeMicroseconds(
34  getMap(speed, kMinMotorSpeed, kIdleMotorSpeed, kMinPulseLength, kIdlePulseLength));
35  }
36  else
37  {
38  Servo::writeMicroseconds(
39  getMap(speed, kIdleMotorSpeed, kMaxMotorSpeed, kIdlePulseLength, kMaxPulseLength));
40  }
41 }
ServoMotor::setSpeed
void setSpeed(int speed) override
Sets the motor speed and direction as the percentage of the maximum possible speed,...
Definition: ServoMotor.cpp:19
smartcarlib::constants::motor::kMaxMotorSpeed
const int kMaxMotorSpeed
Definition: Motor.hpp:17
ServoMotor::ServoMotor
ServoMotor(uint8_t controlPin, int minPulseLength=smartcarlib::constants::servomotor::kDefaultMinPulseLength, int idlePulseLength=smartcarlib::constants::servomotor::kDefaultIdlePulseLength, int maxPulseLength=smartcarlib::constants::servomotor::kDefaultMaxPulseLength)
Constructs a servo motor.
Definition: ServoMotor.cpp:7
smartcarlib::constants::motor::kIdleMotorSpeed
const int kIdleMotorSpeed
Definition: Motor.hpp:16
ServoMotor.hpp
smartcarlib::utils::getMap
constexpr AnyNumber getMap(AnyNumber valueToMap, AnyNumber fromLow, AnyNumber fromHigh, AnyNumber toLow, AnyNumber toHigh)
Maps a value from a range to another.
Definition: Utilities.hpp:104
smartcarlib::constants::motor
Definition: Motor.hpp:13
smartcarlib::utils
Definition: Utilities.hpp:9
smartcarlib::constants::motor::kMinMotorSpeed
const int kMinMotorSpeed
Definition: Motor.hpp:15
smartcarlib::utils::getConstrain
constexpr AnyNumber getConstrain(AnyNumber number, AnyNumber min, AnyNumber max)
Limit the number between a range.
Definition: Utilities.hpp:46