🛠 Piloter un micro-servo avec la bibliothèque Servo

Arduino Nano Every · intermediaire · Schéma : IMG-nano-every-intermediaire-2-nanoevery-servo.svg — Micro-servo de type SG90 alimenté par le 5 V de la Nano Every, signal sur la broche 9, avec les trois fils couleur (signal, VCC, GND) et un bras d'angle annoté

Objectives

Control a micro-servo (SG90 type) in position using the Servo library, sweeping through a few predefined angles. Important reminder about the Nano Every: PWM is available on pins 3, 5, 6, 9, 10 — we will use pin 9. The megaAVR core remaps the timers, so libraries that hijack a timer (older servo drivers or bit-bang RF encoders) may require an updated version.

Hardware

Complete code

// Balayage de positions sur servo, broche 9 (broche PWM valide)
#include <Servo.h>

Servo myservo;
const uint8_t BROCHE_SERVO = 9;
const uint8_t positions[] = {0, 45, 90, 135, 180};
uint8_t index = 0;
uint32_t tPrecedente = 0;

void setup {
  myservo.attach(BROCHE_SERVO);   // impulsions 1 a 2 ms
  Serial.begin(9600);
  Serial.println(F("Servo pret"));
}

void loop {
  if (millis - tPrecedente >= 1000) {
    tPrecedente = millis;
    myservo.write(positions[index]);
    Serial.print(F("angle="));
    Serial.println(positions[index]);
    index = (index + 1) % (sizeof(positions) / sizeof(positions[0]));
  }
}

Expected verification

The servo arm moves every second to 0°, 45°, 90°, 135°, 180°, then starts over. The serial monitor displays the current angle. At the end of the travel range, the servo growls slightly (command out of range): this is normal with write at the limits.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials