Project 2. Fade, pulse and multiple colors

IMG_20160501_230916614_HDR

In the last project, you cobbled together a very simple digital circuit that made a single LED blink. In this project, you will see how to make LEDs fade in and out.

In a traditional incandescent light bulb, the brightness of the bulb can be controlled simply by adjusting the voltage across the filament. This works because these bulbs operate at 120 volts, and a simple rheostat (that is, a variable resistor) is sufficient to increase or decrease the voltage, such that at 60 volts or 90 volts, it will glow slightly dimmer than at maximum voltage. (The values aren’t linear, so it’s not half as bright at 60 volts or whatever. The calculations and explanations are quite technical, and beyond the scope of this blog.) However, an LED requires an exact voltage to operate, with very little tolerance for variance, such that a 5 volt LED works on a voltage range from 4.5 to 5.5 volts (hypothetical numbers, purely to demonstrate the concept). So how can you make an LED “fade”, so that its brightness seems variable? The answer is a capability built into the Arduino, known as Pulse Width Modulation.

Pulse Width Modulation, hereafter referred to as PWM, is a technology used in many digital circuits. PWM means pulses that are on for some percentage of the time, and off for the remainder of the time. Arduino PWM pulses 255 times per second, and the “on” time (known as the duty cycle in technical circles) is how much of each of the pulse is High

512e869bce395fbc64000002
PWM example. Image source: https://learn.sparkfun.com/tutorials/pulse-width-modulation

If you look down the row of digital pins on the Arduino, you will notice that pins 3, 5, 6, 9, 10 and 11 are marked with a tilde (~). These are the pins that support PWM.
[[image]]
By connecting the LEDs to these, and writing the program to use PWM output, you can make it appear to be dimmer or brighter. In reality, they are just switching on and off, but it happens so quickly, much quicker than the eye can perceive, that it appears to be dimmer or brighter.

To make this happen, you will retain the board setup from project 1. The only difference is in the programming, and those differences are relatively trivial.

int ledPin = 10;
void setup() {
//nothing to see here

}

void loop() {
for(int k = 0; k <= 255; k += 5)
{
 analogWrite(ledPin, k);
 delay(30);
}
for(int k = 255; k >= 0; k -= 5)
{
 analogWrite(ledPin, k);
 delay(30);
}
}

In this program, you will notice two differences: the two “for” loops, and that the pins use analogWrite() instead of digitalWrite(). Part of the Arduino library includes functions that convert values written in analogWrite() into PWM values. In particular, it uses values from 0 to 255 to define the duty cycle (see above) of the pin. A value of 0 means 0% duty cycle, the same as digitalWrite(ledPin, LOW); a value of 255 means 100% duty cycle, the same as digitalWrite(ledPin, HIGH). The for loops are arranged in such a way that it increases or decreases the duty cycle by approximately 5% with each execution of the loop. The delay of 30 ms is to make the fade effect visible.

[[gif video of the fade effect taking place]]

By adjusting the values of the delay and/or the third statement defining the for loop [k +=/-= 5], you can adjust the time frame on which the fade takes place.

Finally, and for some added fun times, you can take an RGB LED and hook it up to fade the three colors in and out for mixed colors. The RGB LED used in this example is a common anode: you will connect the longest pin to the voltage source (+) and the other three will act as ground (-), in this case flowing into the Arduino itself. led-rgb1
Common anode RGB LED pinout diagram. Image source: http://www.hertaville.com/files/uploads/2012/09/LED-RGB1.png

The program, seen here, uses sequences of for loops to fade the three colors (red, green and blue, each connected to a PWM-enabled output) in and out, giving the appearance of “mixed” colors.

int redPin = 9; // Red cathode connected to digital pin 9
int greenPin = 10; // Green cathode connected to digital pin 10
int bluePin = 11; // Blue cathode connected to digital pen 11

void setup() {
 //nothing to see here, but gotta have this block of code anyway
 //that's just the way it is

}

void loop() {
int n = 0; 
for(int k = 0; k < 255; k++)
{
 n = 255-k;
 analogWrite(greenPin, k);
 analogWrite(bluePin, n);
 delay(10);
}

for(int k = 0; k < 255; k++)
{
 n = 255-k;
 analogWrite(greenPin, n);
 analogWrite(bluePin, k);

 delay(10);
}

for(int k = 0; k < 255; k++)
{
 n = 255-k;
 analogWrite(greenPin, k);
 analogWrite(redPin, n);

 delay(10);
}

for(int k = 0; k < 255; k++)
{
 n = 255-k;
 analogWrite(greenPin, n);
 analogWrite(redPin, k);

 delay(10);
}

for(int k = 0; k < 255; k++)
{
 n = 255-k;
 analogWrite(bluePin, k);
 analogWrite(redPin, n);

 delay(10);
}

for(int k = 0; k < 255; k++)
{
 n = 255-k;
 analogWrite(bluePin, n);
 analogWrite(redPin, k);

 delay(10);
}
}

