double-servo.ino

Arduino Mega 2560 (Rev3) · File : double-servo.ino · Language : Arduino · Use case : Piloter deux servo-moteurs simultanément (tête de robot)

The Servo library handles up to 12 servos on the Mega via timer 1: here a panning head and a tilt axis sweeping at different amplitudes. Each servo on its own 5 V rail prevents brown-outs.

Hardware required

An Arduino Mega 2560 (ATmega2560, 16 MHz, 5 V): 54 digital I/O, 15 PWM, 16 analog inputs, 4 hardware UARTs. 2 servos (SG90) + external 5 V supply.

Wiring

Signals to 9 and 10, +5 V and GND paralleled with the board (common grounds).

How it works

Two independent state machines sweep within their bounds; timer 1 of the ATmega2560 generates the pulses without blocking loop(). In the Arduino IDE, select « Arduino Mega 2560 » and the port, then Upload. PWM on 2-13 and 44-46; UART1=18/19, UART2=16/17, UART3=14/15; SPI on 50-53.

Going further

Add a joystick (2 potentiometers on A0/A1) for manual head control.

double-servo.ino

// Deux servos independants : panoramique + inclinaison.
#include <Servo.h>

Servo tete, cou;
int a = 0, b = 90;
int sa = 3, sb = 2;

void setup() {
  tete.attach(9);   // panoramique
  cou.attach(10);   // inclinaison
  Serial.begin(9600);
}

void loop() {
  tete.write(a);
  cou.write(b);
  a += sa; b += sb;
  if (a <= 0 || a >= 170) sa = -sa;
  if (b <= 45 || b >= 135) sb = -sb;
  delay(30);
}

← Back to the board