servo-balayage.ino
The hobby servo slowly sweeps from 0 to 180° and back. The Arduino core Servo library generates the standard control pulse (1 to 2 ms every 20 ms) on any compatible pin.
Hardware
An Arduino Uno R3 (ATmega328P, 5 V, 16 MHz) powered over USB or a 7-12 V barrel jack. 1 hobby servo (SG90 class, 3-wire connector: signal, +, -).
Wiring
Orange wire (signal) to pin 9, red (+) to 5V, brown/black (-) to GND. For a big servo, use an external supply with common ground.
How it works
myservo.write(angle) sends the pulse matching the angle. The loop increments the angle by 1° every 20 ms and reverses at both ends.
Running it
In the Arduino IDE, select the « Arduino Uno » board and the matching serial port, then click Upload. Open the serial monitor at 9600 baud to follow the messages.
Variants
Drive the angle with a potentiometer (map(analogRead(A0), 0, 1023, 0, 180)), or add a soft start by varying sweep speed.
servo-balayage.ino
// Balayage d'un servo d'angle (SG90, MG90S, etc.) avec la lib Servo.
#include <Servo.h>
Servo myservo;
int angle = 0;
int sens = 1;
const int PAUSE = 20; // ms entre deux degres
void setup() {
myservo.attach(9); // signal du servo sur la broche 9
myservo.write(0);
Serial.begin(9600);
Serial.println(F("Balayage servo 0-180"));
}
void loop() {
myservo.write(angle);
Serial.println(angle);
angle += sens;
if (angle >= 180) sens = -1;
if (angle <= 0) sens = 1;
delay(PAUSE);
}
// Alimentation : un servo qui tire sur le 5V de la carte fait
// planer le micro (reset). Pour un gros servo, alimenter par une
// source externe 4,8-6V en reliant les masses (GND commun).
// La lib Servo occupe les timers 1 et 2 sur les AVR : attention
// aux conflits avec analogWrite() sur les broches 9/10.