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.

Circuit

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.

Sketch


#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",
             "Seeduino",
             "Servo Seeduino Board",
             "1.0",
             "http://www.marctan.com",
             "0000000012345678");

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


void setup(){
  Serial.begin(115200);
  acc.powerOn();

  servo.attach(8);
}

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 = acc.read(msg, sizeof(msg), 1);
            if(len > 0){
                   servo.write(msg[0]);
            }
      }else{
            servo.write(0); // reset to 0 degree position
      }

      delay(15);
}

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.

APK

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.



outputstream.write(0);
outputstream.write(179);

comments powered by Disqus