servo-balayage.ino

Arduino Pro Mini · File : servo-balayage.ino · Language : Arduino · Use case : Faire balayer un servo-moteur de 0 à 180 degrés

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 Pro Mini (ATmega328P, 5 V/16 MHz or 3.3 V/8 MHz variants) wired to a USB-serial adapter (FTDI) or an ICSP programmer. 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

Select « Arduino Pro Mini » in the IDE (5 V/16 MHz or 3.3 V/8 MHz per your model), ATmega328P processor, the right port, then Upload. The adapter must be wired DTR-DTR, RX-TX, TX-RX, VCC-VCC, GND-GND.

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.

← Back to the board