Arduino Lab 6

PWM output

How could you vary the apparent brightness of an LED? Supposed you turned it on for 5m sec (.005 sec) and then turned it off for 5m sec. Your eyes would not notice the LED flashing at this rate. (After all, most LED displays already do something like this and you haven't noticed it yet.) However, this rapidly flashing LED would appear a little dimmer than an LED that is also on. An LED that was on for 2m sec and then off for 8m sec, would be even dimmer.

This technique of modulating a digital output so that, when treated properly, it acts like an analog output is called pulse-width modulation, or PWM. In PWM, the length of the repeated pattern is called the period. The inverse of the period is the frequency. The proportion of the time when the output is high is called the duty cycle. Thus the dim LED (on for 2m sec and off for 8m sec) has a duty cycle of .2, a frequency of 100 Hz, and a period of 10m sec.

The digital pins of the Arduino board labeled "PWM" can produce analog output with the analogWrite output routine. Start by calling the analogWrite to dimly light your LED. Then modify your code to go through a cycle of slowly dimming and brightening the LED.

Analog input

The Arduino can read true analog input with the analogRead routine. When this routine is called, the board (or rather the ATmega processor) will measure the voltage at an analog input pin and return a number between 0 and 1023. The input voltage must be between 0 V and 5 V and the returned value is roughly proportional to its value.

If we had some potentiometers, we would use them far this part of the lab. However, we don't, so we're just going to make a voltage divider from a couple of resistors.

In our voltage divider, two resistors are connected in series between ground and 5 V. The junction point between these resitors is then connected to an analog input pin as shown below:
Analog input

The output voltage is determined by the two resistors. In the above example the grounded resistor is 330 Ω and the resistor connected to 5 V is 1k Ω. The output at the junction should be close to (330 Ω / (330 Ω + 1000 Ω))*(5 V - 0 V) or 1.25 V.

Write a program that reads the analog input and uses it to set the brightness of the LED. Since analogRead returns a value up to 1023 and since analogWrite must be passed a value up to 255, your program will need to divide by four. Also, since we don't have any potentiometers, you'll need to add and subtract resistors to see any change in the brightness of the LED.