Project 1. Blinky LEDs

IMG_20160501_214600910

So now that you have a rough understanding of what it is you’re working with and have gathered all the components you need to get started, it’s time for you to get started. This first project is designed to get your feet wet, and requires only an introductory knowledge of programming.

 

The first thing you are going to do is take the breadboard and attach your components as follows:

One LED, inserted into two parallel rows. You will notice that the two connecting pins of the LED are different lengths. The long pin of the LED is the Anode, will be connected to Pin 10 on the Arduino. The shorter pin of the LED is the Cathode, and is connected to the ground (-) rail on the breadboard, which is then connected to the ground pin on the Arduino. It is important to connect these pins in this fashion, as connecting them in reverse simply will not work (this is how diodes work; they only allow current to flow in one direction). You should also put a resistor somewhere between the LED and the circuit, because failing to do so could cause the diode to pull too much current, which will cause it to burn out. The value of the resistor, as determined by the colored bands printed on the resistor (a very nifty tool can be found here which will allow you to input the colors and will tell you the resistor resistance), should be between 100 and 600 Ohms. Too much resistance and it won’t be able to pull any current at all, too little and it will burn the diode out. I used a 330Ω resistor, right in the range of tolerable values. (Each LED color and size will require slightly different resistor values. To get an exact value, read the reference sheet that comes with the LEDs; it will tell the operating amperage of the diode. To calculate the resistance needed, divide 5 volts, the operating voltage of the Arduino, by that amperage. For example, a resistor that requires 20 milliamps of current would require 5v/0.02A = 250Ω resistor.)

IMG_20160501_214419146

Once you’ve got the setup complete, you can connect the Arduino to your computer. The next step is writing the program. Ideally, you would have downloaded the Arduino IDE (Integrated Development Environment) from the Arduino website. If you haven’t done so yet, click here and make it happen. This particular code is quite simple, thanks to the geniuses in the Arduino labs: they have written extensive libraries of code that allow end-users to write programs in an almost English-like syntax. The code block is as follows:

int ledPin = 10; //This line, at the very start of the program, defines which pin we will be using to connect to the LED

void setup(){
//If we were writing a more complicated program, we would have something besides comments written here
//This time we will not be using the setup function, because there’s nothing that needs to be set up
//However, we still have to have this here because of how the Arduino programming interface works
}

void loop(){ //This block of code loops indefinitely, and the main body of the program is always written here
digitalWrite(ledPin, HIGH); //Write a digital HIGH (1) to the pin connected to the LED
//The Arduino will do its technical trickery to make the voltage across Pin 10 go to 5V
delay(500); //The delay function is measured in milliseconds. In this case, it equals 0.5 seconds
digitalWrite(ledPin, LOW); //The opposite of the previous command, it will force Pin 10 voltage to 0
delay(500); //Another delay
}

So, what you have here is a program that will turn the LED on, wait half a second, turn the LED off, wait half a second, then repeat from beginning ad infinitum. Super fancy, right?

You can attach multiple LEDs to the different pins on the Arduino, put them on different delays, and make multicolored blinky lights for any reason or purpose your imagination can concoct. In project 2, we will explore making the LED fade in and out using optical trickery.

 

 

 

 

Materials Required

The materials needed for projects in this blog are simple:

  1. Arduino Uno:IMG_20160501_212154286_HDR[1]
    Self-explanatory: this is the heart and brain of all projects conducted here.
  2. USB Cable:
    IMG_20160501_234336440_HDR[1].jpg
    This, specifically, is a USB Type B male-to-male cable used to connect the Arduino to the computer.
  3. Breadboard:
    IMG_20160501_230613772_HDR
    This is a circuit prototyping board. These can be purchased very cheaply at Radio Shack or various online stores. These are used to connect components to voltage sources and input/output lines on the Arduino.
  4. Jumper wires:
    IMG_20160501_212206867_HDR
    These wires have pins on either end that make it easy to connect and disconnect devices, and the pin size is standard for both the breadboards and the Arduino I/O sockets.
  5. LEDs:
    IMG_20160501_212234083_HDR
    These will blink and fade depending on how the Arduino is programmed, and provide a visual indicator of the program logic.
  6. Resistors:
    IMG_20160501_212243873_HDR
    These are used in series with the LEDs to control the amount of current provided to the LED. The values will be explained in each post.

