Library for controlling servos
curl -o src/libs/servo.ts https://c2coder.github.io/Jaculus-libraries/data/servo/servo.ts
import { Servo } from "./libs/servo.js"
const SERVO_PIN = 35;
const TIMER = 1;
const CHANNEL = 3;
const servo = new Servo(SERVO_PIN, TIMER, CHANNEL);
servo.write(0); // 0°
servo.write(512); // 90°
servo.write(1023); // 180°
import { Servo } from "./libs/servo.js"
const SERVO_PIN = 35;
const TIMER = 1;
const CHANNEL_1 = 3;
const CHANNEL_2 = 4;
const servo_1 = new Servo(SERVO_PIN, TIMER, CHANNEL_1);
const servo_2 = new Servo(SERVO_PIN, TIMER, CHANNEL_2);
servo_1.write(0); // 0°
servo_2.write(0); // 0°
servo_1.write(512); // 90°
servo_2.write(512); // 90°
servo_1.write(1023); // 180°
servo_2.write(1023); // 180°
import * as ledc from "ledc";
/**
* A class for controlling a servo motor.
*/
export class Servo {
private channel: number; // the PWM channel to use
/**
* Create a new servo object.
* @param pin The pin the servo is connected to.
* @param timer The timer to use for PWM.
* @param channel The channel to use for PWM.
*/
constructor(pin: number, timer: number, channel: number) {
this.channel = channel;
ledc.configureTimer(timer, 50, 12); // 50Hz is the frequency of a servo, 12 is the resolution of the timer
ledc.configureChannel(channel, pin, timer, 1023); // 1023 is the resolution of a servo
}
/**
* Set the servo position.
* @param value The position to set the servo to, from 0-1023.
*/
write(value: number) {
// map the value from 0-1023 to 0.5-2.5ms
const ms = ((value / 1023) * 2) + 0.5; // 0.5-2.5ms is the range of a servo
// convert to a duty cycle
const duty = (ms / 20) * 1023; // 20ms is the period of a servo
ledc.setDuty(this.channel, duty); // set the duty cycle to the servo
}
}