Lab: Servo Motor Control with Arduino

In this lab, we learned to control a servomotor’s position using the value returned from an analog sensor. I used a force sensitive variable resistor connected to Analog pin 0 in the Arduino, and a 360 degree servo motor connected to digital pin 3.

lab-servo01

lab-servo02
The code below first calls the servo library using #include. In the setup, the servo is initialized using servo.attach(), and in the main loop, analogRead() reads the sensor. The results are printed in the Serial monitor, while the variable servoAngle sets the servo’s position.

#include < Servo.h > Servo servoMotor; int servoPin = 3; void setup() { Serial.begin(9600); servoMotor.attach(servoPin); } void loop() { int analogValue = analogRead(A0); Serial.println(analogValue); int servoAngle = map(analogValue, 0, 1023, 0, 179); servoMotor.write(servoAngle); }

As a second step in this Lab, I connected another servo to Analog pin 1 and this time used two potentiometers as variable resistors, creating a combined mechanism that rotates two axis independently.

lab-servo03

Arduino code:

#include < Servo.h > Servo servoMotorA; Servo servoMotorB; int servoPinA = 2; int servoPinB = 3; void setup() { Serial.begin(9600); servoMotorA.attach(servoPinA); servoMotorB.attach(servoPinB); } void loop() { int analogValueA = analogRead(A0); int analogValueB = analogRead(A1); Serial.println(analogValueA); Serial.println(analogValueB); int servoAngleA = map(analogValueA, 0, 1023, 0, 30); int servoAngleB = map(analogValueB, 0, 1023, 0, 30); servoMotorA.write(servoAngleA); servoMotorB.write(servoAngleB); }

One Comment

  1. Flavyx

    Thank you very much

Leave a Reply