Overview
This project involves controlling a servo motor based on input received through the serial monitor. Users input a value between 0 and 180 via the serial monitor, which corresponds to the angle to which the servo motor should rotate.
Components
Component Name | Purpose |
---|---|
Arduino Nano | This will be the microcontroller |
SG90 180 degree servo | This will be the servo |
Circuit Diagram
Assembly
SG90 180 degree servo
Nano Pin | Servo Pin |
---|---|
D4 | Sig |
5V | VCC |
Gnd | Gnd |
Code
/*
Project: Serial input with output as servo
Project Description:
This sketch writes readings reads from serial and accordingly rotates.
This sketch is for a servo
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
// For Arduino Nano
#include <Servo.h>
// For ESP32
// #include <ESP32Servo.h>
// PIN DEFINITIONS
#define ServoPin 4
// CONSTANT DEFINITIONS
// GLOBAL VARIABLES
// Used for reading by character.
// Note that the 64 byte size of the Arduino serial input buffer does not limit the number of characters that you can receive
// because the code can empty the buffer faster than new data arrives.
// Used for reading an integer value.
int receivedValue;
// Create objects
Servo myServo; // create servo object to control a servo
// LOCAL FUNCTIONS
// Read an entire string (this is a blocking function and waits until timeout).
void readValue()
{
Serial.println("Enter a value between 0 - 180:");
// Wait until data is available
while (!Serial.available()) {}
// Read characters until newline is encountered
String input = Serial.readStringUntil('\n');
// Convert the input string to an integer
receivedValue = input.toInt();
// Print the entered value for confirmation
Serial.print("Entered value: ");
Serial.println(receivedValue);
// Clear the input buffer to prevent trailing characters
while (Serial.available()) {
Serial.read(); // Read and discard any remaining characters
}
}
void writeToServo(int value){
myServo.write(value);
}
void servoSetup()
{
// Define servo
myServo.attach(ServoPin);
}
// THE setup FUNCTION RUNS ONCE WHEN YOU PRESS RESET OR POWER THE BOARD.
void setup() {
Serial.begin(9600);
servoSetup();
Serial.println("The board is ready!");
}
// THE loop FUNCTION RUNS OVER AND OVER AGAIN FOREVER UNTIL THE BOARD IS POWERED OFF.
// Run only one option at a time (comment out all code for the other option).
void loop() {
// Read a string
readValue();
writeToServo(receivedValue);
delay(1000);
}