servo-sweep.ino
The position servo is the teaching actuator par excellence: this 0-180° sweep on pin 10 shows attach/write and the reversal logic. The Servo library drives the 50 Hz signal on any Nano pin.
Hardware
An Arduino Nano classic (ATmega328P at 16 MHz, 30-pin DIL breadboard footprint, mini-B USB, 5 V logic, RESET pin at the lower-left corner). Arduino Nano, SG90-class servo, external 5 V supply if the movement is loaded (USB alone caps at ~500 mA).
Wiring
Servo: brown/black→GND (common with the Nano), red→external +5 V, orange→D10. Common ground mandatory.
How it works
Servo::write(angle) converts the angle into pulse width (1 ms = 0°, 2 ms = 180°) via the timer. A 5° step every 20 ms gives smooth motion without jerks.
Running it
In the Arduino IDE, select the Arduino Nano board and ATmega328P processor, pick the serial port, then upload. The board's 5 V rail suits 5 V sensors; otherwise use 3.3 V on compatible pins.
Variants
Replace the sweep with potentiometer tracking (map(analogRead, 0, 1023, 0, 180)), or limit the mechanical travel to avoid cracking sounds.
servo-sweep.ino
// Balayage de servo 9g avec la bibliotheque Servo (Arduino Nano).
// Alimentez le servo par une source externe si plusieurs mouvements.
#include <Servo.h>
Servo myservo;
const int BROCHE = 10;
int angle = 0;
int sens = 1;
const int PAS = 5; // degres par iteration
const unsigned long PAUSE = 20; // ms entre pas
void setup() {
myservo.attach(BROCHE); // impulse 1 a 2 ms par defaut
Serial.begin(9600);
}
void loop() {
angle += sens * PAS;
if (angle >= 180) sens = -1;
if (angle <= 0) sens = 1;
myservo.write(angle);
Serial.print(F("angle="));
Serial.println(angle);
delay(PAUSE);
// myservo.read() n'existe pas : un servo de position ne renvoie
// pas sa position. Pour la mesurer, capteur potentiometre ou
// servo en rotation continue codeur.
}