Program to control a micro servo motor

Write the following code in Cloud9 and save it as microServo.js. Run the program and you should see the servo motor moving from 0 to 180 degrees to and fro.

The code for is microServo.js as follows:

var b = require('bonescript'),
var servo = 'P9_14';
var duty_min = 3;
var loopTime = 5;
var angle = 0;
var increment = true;

b.pinMode(servo, b.OUTPUT);
var loopTimer = setInterval(updateAngle, loopTime);

function updateAngle(x)
{
   
    if(angle == 180 )
        increment = false;
    if(angle == 0)
        increment = true;

    if(increment == true)
        angle = angle + 1;
    else
        angle = angle - 1;
   
        var duty_cycle = (angle * 0.064) + duty_min;
    console.log("angle =",angle);
    console.log("duty cycle = ",duty_cycle);
    b.analogWrite(servo, duty_cycle/100, 60);
}

Explanation

In this program, we created loopTimer, which will increment/decrement the shaft angle by one degree. We know that we have a limit of 3% to 14.5% to drive the servo. So, we created an equation where we get 180 values in the duty cycle range of 3 to 14.5:

duty_cycle = (angle * 0.064) + duty_min

where

duty_min = 3

angle = angle in between 0 to 180

Now, any value for the variable angle from 0 to 180 will give a duty_cycle value inside 3 to 14.5. We apply it using analogWrite(). We set the frequency to 60Hz, which creates a 16.66 millisecond pulse. This is near to the 20 millisecond period needed to drive the servo motor. The timer gets called after every 5 milliseconds and it calls the function updateAngle(), which either increments shaft angle by one degree or decrements by one degree. Inside updateAngle(), if the variable angle reaches the limits, that is, 0 or 180, then we toggle the flag variable increment. Based on this flag, we change the duty cycle inside range from 3% to 14.5% and then from 14.5% back to 3%. The servo shaft moves to and fro according to the duty cycle change.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.16.81