Controlling a Micro-Servo

In this post, I'll show you how to use a micro-servo in Arduino and be controlled from an Android application. Let's start by describing what a servo is.

A servomotor is a motor in which the shaft rotates in micro steps. You can control the servo by sending the angular degrees by which it should position its shaft.


Our circuit consists of only the motor and the arduino. Our servo motor has 3 wires as you can see from the photo above - brown, red and orange. Brown wire goes to the ground, red wire goes  to Vcc or to the positive line and orange goes to one of the PWM pins.

We just need to send a value in Pin 8 and our servo motor will position its shaft to the given value.


#include >Servo.h>
#include >Usb.h>
#include >AndroidAccessory.h>

Aside from the standard Usb.h and AndroidAccessory.h, we now need to import Servo.h as well. Then we declare a variable for our servo.

Servo servo;

Next is to initialize our AndroidAccessory object just like what we did in our previous demos.

AndroidAccessory acc("Marc Tan",
             "Servo Seeduino Board",

Then let’s start implementing our setup and loop functions.

void setup(){


setup() function initializes the serial communication for debugging. Then we need to call acc.powerOn() so that a broadcast intent will be fired on the Android device side and we can select what application should be opened for the attached accessory. Then lastly, we will bind our servo data pin to PWM pin 8.

void loop(){
      byte msg[1];

      if (acc.isConnected()) {
            int len =, sizeof(msg), 1);
            if(len > 0){
            servo.write(0); // reset to 0 degree position


Again, we need to make sure our device is still connected before doing anything else. After reading the data from the stream, we just need to call servo.write() function and add a 15 ms delay so that there will be enough time to wait for the servo motor to position its shaft. If the device isn’t connected, we will reset its shaft to 0 degree position.


The APK code is almost the same as the previous demo apps I’ve created. We just need to limit the data to be sent from 0-179. So to control the servo to rotate from 0-179, we execute the following code.


comments powered by Disqus