Skip to Content
This is the Beta version of our new Learning Paths approach. Please email feedback.

Servo

servo.ino
/* Project: Smart Home Component: Servo Motor Sketch Description: This sketch has functions to rotate a servo motor from 0 to 180 degrees in increments of one degree. This will take an analog input from the app and move the servo to the degree selected. Author: STEMVentor Educonsulting This code is copyrighted. Please do not reuse or share for any purpose other than for learning with subscribed STEMVentor programs. This code is for educational purposes only and is not for production use. */ // LIBRARIES // Install the library "Servo by Michael Margolis, Arduino" from the IDE library manager. #include <Servo.h> // PIN DEFINTIONS // GLOBAL CONSTANTS // GLOBAL VARIABLES // INITIALIZE OBJECTS // Currently supports only one servo, need to add multi-servo support identified by pin. Servo servo; // LOCAL FUNCTIONS // This function will move the servo to a position between 0° and 180° // taking the degree value as a parameter. // This can be used if receiving the degree value like from the app. void moveServoByDegrees(uint8_t pin, uint8_t degrees) { servo.write(degrees); // Sets the servo position to the degrees value passed. delay(2000); // Force a delay to avoid rapid switching. } // This function will move the servo to a position between 0° and 180° // taking a voltage value (0-1023) as a parameter and then converting that to a degrees value. // This can be used if receiving an analog value from a sensor. void moveServoByValue(uint8_t pin, uint8_t value) { uint8_t degrees = map(value, 0, 1023, 0, 180); // Scale the value to between 0 and 180 for the servo. servo.write(degrees); delay(2000); // Force a delay to avoid rapid switching. } void servoSetup() { // Set the Servo object with the pin to which the servo is connected. servo.attach(SERVO_PIN); // Test the movement with a complete sweep with degrees. moveServoByDegrees(SERVO_PIN, 180); moveServoByDegrees(SERVO_PIN, 0); // Test the movement with a complete sweep with values. moveServoByValue(SERVO_PIN, 1023); moveServoByValue(SERVO_PIN, 0); }