Pico-Arduino
PicoPWMServo.h
1 #pragma once
2 
3 #include "PicoPWM.h"
4 
5 // the shortest pulse sent to a servo
6 #ifndef MIN_PULSE_WIDTH
7 #define MIN_PULSE_WIDTH 544
8 #endif
9 // the longest pulse sent to a servo
10 #ifndef MAX_PULSE_WIDTH
11 #define MAX_PULSE_WIDTH 2400
12 #endif
13 // default pulse width when servo is attached
14 #ifndef DEFAULT_PULSE_WIDTH
15 #define DEFAULT_PULSE_WIDTH 1500
16 #endif
17 // minumim time to refresh servos in microseconds
18 #ifndef REFRESH_INTERVAL
19 #define REFRESH_INTERVAL 20000
20 #endif
21 // minimum in degrees
22 #define MIN_DEGREES 0
23 // maximum in degrees
24 #define MAX_DEGREES 180l
25 
31 class Servo {
32 public:
33  Servo() {
34  }
35 
36  ~Servo(){
37  if (pwm!=nullptr) delete pwm;
38  }
39 
41  void attach(int pin) {
42  if (pwm==nullptr){
43  pwm = new PicoPWMNano(REFRESH_INTERVAL * 1000);
44  }
45  if (pwm!=nullptr)
46  pwm->begin(pin);
47  this->is_attached = true;
48  this->pin = pin;
49  }
50 
52  void attach(int pin, int min, int max) {
53  this->min = min;
54  this->max = max;
55  attach(pin);
56  }
57 
58  // stops the generation of signals
59  void detach() {
60  is_attached = false;
61  if (pwm!=nullptr)
62  pwm->end(pin);
63  }
64 
65  // if value is < 200 its treated as an angle, otherwise as pulse width in microseconds
66  void write(int value) {
67  int pulse_width_ms = value;
68  if (value<200){
69  pulse_width_ms = map(value,MIN_DEGREES, MAX_DEGREES, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
70  }
71  writeMicroseconds(pulse_width_ms);
72  }
73 
74  // Write pulse width in microseconds
75  void writeMicroseconds(int value) {
76  pwm_value = value;
77  if (pwm!=nullptr) {
78  // convert value to nanoseconds
79  pwm->setDutyCycle(pin, value * 1000);
80  }
81  }
82 
83  // returns current pulse width as an angle between 0 and 180 degrees
84  int read() {
85  return map(pwm_value, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH, MIN_DEGREES,MAX_DEGREES);
86  }
87  // returns current pulse width in microseconds for this servo (was read_us() in first release)
88  int readMicroseconds() {
89  return pwm_value;
90  }
91  // return true if this servo is attached, otherwise false
92  bool attached() {
93  return is_attached;
94  }
95 
96 private:
97  PicoPWMNano *pwm;
98  int8_t min = MIN_DEGREES;
99  int8_t max = MAX_DEGREES;
100  bool is_attached = false;
101  int pwm_value;
102  int pin;
103 
104 };
Definition: PicoPWM.h:22
We provide an alternative Pico implementation for the Servo class which is compatible with the Arduin...
Definition: PicoPWMServo.h:31
void attach(int pin, int min, int max)
as above but also sets min and max values for writes.
Definition: PicoPWMServo.h:52
void attach(int pin)
attach the given pin to the next free channel, sets pinMode, returns channel number or 0 if failure
Definition: PicoPWMServo.h:41