Lab 3: Servo Motor Control with an Arduino

In this lab, we’ll control a servomotor’s position using the value returned from an analog sensor. Servos are the easiest way to start making motion with a microcontroller. Even though they don’t turn 360 degrees, you can use them to create all sorts of periodic or reciprocating motions.

The Lab:

The Arduino Code:

#include <Servo.h> //include the servo library

Servo servoMotor; //creates an instance of the servo object to control a servo
int servoPin = 2; //control pin for servo motor

void setup() {
Serial.begin(9600); //initialize serial communications
servoMotor.attach(servoPin); //attached the servo on pin 2 to the servo object
}

void loop(){
int analogValue = analogRead(A0); //read the analog input
Serial.println(analogValue); //print it

//if your sensor’s range is less than 0 to 1023, you’ll need to
//modify the map() function to use the values you discovered;

int servoAngle = map(analogValue, 0, 1023, 0, 179);
servoMotor.write (servoAngle);

}

The Result:

The Result

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>