Program to fade in and fade out LED

Write the following code in Cloud9 and save it as fadeLED.js. Run the program and you should see the LED fading in and out alternatively.

The code for fadeLED.js is as follows:

var b = require('bonescript'),
var led = "P9_21";
var loopTime = 20;
var duty_cycle=0;
var increment = true;

var loopTimer = setInterval(fadeLED, loopTime);

function fadeLED()
{
    if(duty_cycle == 100 )
        increment = false;
    if(duty_cycle == 0)
        increment = true;

    if(increment == true)
        duty_cycle = duty_cycle + 1;
    else
        duty_cycle = duty_cycle - 1;

    console.log("duty_cycle = ",duty_cycle/100);
    b.analogWrite(led,duty_cycle/100);
}

Explanation

In Chapter 3, Blinking External LEDs we used the function digitalWrite() with a similar setup. Here, we are using the analogWrite() function. We are initializing the variable duty_cycle with a value of zero. We use the variable increment as a Boolean flag to keep track of fading in or fading out. Then we declared loopTimer to call the fadeLED() function after each 20 milliseconds. Inside the function fadeLED(), we are checking the duty_cycle value. If it is equal to 100, then we reached maximum limit. Here, we set the flag increment to false to mark that we will fade out now. If the duty_cycle is equal to 0, we will mark the flag increment to true. Based on the flag value, we increment or decrement the duty cycle. Finally, we used the analogWrite() function to write a duty_cycle ratio on pin P9_21. This step actually puts PWM voltage on the pin.

In the beginning, the variable duty_cycle gets incremented by 1 after each 20 milliseconds from 0 to 100. Then it gets decremented by 1 after each 20 milliseconds from 100 to 0. When it is incrementing, the duty cycle of the PWM increases and so does the voltage on the pin. Increased voltage makes the LED brighter. When decrementing, the PWM duty cycle reduces the voltage on the pin. It makes the LED dimmer. This fade in and fade out happens alternatively till we stop the program. There could be errors related to device tree and sysfs file non-existence which go away after reboot. You can see device tree related messages using the dmesg command or in the /var/log/messages file.

If you shoot this LED with a high frame rate camera, you will see it is switching on and off. If you attach an oscilloscope to the pin, you will get a PWM waveform. The LED is not remaining ON for all the time. There are fluctuations. But they are fast enough (2 kHz) not to be captured by the human eye. Let's use the same technique to control a micro servo motor.

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

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