Sub topic 2
Moving a servo with the Servo library
This chapter assumes you can upload sketches with the Arduino IDE, write setup() and loop() functions, use digitalWrite and pinMode, and understand voltage, current, and ground. Your servo should already have its own 5 V supply, with that supply's ground connected to the Arduino GND pin.
Attaching and writing to a servo
The Servo library ships with the Arduino IDE. You attach a servo to a PWM-capable pin, then write an angle from 0 to 180 degrees.
#include <Servo.h>
Servo myServo;
const int SERVO_PIN = 9;
void setup() {
myServo.attach(SERVO_PIN);
}
void loop() {
for (int angle = 10; angle <= 170; angle++) {
myServo.write(angle);
delay(15);
}
for (int angle = 170; angle >= 10; angle--) {
myServo.write(angle);
delay(15);
}
}The sweep stops at 10 and 170 degrees, just inside the mechanical end stops, which reduces gear strain. The delay(15) calls block loop(), so the sketch does nothing else during the sweep.
Smooth servo sweeps without delay()
millis() returns the number of milliseconds since the board started. Store the time of the last step and move only when 15 ms have passed. loop() keeps running between steps.
#include <Servo.h>
Servo servo;
const int SERVO_PIN = 9;
const int MIN_ANGLE = 10;
const int MAX_ANGLE = 170;
const unsigned long STEP_MS = 15;
int angle = MIN_ANGLE;
int step = 1;
unsigned long lastStep = 0;
void setup() {
servo.attach(SERVO_PIN);
servo.write(angle);
}
void loop() {
unsigned long now = millis();
if (now - lastStep >= STEP_MS) {
lastStep = now;
angle += step;
if (angle >= MAX_ANGLE || angle <= MIN_ANGLE) {
step = -step;
}
servo.write(angle);
}
// Other work can run here on every pass through loop().
}What a small DC motor demands: stall current and back-EMF
A DC motor draws the most current when it is stalled. A spinning coil generates back-EMF, a voltage that opposes the supply. As the motor speeds up, back-EMF rises and current falls. A stalled motor produces no back-EMF, so it can draw several times its running current. An Arduino I/O pin is rated for about 20 mA recommended and 40 mA absolute maximum on the ATmega328P, so a motor must never be connected to a pin directly.
Protecting your circuit with a flyback diode
A motor coil stores energy in its magnetic field. When a MOSFET switches off, the current cannot stop instantly, so the coil pushes a high-voltage spike into the circuit. A flyback diode placed across the motor, with its cathode toward the positive supply, gives that current a safe path.
Exercise
Why does the flyback diode's cathode connect to the positive supply rather than to ground?
Show answer
During normal operation the diode is reverse-biased and does not conduct. The cathode must sit at the positive supply so that the diode conducts only when the coil reverses polarity. It then clamps the spike to about one diode drop above the supply.