servo-angle.ino

Teensy 4.0 · File : servo-angle.ino · Language : Arduino · Use case : Piloter un servo avec la bibliothèque Servo sur Teensy

A typical Teensy combo: a capacitive touch controls a hobby servo speed. The core Servo library works exactly like on Arduinos, and touchRead() gives a contact-proportional value for organic variation.

Hardware

A Teensy 4.0 (NXP i.MX RT1062, Cortex-M7 @ 600 MHz, 3.3 V logic) powered over USB. 1 hobby servo (SG90/MG90S) + a bare wire for the capacitive touch pad.

Wiring

Servo: signal to pin 9, + to 5 V (external supply advised), - to common GND. Touch: bare wire on pin 0.

How it works

touchRead() grows with contact area; map() converts it to rotation speed, constrain() clamps the angle to 0-180°. The servo gets the current position every 20 ms.

Running it

With Teensyduino in the Arduino IDE, select « Teensy 4.0 », Upload then confirm in the Teensy Loader. Pins are 3.3 V; the 4.0 is pin-compatible with the 3.2.

Variants

Replace the touch pin with a potentiometer, or add a « return to center » mode after 5 s without contact.

servo-angle.ino

// Servo d'angle commande par une touche capacitive (combo Teensy).
#include <Servo.h>

Servo myservo;
const int TOUCHE = 0;
const int SEUIL = 500;

int angle = 90;
unsigned long derniereEtape = 0;

void setup() {
  myservo.attach(9); // signal servo sur la broche 9
  myservo.write(angle);
  Serial.begin(9600);
  Serial.println(F("Touche capacitive = vitesse angulaire"));
}

void loop() {
  if (millis() - derniereEtape < 20) return;
  derniereEtape = millis();

  int t = touchRead(TOUCHE);
  if (t > SEUIL) {
    // Plus le contact est grand, plus l'angle tourne vite.
    int vitesse = map(t, SEUIL, 1024, 1, 6);
    angle = constrain(angle + vitesse, 0, 180);
    if (angle == 180) angle = 0; // rebouclage en douceur
    myservo.write(angle);
    Serial.print(F("touche=")); Serial.print(t);
    Serial.print(F(" angle=")); Serial.println(angle);
  }
}

← Back to the board