Saturday, November 5, 2016

How to make an LED fade in, fade out with 1 Nusbio GPIO

Overview

With one GPIO (General Purpose Input Output) from an Arduino, Raspberry PI or Nusbio you can easily turn one LED on or off.
But making the LED fade in and fade out is a little bit more complicated. With a micro-controller like an Arduino you can use a GPIO with PWM (Pulse with modulation) and call the method analogWrite(pin, value). The value defines what is called the duty cycle, in simple term this will be the intensity of the LED.



But with a Raspberry PI linked to Linux or Nusbio linked to Windows, there is no PWM (PWM is a hardware function, not available on PC and not managed by the OS).

So for this post I used an good old analog solution:

  • 1 transistor 2N3904
  • 1 100mF capacitor
  • 1 220k Ohm resistor
  • 1 1k Ohm resistor
Wired as follow:

This circuit looks simple, but it is not easy to understand how it works, though it does work as shown in the video.
And I will not try to explain it today.
If you are like me a software developer interested in learning analog electronic, it is a good example to start with because there are so many concepts involved to understand before you can picture how the all thing works:
  • LED voltage drop
  • Capacitor
  • Transistor
  • Sourcing and sinking current
 The first step is to try it on a bread board.

Use a red LED because the LED voltage drop makes a different, a blue LED would require different resistors.

Programming

The programming on the other side is simple, turn the LED on and wait for the LED to fade in,
then the LED off and wait for the LED to fade out.
The speed of the fade in fade out is controlled by the size of the capacitor and the resistance in between the GPIO and the base of the transistor (in my case a 220K Ohm).


var serialNumber = Nusbio.Detect();
if (serialNumber == null) // Detect the first Nusbio available
{
    Console.WriteLine("Nusbio not detected");
    return;
}
Console.Clear();
using (var nusbio = new Nusbio(serialNumber: serialNumber))
{
    ConsoleEx.WriteMenu(0, 1, "Q)uit");
    while (true)
    {
        Console.Write("On ");
        nusbio.GPIOS[0].High();
        Thread.Sleep(1000 * 3);
        Console.Write("Off ");
        nusbio.GPIOS[0].Low();
        Thread.Sleep(1000 * 3);
        if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Q)
            break;
    }
}