NXPCUP-libary
Library for car's control board on NXPCUP competition based on the Mbed framework.
Motor.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include "mbed.h"
4 
5 #include "SoftPWM.h"
6 #include "util.h"
7 
8 namespace nxpcup {
9 
10 class Motor {
11 public:
12  struct Config {
13  PinName pwm0;
14  PinName pwm1;
15  bool inverse = false;
17  static constexpr int PERIOD_US = 500; // 2000 Hz
18  static constexpr int MAX_POWER = 1000; // MUST BE DIVISIBLE BY PERIOD_US
19  static constexpr int POWER_DIVIDER = MAX_POWER / PERIOD_US; // 1000 / 2 = 500
20  static_assert(POWER_DIVIDER * PERIOD_US == MAX_POWER);
21  };
22 
29  Motor(const PinName pin0, const PinName pin1)
30  : m_maxPowerPercent(100)
31  {
32 #if defined MOTOR_HARDWARE_PWM
33  m_in0 = new PwmOut(pin0);
34  m_in1 = new PwmOut(pin1);
35 #elif defined MOTOR_SOFTWARE_PWM
36  m_in0 = new SoftPWM(pin0);
37  m_in1 = new SoftPWM(pin1);
38 #endif
39 
40  m_in0->period_us(Config::PERIOD_US);
41  m_in1->period_us(Config::PERIOD_US);
42 
43  m_in0->pulsewidth_us(0);
44  m_in1->pulsewidth_us(0);
45  }
46 
52  Motor(const Config& config)
53  : Motor(config.pwm0, config.pwm1)
54  {
55  m_inverse = config.inverse;
56  }
57 
64  void power(int power)
65  {
66  power = nxpcup::clamp<int>(power, -Config::MAX_POWER, Config::MAX_POWER);
67 
68  power = (m_inverse ? -1 : 1) * power;
69  if (m_maxPowerPercent != 100) {
70  power = (power * m_maxPowerPercent) / 100;
71  }
72 
73  if (power > 0) {
74  m_in0->pulsewidth_us(power / Config::POWER_DIVIDER);
75  m_in1->pulsewidth_us(0);
76  } else {
77  m_in0->pulsewidth_us(0);
78  m_in1->pulsewidth_us(-power / Config::POWER_DIVIDER);
79  }
80  }
81 
88  void setMaxPowerPercent(int percent)
89  {
90  m_maxPowerPercent = nxpcup::clamp<int>(percent, 0, 100);
91  }
92 
96  int maxPowerPercent() const { return m_maxPowerPercent; }
97 
101  int maxPower() const { return Config::MAX_POWER; }
102 
103 private:
104 #if defined MOTOR_HARDWARE_PWM
105  PwmOut* m_in0;
106  PwmOut* m_in1;
107 #elif defined MOTOR_SOFTWARE_PWM
108  SoftPWM* m_in0;
109  SoftPWM* m_in1;
110 #endif
111 
112  bool m_inverse = false;
113  int m_maxPowerPercent;
114 };
115 
116 } // namespace nxpcup
Definition: Motor.h:12
static constexpr int POWER_DIVIDER
Definition: Motor.h:19
Motor(const PinName pin0, const PinName pin1)
Definition: Motor.h:29
bool inverse
Definition: Motor.h:15
void power(int power)
Definition: Motor.h:64
static constexpr int PERIOD_US
Definition: Motor.h:17
Definition: Motor.h:10
static constexpr int MAX_POWER
Definition: Motor.h:18
Definition: BorderDetector.h:6
Definition: SoftPWM.h:24
int maxPower() const
Definition: Motor.h:101
void setMaxPowerPercent(int percent)
Definition: Motor.h:88
PinName pwm0
Definition: Motor.h:13
int maxPowerPercent() const
Definition: Motor.h:96
Motor(const Config &config)
Definition: Motor.h:52
PinName pwm1
Definition: Motor.h:14