Cool, but what IS an Arduino?

That is a very good question, and ultimately depends on what the meaning of the word “is” is.

Arduino refers to a family of products, all based around the same concept: a microcontroller, on a small form factor circuit board, augmented with additional circuitry to make the platform simple to use and learn. The product used in projects on this blog is the Arduino Uno, so named because it was the first product they officially released. (Note: I bought my Uno in 2013, and the design has undergone a few incremental changes since then. However, the differences between the Uno used on this blog and one purchased brand-new today are only visual; all programs, wiring diagrams, breadboard layouts, etc. will be identical.)

arduinouno_r3_front_450px

Top view of Arduino Uno. Image source: arduino.cc

The Uno is based on the Atmel ATmega328P microprocessor. An in-depth technical description of this processor is beyond the scope of this website, but the Arduino platform takes this microprocessor and builds around it a platform that includes a USB port, a USB controller, a bootloader and multiple jumper sockets connected to the various input/output devices on the processor. This platform allows the Arduino to be used by starters to build circuits without needing any knowledge of fabrication techniques; you don’t need to solder together connections, which is precise and frustrating; etch your own PCBs, which requires harsh chemicals and can ruin components if not done properly; or flash program any devices, which requires expensive hardware and extensive knowledge of programming in Assembly. Devices can be connected by sticking jumper wires into a breadboard, and programs can be written in C and transferred via USB cable.

[[homebrew image of arduino]]

In addition to the simplicity and ease of use with which the Arduino has been designed, there is a massive community of homebrewers, with diverse spectra of backgrounds and experiences.

What the heck is an “Arduino”?

Before I can explain Arduino, I need to explain microcontrollers:

A microcontroller is a miniaturized computer on a single chip, which may contain any number of inputs and outputs. They are usually much more minimal and constrained in what they are capable of, compared to what people usually think when you say “computer”, but they are physically quite small and use very little electricity. They are called “microcontrollers” because they are often used as controllers: when a minimal, autonomous solution to control a machine or process is required. To put these size differences in context: your PC could have a 2.5GHz quad core processor, 8GB of RAM, 500GB or more of storage available, and can handle an arbitrarily large number of inputs (it can communicate with many devices simultaneously, some at very fast speeds). A microcontroller, like the one you’d find in a microwave or vending machine, might have a 25MHz clock (1/100 the speed of your pc), ~128Kb or less of memory, and could only handle 15-30 simple binary inputs. However, your PC is 2 feet tall, 6 inches wide and a foot deep, and requires 300-500 watts to power; a microcontroller, on the other hand, might be just a few square millimeters in size and some can operate on milliwatts of power or less.

For example, your refrigerator has a microcontroller inside that controls the heat pump and fans. It would have a temperature sensor and the temperature control knob as inputs, and the outputs are connected to relays that activate the heat pump. The microcontroller would be programmed to repeat the same loop over and over: read the internal temperature of the fridge from the temperature sensor and compare that value to the desired temperature (as determined by the control knob); then, if the actual temperature is higher than the desired temperature, it will activate the heat pump to start lowering the temperature within the box. It will leave the heat pump on until it measures the internal temperature to be equal to or lower than the desired temperature, whereupon it will open the heat pump relay, turning it off. The microcontroller will loop this same program indefinitely, until the fridge is unplugged.

So what’s the point? Well, compared to your laptop, iPad, or desktop computer, the microcontroller is very small, but completely sufficient for running simple math operations and controlling simple outputs. Microcontrollers are everywhere and in everything: automated toilets, printers, toll booths, all sorts of kitchen appliances, televisions, etc. Microcontroller programs are often simpler and smaller than programs for full-sized computers, no more complicated than they need to be. However, most microcontrollers require advanced hardware and knowledge of manufacturing/fabrication techniques to use. To create a project using raw hardware requires circuit fabrication materials and knowledge of techniques, oscilloscopes and logic analyzers for debugging, and special hardware to load the programming onto the chip; such a setup can cost upwards of tens of thousands of dollars. In addition, programs are often written in Assembly language, which is unique to each microprocessor architecture, and each with its own esoteric (and in some cases, quite archaic) set of commands and syntax rules.