🛠 Piloter un micro-servo moteur

Arduino Nano (Classic, ATmega328P) · intermediaire · Schéma : IMG-nano-classic-intermediaire-5-nanoc-servo.svg — micro-servo SG90 alimenté en 5 V, signal sur broche 9 de l'Arduino Nano, balayage 0-180 degrés

Objectives

Control a micro-servo (such as the SG90) using the Servo library: the servo expects a 20 ms frame where a 1 to 2 ms pulse defines the angle. We program a 0-180° sweep and discuss proper power supply (the Nano's 5 V is sufficient for ONE small servo, never for multiple).

Hardware

Complete code

// Balayage servo 0-180 degres sur la broche 9
#include <Servo.h>

Servo myservo;
uint8_t angle = 0;
bool sens = true;

void setup {
  myservo.attach(9);        // signal sur broche 9
  myservo.write(0);
  Serial.begin(9600);
}

void loop {
  angle += sens ? 5 : -5;   // pas de 5 degres
  if (angle >= 180) sens = false;
  if (angle <= 0)   sens = true;
  myservo.write(angle);     // 0..180
  Serial.println(angle);
  delay(50);                // vitesse du balayage
}

Expected verification

The servo arm sweeps regularly from 0° to 180° and returns, smoothly, without excessive jitter or constant buzzing. The serial monitor displays the increasing then decreasing angle setpoint. When stopped at a position, the servo holds its torque without trembling in a loop.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials