Kamis, 02 Agustus 2012

Arduino language tutorial (Lesson 3)

LESSON 3:

Controlling Light with PWM

One of the limita-tions of the blinking LED examples that we have used so far in lesson 1 and 2 is that you can turn the light only on and off. A fancy interactive lamp needs to be dimmable.
if you change the numbers in the delay function in example of lesson 1 until you don’t see the LED blinking any more, you will notice that the LED seems to be dimmed at 50% of its normal brightness. Now change the numbers so that the LED is on is one quarter of the time that it’s off. Run the sketch and you’ll see that the brightness is roughly 25%. This technique is called pulse width modulation (PWM).

This technique also works with devices other than an LED. For example, you can change the speed of a motor in the same way.
While experimenting, you will see that blinking the LED by putting delays in your code is a bit inconvenient.
Arduino board has a piece of hardware that can very efficiently blink three LEDs while your sketch does something else. This hardware is imple-mented in pins 9, 10, and 11, which can be controlled by the analogWrite() instruction.

For example, writing analogWrite(9,128)will set the brightness of an LED con-nected to pin 9 to 50%. Why 128? analogWrite()expects a number between 0 and 255 as an argument, where 255 means full brightness and 0 means off.

Let’s try it out. Build the circuit that you see below :
(Note that LEDs are polarized: the long pin (positive) should go to the right, and the short pin (negative) to the left. Also, most LEDs have a flattened negative side, Use a 270 ohm resistor (red violet brown)).
Then, create a new sketch in Arduino and write the following sketch :

// Example 04: Fade an LED in and out like on a sleeping Apple computer
const int LED = 9;                       // the pin for the LED
int i = 0;                                      // We’ll use this to count up and down
void setup() 
{
pinMode(LED, OUTPUT);                 // tell Arduino LED is an output
}
void loop()
{
for (i = 0; i < 255; i++)                  // loop from 0 to 254 (fade in)
{
analogWrite(LED, i);                     // set the LED brightness
delay(10);                                    // Wait 10ms because analogWrite is instantaneous
                                                   // and we would not see any change
}

for (i = 255; i > 0; i--)                  // loop from 255 to 1 (fade out)
{
analogWrite(LED, i);                   // set the LED brightness
delay(10);                                  // Wait 10ms
}
}

END OF LESSON 3




- Reference : O'REILLY  Getting Started with Arduino by Massimo Banzi  , 2nd Edition.

GO TO :

LESSON 1
LESSON 2
LESSON 3
LESSON 4

0 komentar:

Posting Komentar