Servo: using a driver

Control a servo motor using the servo driver to simplify things.

In many cases, it would be nice to avoid having to care about all these specific calculations. Luckily we have the servo driver as part of the TinyGo drivers module. It still requires looking up the right PWM and pin combinations, but it does simplify controlling the servos a bit.

To use the driver, we need to configure it first:

	// Configure the servo array.
	array, err := servo.NewArray(pwm)
	if err != nil {
		println("could not configure:", err.Error())
		return
	}

We just pass in the PWM peripheral, and it will configure the PWM to the right period size. Note it is called an “array” since we can actually control multiple servos! More on that later.

Next, we can configure the servo array to use this servo:

	// Add a servo to the servo array.
	servo, err := array.Add(servoPin)
	if err != nil {
		println("could not add servo pin:", err.Error())
		return
	}

This will configure the pin to be used as a servo pin, and returns a servo.Servo instance. This instance can then be used to set the servo angle:

	// Left position at 2000µs (2ms) "on" time.
	println("left:  -90°")
	servo.SetMicroseconds(2000)
	time.Sleep(time.Second * 3)
Last modified May 1, 2025: Add PWM tour (af9cc3a)
Loading...

Note: these numbers are estimates, based on datasheets and measurements. They don't include everything and may be wrong.

Loading...