67 _min(SERVO_DEFAULT_MIN_US),
68 _max(SERVO_DEFAULT_MAX_US),
69 _pulseUs((SERVO_DEFAULT_MIN_US + SERVO_DEFAULT_MAX_US) / 2) {}
77 _min(SERVO_DEFAULT_MIN_US),
78 _max(SERVO_DEFAULT_MAX_US),
79 _pulseUs((SERVO_DEFAULT_MIN_US + SERVO_DEFAULT_MAX_US) / 2) {}
91 return attach(pin, SERVO_DEFAULT_MIN_US, SERVO_DEFAULT_MAX_US);
101 uint8_t
attach(
int pin,
int min,
int max) {
106 _gpio->pinMode(_pin, OUTPUT);
107 _gpio->analogWriteFrequency(_pin, 50);
109 _writePulse(_pulseUs);
129 value = std::max(0, std::min(value, 180));
141 _pulseUs = std::max(_min, std::min(us, _max));
142 if (
attached()) _writePulse(_pulseUs);
149 return _pulseToAngle(_pulseUs);
163 return _pin != SERVO_NO_PIN;
167 HardwareGPIO_RPI* _gpio;
174 int _angleToPulse(
int angle)
const {
175 return _min + (angle * (_max - _min)) / 180;
179 int _pulseToAngle(
int us)
const {
180 if (_max == _min)
return 0;
181 int angle = ((us - _min) * 180) / (_max - _min);
182 return std::max(0, std::min(angle, 180));
193 void _writePulse(
int us) {
194 int pwm_channel = -1;
195 if (_pin == 18 || _pin == 12) pwm_channel = 0;
196 else if (_pin == 19 || _pin == 13) pwm_channel = 1;
197 if (pwm_channel < 0)
return;
200 FILE* fexp = fopen(
"/sys/class/pwm/pwmchip0/export",
"w");
201 if (fexp) { fprintf(fexp,
"%d", pwm_channel); fclose(fexp); }
203 char period_path[64], duty_path[64], enable_path[64];
204 snprintf(period_path,
sizeof(period_path),
205 "/sys/class/pwm/pwmchip0/pwm%d/period", pwm_channel);
206 snprintf(duty_path,
sizeof(duty_path),
207 "/sys/class/pwm/pwmchip0/pwm%d/duty_cycle", pwm_channel);
208 snprintf(enable_path,
sizeof(enable_path),
209 "/sys/class/pwm/pwmchip0/pwm%d/enable", pwm_channel);
212 FILE* fp = fopen(period_path,
"w");
213 if (fp) { fprintf(fp,
"%lu", SERVO_PERIOD_NS); fclose(fp); }
216 unsigned long duty_ns = (us > 0) ? (
unsigned long)us * 1000UL : 0UL;
217 FILE* fd = fopen(duty_path,
"w");
218 if (fd) { fprintf(fd,
"%lu", duty_ns); fclose(fd); }
221 FILE* fe = fopen(enable_path,
"w");
222 if (fe) { fprintf(fe,
"%d", us > 0 ? 1 : 0); fclose(fe); }
uint8_t attach(int pin, int min, int max)
Attach the servo to a GPIO pin with custom min/max pulse widths.
Definition Servo.h:101