TinyRobotics
Loading...
Searching...
No Matches
BrushlessMotor.h
1
2#pragma once
3
4#include <Arduino.h>
5#ifdef ESP32
6#include <ESP32Servo.h>
7#else
8#include <Servo.h>
9#endif
10
11#include "IMotor.h"
12
13namespace tinyrobotics {
14
15/**
16 * @class BrushlessMotor
17 * @ingroup motors
18 * @brief Simple brushless DC motor (ESC) driver using Servo library for
19 * Arduino/ESP32.
20 *
21 * This class provides an interface to control brushless DC motors (with ESCs)
22 * using the Servo or ESP32Servo library. It allows attaching to a pin, setting
23 * speed as a percentage, and detaching the servo.
24 *
25 * Main methods:
26 * - setPin(pin): Defines the pin to which the ESC control signal is connected.
27 * - begin(): Initialize and attach the servo to the configured pin.
28 * - setSpeed(percent): Set the motor speed as a percentage (0 to 100).
29 * - end(): Stop the motor and detach the servo.
30 *
31 * Usage notes:
32 * - Call setPin() before begin().
33 * - Use setSpeed() to control the motor speed. Use end() to stop and detach.
34 * - The class maps speed percentage to servo pulse width (1000-2000us typical
35 * for ESCs).
36 *
37 * Example usage:
38 * @code
39 * BrushlessMotor motor;
40 * motor.setPin(9);
41 * motor.begin();
42 * motor.setSpeed(50); // 50% throttle
43 * motor.end();
44 * @endcode
45 */
46
47template <typename T = float>
48class BrushlessMotor : public IMotor<T> {
49 public:
50 BrushlessMotor(uint8_t id = 0) { this->setID(id); }
51
52 /** Attach the servo to a pin */
53 void setPin(int pin) { this->pin = pin; }
54
55 bool begin() {
56 if (pin == -1) return false;
57 servo.attach(pin);
58 return true;
59 }
60
61 // Set value as percentage (-100 to 100)
62 bool setValuePercent(T percent) override {
63 if (!servo.attached()) return false;
64 lastValuePercent = constrain(percent, -100, 100);
65 int angle = map(lastValuePercent, 0, 100, 100, 2000); // Map to servo angle
66 servo.write(angle);
67 return true;
68 }
69
70 T getValuePercent() const override {
71 return lastValuePercent;
72 }
73
74 void end() override {
75 setValuePercent(0);
76 servo.detach();
77 }
78
79 bool isPinsSet() const override { return pin != -1; }
80
81 protected:
82 Servo servo;
83 int pin = -1;
84 bool is_pin_assigned = false;
85 T lastValuePercent = 0.0f;
86};
87
88} // namespace tinyrobotics
Simple brushless DC motor (ESC) driver using Servo library for Arduino/ESP32.
Definition: BrushlessMotor.h:48
void setPin(int pin)
Definition: BrushlessMotor.h:53
Abstract base class for all motor driver types.
Definition: IMotor.h:21