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
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.
Next is to initialize our AndroidAccessory object just like what we did in our previous demos.
Then let’s start implementing our setup and loop functions.
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.
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.