Servo and Knob
Part of the Outputs section of Coddy's Arduino journey. Lesson 22 of 24.
The arm can follow a knob instead of a fixed list of angles. It is the same pattern as the dimmer and the pitch knob: read, convert, use.
The knob gives 0 to 1023 and arm.write() takes 0 to 180 degrees, so map() converts between them:
int reading = analogRead(A0);
int angle = map(reading, 0, 1023, 0, 180);
arm.write(angle);A reading of 0 becomes 0 degrees, 1023 becomes 180, and everything in between lands in between, so the arm turns as the knob turns.
Printing the angle with Serial.println() shows in the Serial monitor which number the arm is getting, which helps when it does not point where you expect.
Challenge
EasyMake the servo follow the knob:
- read the knob with
analogRead(A0) - turn the reading into an angle from 0 to 180 with
map() - move the arm there with
arm.write()and print the angle
Press Run and turn the knob, then Check.
Try it yourself
#include <Servo.h>
Servo arm;
void setup() {
arm.attach(9);
Serial.begin(9600);
}
void loop() {
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Outputs
Practice on your own: Arduino playground