element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet & Tria Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • About Us
    About the element14 Community
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Japan
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      •  Vietnam
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Arduino
  • Products
  • More
Arduino
Arduino Forum serial controlling a servo?
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Arduino to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • State Not Answered
  • Replies 5 replies
  • Subscribers 417 subscribers
  • Views 2157 views
  • Users 0 members are here
  • heat
  • on
  • help
  • the
  • yells
  • me
  • at
  • control
  • leaving
  • thermostat
  • servo
  • heating
  • please
  • for
  • serial
  • uno
  • arduino
  • dad
  • bacon
Related

serial controlling a servo?

e14 Contributor
e14 Contributor over 12 years ago

I got 2 servos in hopes of attaching them to my thermostats and having them turn the knobs but, i don't feel like changing the variables and re uploading the code to my arduino uno.  How would I be able to send a serial signal my computer and set that to a var on the arduino witch will turn the servo?

 

failed try:

 

#include <Servo.h>

 

 

Servo servo;

int servoSerial;

 

 

void setup(){

Serial.begin(9600);

servo.attach(9);

}

 

 

void loop(){

  servoSerial = Serial.read()

servo.writeMicroseconds (servoSerial);

}

  • Sign in to reply
  • Cancel
  • Robert Peter Oakes
    0 Robert Peter Oakes over 12 years ago

    Hi Kyle

     

    Im afraid you need to walk before you can run...

     

    Try simply controlling the servo using the code first, then look at how serial.Read and Serial.Write actually do, there all about CHAR types and strings so you need to learn how to convert them to usable values using commands like ATOI(string) that converts a string to an Integer as an example

     

    You need to know what a char type actually is and what it looks like when received by the serial.Read command etc, to demonstrate this... Sending 127 from the keyboard of the PC to the Arduino does not yield the number 127 to be simply sent to the servo output, it arrives as 3 character values "1", "2" and "7", these would have to be converted to a number before you use them, in your code the way it is, sending a single character from the alphabet only and knowing its decimal value would or should work ut you need to know what is the right character for 1 through 127 or even 255 (Google Ascii Table)

     

    The Arduino sample sketches have all these examples built in for you to review and learn

     

    Once you understand them, it will be time to move onto combining different programs into ones you design

     

    Peter

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • gdstew
    0 gdstew over 12 years ago

    Here is a test program I wrote (I think I modified an existing sketch I don't remember) that does what you want.  To use it send

    1S0# - 1S180# to position the servo from 0 to 180 degrees.

     

    // Test program for the SG-90 servo motor

    //

     

    #include <Servo.h>

     

    #define SerialSpeed 9600

    #define BufferLength 16

    #define LineEnd '#'

    #define PinServo1 5

    #define DefaultPosition 90

     

    Servo servo1 ;

    char inputBuffer[BufferLength] ;

     

    void setup()

    {

       pinMode(PinServo1, OUTPUT) ;

     

       // Attach servo and set servo min/max timing, and move to default position

     

    //   servo1.attach(PinServo1, 560, 2420) ;

       servo1.attach(PinServo1) ;

       servo1.write(DefaultPosition) ;

     

       Serial.begin(SerialSpeed) ;

    }

     

    void HandleCommand( char *input, int length)

    {

        Serial.println(input) ;

     

        if (length < 2)

          {

            return ; // Invalid command length

          }

     

        int value = 0 ;

     

        if (length > 2)

          {

            value = atoi(&input[2]) ;

     

            if ((value < 0) || (value > 180))

              {

                return ; // Invalid position parameter

              }

          }

     

        int *command = (int *)input ;

     

        switch (*command)

          {

            case '1S':

     

              servo1.write(value) ;

              break ;

     

            default:

     

              Serial.println("Unknown command") ;

              break ;

          }

    }

     

    void loop()

    {

      // Get a command stringfrom the serial port

     

       int inputLength = 0 ;

     

       do {

            while (!Serial.available()) ; // Wait for command

     

            inputBuffer[inputLength] = Serial.read() ;

          } while ((inputBuffer[inputLength] != LineEnd) && (++inputLength < BufferLength)) ;

     

        inputBuffer[inputLength] = 0 ; // Make sure command string is null terminated

        HandleCommand(inputBuffer, inputLength) ;

    }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Robert Peter Oakes
    0 Robert Peter Oakes over 12 years ago in reply to gdstew

    I am assuming this test code works, it seems to have all the basics you need to control the servo, you simply need to modify it and the commands to be able to work with two servos.

     

    not meaning to imply anything but do you understand what this code is doing (The code you just provided, not the code in the original post), just if you do understand it then I fail to understand how you came up with your first code sample as it is so much closer to what you would need

     

    please add a schematic showing how you see this all being connected including how you intend to control it

     

    also what do you mean by "i don't feel like changing the variables and re uploading the code to my arduino uno" ?

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • gdstew
    0 gdstew over 12 years ago

    Here is a two servo version of the previous program. I have also attempted to make it

    more robust by:

     

    1) Standardizing part of the error messages so they can be more easily recognized by

         the sending program.

    2) Adding a short standard response message when the command is accepted and the

         function to change the servo position has been executed. Note that this does not verify

        that the  servo  position has changed, only that the function to change it has been

        executed.

     

    I added many comments to make it easier to understand.

     

    I also fixed an error in the program where in a couple of places the command input

    buffer name was wrong (input instead of inputBuffer).

     

    // Test program for the SG-90 servo motor

    //

    //  to change servo 1 position send 1S0# - 1S180# command to Arduino

    //   serial port

    //

    //  to change servo 2 position send 2S0# - 2S180# command to Arduino

    //   serial port

     

    #include <Servo.h>

     

    #define SerialSpeed 9600

    #define BufferLength 16

    #define LineEnd '#'

     

    // Define Ardunio connector pin numbers used for servo motors, pins 9, 10,

    //  and 11 can also be used

     

    #define PinServo1 5

    #define PinServo2 6

     

    // These can be changed to fit servo range needed

     

    #define DefaultPosition 90

    #define MinPosition 0

    #define MaxPosition 180

     

    // Create two servo objects using the servo library

     

    Servo servo1 ;

    Servo servo2 ;

     

    char inputBuffer[BufferLength] ; // Buffer used for incomming servo position

                                     //  commands

     

    void setup()

    {

       // Configure Arduino I/O pins

     

       pinMode(PinServo1, OUTPUT) ;

       pinMode(PinServo2, OUTPUT) ;

     

       // Attach servos per servo library and move to default position

     

       servo1.attach(PinServo1) ;

       servo1.write(DefaultPosition) ;

       servo2.attach(PinServo1) ;

       servo2.write(DefaultPosition) ;

     

       // Initialize serial port

     

       Serial.begin(SerialSpeed) ;

    }

     

    void HandleCommand(char *inputBuffer, int length)

    {

        // Minimum command is 1S0# or 2S0#, 4 characters

     

        if (length < 4)

          {

           // Send error message to serial port

     

            Serial.println("ERROR: Invalid command length") ;

            return ; // Invalid command length

          }

     

        int value = 0 ;

     

        value = atoi(&inputBuffer[2]) ;  // Convert ASCII position string to an integer

     

        // Check for minimum and maximun servo position settings

     

        if ((value < MinPosition) || (value > MaxPosition))

          {

           // Send error message to serial port

     

            Serial.println("ERROR: Invalid servo position") ;

            return ; // Invalid position parameter

          }

     

        int *command = (int *)inputBuffer ; // Get a pointer to the first two characters in command buffer

     

        // See if the pointer points to a valid command in the command buffer

     

        switch (*command)

          {

            case '1S':

     

              servo1.write(value) ; // Servo 1 position command found, change servo position

              Serial.println("OK") ; // Send command executed response

              break ;

     

            case '2S':

     

              servo2.write(value) ; // Servo 2 position command found, change servo position

              Serial.println("OK") ; // Send command executed response

              break ;

     

            default:

     

              Serial.println("ERROR: Unknown command") ;

              break ;

          }

    }

     

    void loop()

    {

      // Get a command string from the serial port

     

       int inputLength = 0 ;

     

      // Read incomming command from serial input buffer one character at a time putting

      //  it in the command buffer  while looking for command terminator and making sure

      // it does not over  run the buffer

     

       do {

            while (!Serial.available())

             {

               // Other functions can be called from inside this loop but care must be taken that

               //  they do not take so long to execute that incoming commands are missed

     

               ; // For now do nothing while waiting for commands to be received

             }

     

            inputBuffer[inputLength] = Serial.read() ; // Read one character at a time

          } while ((inputBuffer[inputLength] != LineEnd) && (++inputLength < BufferLength)) ;

     

        inputBuffer[inputLength] = 0 ; // Terminate command string with null

        HandleCommand(inputBuffer, inputLength) ; //

    }

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Robert Peter Oakes
    0 Robert Peter Oakes over 12 years ago in reply to Robert Peter Oakes

    just realised this was from someone else Helping Kyle, Sorry Gary

     

    Like I said, this one looks like it should do the trick so Kyle, try to understand the one Gary provided and go from there

     

    Again, Sorry Gary.

     

    Peter

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2026 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube