• Arduino

    Learn about Arduino and make various interesting projects using Arduino...

    Read More
  • 555 IC

    Learn about 555 IC and make various interesting projects using 555 IC...

    Read More
  • Basic Electronics

    Learn about Basic Electronics and various electronic components and their working...

    Read More

Sending Data to Two Serial Devices at the Same Time

You want to send data to a serial device such as a serial LCD, but you are already using
the built-in serial port to communicate with your computer.

On a Mega this is not a problem, as it has four hardware serial ports; just create two
serial objects and use one for the LCD and one for the computer:

void setup() {
// initialize two serial ports on a Mega
Serial.begin(9600); // primary serial port
Serial1.begin(9600); // Mega can also use Serial1 through Serial3
}

On a standard Arduino board (such as the Uno or Duemilanove) that only has one
hardware serial port, you will need to create an emulated or “soft” serial port.
You can use the distributed SoftwareSerial library for sending data to multiple devices.


Select two available digital pins, one each for transmit and receive, and connect your
serial device to them. It is convenient to use the hardware serial port for communication
with the computer because this has a USB adapter on the board. Connect the device’s
transmit line to the receive pin and the receive line to the transmit pin.Connecting a serial device to a “soft” serial port
In your sketch, create a Software Serial object and tell it which pins you chose as your
emulated serial port.
 In this example, we’re creating an object named  serial_lcd, which
we instruct to use pins 2 and 3:
/*
* SoftwareSerialOutput sketch
* Output data to a software serial port
*/
#include <SoftwareSerial.h>
const int rxpin = 2; // pin used to receive (not used in this version)
const int txpin = 3; // pin used to send to LCD
SoftwareSerial serial_lcd(rxpin, txpin); // new serial port on pins 2 and 3
void setup()
{
Serial.begin(9600); // 9600 baud for the built-in serial port
serial_lcd.begin(9600); //initialize the software serial port also for 9600
}
int number = 0;
void loop()
{
serial_lcd.print("The number is "); // send text to the LCD
serial_lcd.println(number); // print the number on the LCD
Serial.print("The number is ");
Serial.println(number); // print the number on the PC console
delay(500); // delay half second between numbers
number++; // to the next number
}
If you are using Arduino versions prior to 1.0, download the NewSoftSerial  library  and  replace  references  to  SoftwareSerial  with  NewSoftSerial:
// NewSoftSerial version
#include <NewSoftSerial.h>
const int rxpin = 2; // pin used to receive from LCD
const int txpin = 3; // pin used to send to LCD
NewSoftSerial serial_lcd(rxpin, txpin); // new serial port on pins 2 + 3
This sketch assumes that a serial LCD has been connected to pin 3 as shown in Figure 4-6, and that a serial console is connected to the built-in port. The loop will repeatedly display the same message on each:
The number is 0
The number is 1

Receiving Serial Data in Arduino

You want to receive data on Arduino from a computer or another serial device; for
example, to have Arduino react to commands or data sent from your computer.


It’s easy to receive 8-bit values (chars and bytes), because the Serialfunctions use 8-bit values. This sketch receives a digit (single characters 0 through 9) and blinks the
LED on pin 13 at a rate proportional to the received digit value:

/*
* SerialReceive sketch
* Blink the LED at a rate proportional to the received digit value
*/
const int ledPin = 13; // pin the LED is connected to
int blinkRate=0; // blink rate stored in this variable
void setup()
{
Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud
pinMode(ledPin, OUTPUT); // set this pin as output
}
void loop()
{
if ( Serial.available()) // Check to see if at least one character is available
{
char ch = Serial.read();
if( isDigit(ch) ) // is this an ascii digit between 0 and 9?
{
blinkRate = (ch - '0'); // ASCII value converted to numeric value
blinkRate = blinkRate * 100; // actual rate is 100ms times received digit
}
}
blink();
}
// blink the LED with the on and off times determined by blinkRate
void blink()
{
digitalWrite(ledPin,HIGH);
delay(blinkRate); // delay depends on blinkrate value
digitalWrite(ledPin,LOW);
delay(blinkRate);
}
Upload  the sketch and send messages using the Serial Monitor. Open the Serial Monitor
by clicking the Monitor icon and type a digit in the text box at the top
of the Serial Monitor window. Clicking the Send button will send the character typed
into the text box; if you type a digit, you should see the blink rate change


Drakness Detector using 741 opamp IC

The circuit below is darkness detector that is it automatically turns on the LED when LDR senses no light.
LDR is the light dependent resistor when exposed to darkness, a LDR has a tremendous amount of resistance. Depending on the specific LDR in use, its resistance can be anywhere from over 100KΩ to well over 2MΩ. When exposed to bright light, a LDR's resistance drops drastically. Again, based on the LDR, it may be to 5KΩ or below or to about 30KΩ. For any LDR, you can pretty much be sure that the resistance will fall to about 30KΩ when exposed to bright light.


COMPONENTS REQUIRED :

1.one LM741 IC
2.one LDR
3.Two 100k resistances
4.one 180ohm resistance
5.one 4.7k resistance
6.one LED
7.one 9-12v Battery



what are Infrared LEDs ?

Infrared LEDs are just like ordinary LEDs but the light output cannot be seen. To view an infrared LEDs, turn it on with the appropriate battery and dropper resistor and view it with a camera. You will see the illumination on the screen.

Infrared LEDs are sometimes clear and sometimes black. They operate just like a red LED with the same characteristic voltage-drop of about 1.7v.

Sometimes an infrared LED is pulsed with a high current for a very short period of time but the thing to remember is the wattage-dissipation of a 5mm LED is about 70mW. This means the constant-current should be no more than 40mA.

 Infrared LEDs are also called TRANSMITTING LEDs as they emit light. These are given the term Tx (for transmitting). An infrared LED can be connected to a 5v supply via a 220R current-limiting resistor for 15mA current.
 Infrared receivers (Rx) can look exactly like infrared LEDs, but they do not emit IR light. They detect Infrared illumination and must be connected the correct way in a circuit.
They have a very high resistance when no receiving IR illumination and the resistance decreases as the illumination increases.
This means they are connected to a 5v supply via a resistor and when the resistance of the infrared receiver decreases, current will flow thought it and the resistor. This will produce a voltage across the resistor and this voltage is fed to the rest of the circuit.

Here is a circuit to show how to connect an infrared LED and Infrared (diode) receiver:


You cannot use an IR LED as a receiver or an Infrared diode as an illuminator. They are constructed differently. An infrared LED has a characteristic voltage drop of 1.7v An Infrared receiver does not have a characteristic voltage-drop. It has a high resistance when not illuminated and a low resistance when it receives illumination.
 

Laser Ray Effect using 555

This circuit produces a weird "Laser Ray" sound and flashes a  LED at approx 5Hz.

 COMPONENTS USED:

1.one 555 IC
2.one 100nF Ceramic Capacitor
3.one 10uF Electrolytic Capacitor
4.one 220K resistance
5.one 470ohm resistance
6.one LED
7.one 8ohm Speaker
8.one 6-12v supply



Delayed Start Circuit using 555 IC

This circuit does not turn on for XX seconds after power is applied. Adjustable from 1 second to 2 minutes.The delay can be adjusted by changing the resistance between pin 6 and ground.
Either you can use a 1M Variable Resistor or use different resistances to get different delays in turning on the circuit. Just Connect a LED to pin 3 of 555 along with a resistor to delay the start of LED.

Resistances Between pin 6 and Ground and their Respective Delays :

1K-     1s
100k-  10s
220k-  25s
250k-  27s
500k-  56s
1M-   2min


COMPONENTS USED :

1.one 555 IC.
2.one 100uF Electrolytic Capacitor.
3.one 1M Variable resistor or different Resistances (1K,100K,250K etc)
4.one LED.
5.one 470ohm/220ohm resistance.
6.one 9-12V Power Supply.




Toggle LED on off using 555

This circuit will toggle the output each time the switch is pressed. The action cannot be repeated until the 10u charges or discharges via the 100k. In this Project we will connect an LED to the pin 3 of 555,when the button will be pressed the LED will toggle on off.

COMPONENTS REQUIRED :

1.one 100k Resistor
2.two 10k Resistor
3.one 555 IC
4.one 10uF Electrolytic capacitor
5.one push button
6.one 470ohm/220ohm resistor
7.one LED
8.one 9-12V supply

STEPS  :

1.Place 555 IC on BreadBoard
2.Connect pin 2 to pin 6.
3.Connect pin 4 to pin 8.
4.Connect pin 1 to ground.
5.Connect pin 8 to VCC.
6.connect a 10K resistor between pin 2 and ground.
7.Connect another 10k resistor between pin 6 and VCC.
8.Connect 100K resistor between pin 3 and longer leg of Capacitor.
9.Connect shorter leg of Capacitor to ground.
10.Connect an LED to pin 3 with a 470ohm/220ohm resistor in series.
11.Connect the push button between pin 6 and positive terminal of Capacitor.
12.Connect power supply




LED Fading/Blinking using 555 IC

This circuit makes a LED fade on and off.  first charges a 100u and the transistor amplifies the current entering the 100u and delivers 100 times this value to the LED via the collector-emitter pins. The circuit needs 9v for operation since pin 2 of the 555 detects 2/3Vcc before changing the state of the output so we only have a maximum of 5.5v via a 470R/220R resistor to illuminate the LED.

 

COMPONENTS REQUIRED:

1. one 470ohm / 220ohm  resistor 
2. one 33k resistor
3. one LED ( I used Blue)
4. one 100uf Capacitor
5. one 555 Timer
6. one Generic NPN Transistor (2222A)
7. one 9-12V Supply

STEPS :

1. Place 555 Timer
2. Connect Pin 1 To Ground
3. Connect Pin 2  to Base of NPN
4. Connect 33K resistor between Pin 3 and base of NPN
5. Connect Pin 4 to Pin 8
6. Connect Pin 6  to Pin 2
7. Connect Pin 8  to Positive voltage
8. Connect Emitter of NPN to 470ohm resistor to longer leg of LED,Connect shorter leg to ground
9. Connect Base of NPN to + side of cap, then ground - side
10. Connect Collector of NPN to + voltage


Resistance b/w pin3 of 555 and base of NPN(2222A)

30K/33K - Fadein,Fade out
220ohm - Fast blink
1K - Blink
470ohm - Slow blink
100K - Faded start



(NOTE :  Below i used a combination of resistors equal to 30K  to Fade in and Fade out a LED )



Programmable LED MATRIX [ARDUINO]


This led matrix can be programmed using arduino, various patterns can be made using functions and by specifying the LED's on the array.

components-

transistors- BC547
Resistances- 470 ohm and 1K ohm
Arduino Uno
hookup wires
breadboard

Circuit Schematic-



Sketch-

int x [4] = {13,12,11,4}; //Pins of x axis in numerical order
int y [4] = {10,7,8,2}; //Pins of y axis in numerical order
void setup ()
{
 for (int a=0; a<4; a++) { //Output pins
 pinMode(x[a], OUTPUT);
 }
  for (int b=0; b<4; b++) { //Output pins
 pinMode(y[b], OUTPUT);
 }
}
void flash (int x1,int y1) { //Function to flash leds
  x1-=1; //-1 because arrays starts with 0 so the 4 is 3 and 3 is 2...
  y1-=1;
  for (int c=0; c<4;c++) {
if(c!=x_){ //This will turn off every single x led except the led you wanna flash
  digitalWrite(x[c], LOW);
}
  }
  for (int d=0; d<4;d++) {
if(d!=y_){ //This will turn off every single y led except the led you wanna flash
digitalWrite(y[d], LOW);
}
  }
  digitalWrite(x[(x1)],HIGH); 
  delay(80);
  //Flashes the x led you want to
  digitalWrite(y[(y1)],HIGH);
  delay(80);
}

void loop () {

flash(1,1);
flash(1,2);
flash(1,3);
flash(1,4);
flash(2,1);
flash(2,2);
flash(2,3);
flash(2,4);
flash(3,1);
flash(3,2);
flash(3,3);
flash(3,4);
flash(4,1);
flash(4,2);
flash(4,3);
flash(4,4);

flash(1,1);
flash(2,1);
flash(3,1);
flash(4,1);
flash(1,2);
flash(2,2);
flash(3,2);
flash(4,2);
flash(1,3);
flash(2,3);
flash(3,3);
flash(4,3);
flash(1,4);
flash(2,4);
flash(3,4);
flash(4,4);


}

Programmable LED MATRIX [ARDUINO] video DEMO
























ARDUINO: Driving DC Motors using Transistors and PWM

DC motors, which you can find in numerous devices around your home, rotate continuously when a DC voltage is applied across them. Such motors are commonly found as the driving motors in radio control (RC) cars, and as the motors that make the discs spin in your DVD player. DC motors are great because they come in a huge array of sizes and are generally very cheap. By adjusting the voltage you apply to them, you can change their rotation speed. By reversing the direction of the voltage applied to them, you can change their direction of rotation as well. This is generally done using an H-bridge,Brushed DC motors,employ stationary magnets and a spinning coil. Electricity is transferred to the coil using “brushes,” hence the reason they are called brushed DC motors. Unlike 
brushless DC motors (such as stepper motors), brushed DC motors are cheap and have easier speed control. However, brushed DC motors do not last as long because the brushes can wear out over time. These motors work through an inductive force. When current passes through the spinning coil, it generates a magnetic field that is either attracted to or repelled by the stationary magnets depending on the polarity. By using the brushes to swap the polarity each half rotation, you can generate angular momentum. The exact same configuration can be used to create a generator if you manually turn the armature. This will generate a fluctuating magnetic field that will, in turn, generate current. This is 
how hydroelectric generators work—falling water turns the shaft, and a current is produced. This capability to create current in the opposite direction is why we will use a diode to ensure that the motor cannot send current back into your circuit when it is forcibly turned.

Handling High-Current Inductive Loads

DC motors generally require more current than the Arduino’s built-in power supply can provide, and they can create harmful voltage spikes due to their inductive nature. To address this issue, you first learn how to effectively isolate a DC motor from your Arduino, and then how to power it using a secondary supply. A transistor will allow the Arduino to switch the motor on and off safely, as well
as to control the speed using the pulse-width modulation (PWM).

Before you hook up your DC motor, it’s important to understand what all
these components are doing:



■Q1 is an NPN bipolar-junction transistor (BJT) used for switching the separate 9V supply to the motor. There are two types of BJTs, NPN and PNP, which refer to the different semiconductor “doping” techniques used to create the transistor.You can simplistically think of an NPN transistor as a voltage-controlled switch that allows you to inhibit or allow current flow.
■A 1kΩ resistor is used to separate the transistor’s base pin from the control
pin of the Arduino.
■U1 is the DC motor.
■C1 is for filtering noise caused by the motor.
■D1 is a diode used to protect the power supply from reverse voltage
caused by the motor acting like an inductor.



Controlling Motor Speed with PWM

//Simple Motor Speed Control Program
const int MOTOR=9; //Motor on Digital Pin 9
void setup()
{
pinMode (MOTOR, OUTPUT);
}
void loop()
{
for (int i=0; i<256; i++)
{
analogWrite(MOTOR, i);
delay(10);
}
delay(2000);
for (int i=255; i>=0; i--)
{
analogWrite(MOTOR, i);
delay(10);
}
delay(2000);
}

Transistor Tester using 555 IC

The 555 operates at 2Hz. Output pin 3 drives the circuit with a positive then zero voltage. The other end of the circuit is connected to a voltage divider with the mid-point at approx 4.5v.

This allows the red and green LEDs to alternately flash when no transistor is connected to the tester.

If a good transistor is connected, it will produce a short across the LED pair when the voltage is in one direction and only one LED will flash.

If the transistor is open, both LED’s will flash and if the transistor is shorted, neither LED will flash.

COMPONENTS USED  :

1.one 555 IC
2.two 1N4148 diode
3.one 33K resistor
4.four 220 Ohm resistance
5.one Red LED
6.one Green LED
7.one 10uF Electrolytic Capacitor
8.one 9-12v Supply




(NOTE - In pics below i have used a series of resistances to make 33K resistance )



Integrated Circuit chips

Figure below shows what is often referred to as an integrated circuit (IC). The circuit is actually etched onto a tiny wafer or “chip” of silicon, embedded in a black plastic body, which is properly referred to as the “package.” Tiny wires inside the package link the circuit with the two rows of pins on either side.

                                    

 
   



                                                                                                                                                                                                                                                                                 
          

Figure 4-2. An integrated circuit chip in Plastic Dual-Inline Pin package, abbreviated PDIP, or, more often, DIP.The pins are mounted at intervals of 1/10 inch in two rows spaced 3/10 inch apart. This format is known as a Plastic Dual Inline Package, abbreviated PDIP, or, more often, just DIP. The chip in the photograph has four pins in each row; others may have many more. The first thing you need to know, when shopping for chips, is that you’ll only be using the DIP package. Figure 4-3 shows a size comparison between a 14-pin DIP package and a 14-pin surface-mount package. Many surface-mount chips are even smaller than the one shown.Just about every chip has a part number printed on it. In Figure 4-2, the part number is KA555. In Figure 4-3, the DIP chip’s part number is M74HC00B1, and the surface-mount chip is a 74LVC07AD. You can ignore the second line of numbers and/or letters on each chip, as they are not part of the part number.

Notice in Figure 4-3 that even though the chips look quite different from each other, they both have “74” in their part numbers. This is because both of them are members of the “7400” family of logic chips, which originally had part numbers from 7400 and upward (7400, 7401, 7402, 7403, and so on). Often they are now referred to as “74xx” chips, where “xx” includes all the members of the family.  The DIP chip, at the rear, has pins spaced 1/10 inch apart, suitable for insertion in a breadboard or perforated board. It can be soldered without special tools. The small-outline integrated circuit (SOIC) surface-mount chip 
(foreground) has solder tabs spaced at 1/20 inch. Other surface-mount chips have pins spaced at 1/40 inch or even less (these dimensions are often expressed in millimeters).

 Surface-mount chips are designed primarily for automated assembly and are difficult to work with manually. In this photo, the yellow lines are 1 inch apart to give you an idea of the scale.Take a look at Figure 4-4, which shows how to interpret a typical part number in a 74xx family member. The initial letters identify the manufacturer (which you can ignore, as it really makes no difference for our purposes).
Skip the letters until you get to the “74.” After that, you find two more letters, which are important. The 74xx family has evolved through many generations, and the letter(s) inserted after the “74” tell you which generation you’re dealing with. Some generations have included:
•  74L
•  74LS
•  74C
•  74HC
•  74AHC
And there are more.


Sound , Electricity & Sound

Time to establish a clear idea of how sound is transformed into electricity and back into sound again.

Suppose someone bangs a gong with a stick. The flat metal face of the gong vibrates in and out, creating sound waves. A sound wave is a peak of higher air pressure, followed by a trough of lower air pressure.

The wavelength of the sound is the distance (usually ranging from meters to millimeters) between one peak of pressure and the next peak.
The frequency of the sound is the number of waves per second, usually ex- pressed as hertz.

Suppose we put a very sensitive little membrane of thin plastic in the path of the pressure waves. The plastic will flutter in response to the waves, like a leaf fluttering in the wind. Suppose we attach a tiny coil of very thin wire to the back of the membrane so that it moves with the membrane, and let’s posi- tion a stationary magnet inside the coil of wire. This configuration is like a tiny, ultra-sensitive loudspeaker, except that instead of electricity producing sound, it is configured so that sound produces electricity. Sound pressure waves make the membrane move to and fro along the axis of the magnet, and the magnetic field creates a fluctuating voltage in the wire.

This is known as a moving-coil microphone. There are other ways to build a microphone, but this is the configuration that is easiest to understand. Of course, the voltage that it generates is very small, but we can amplify it using a transistor, or a series of transistors. Then we can feed the output through the coil around the neck of a loudspeaker, and the loudspeaker will recreate the pressure waves in the air.


Somewhere along the way, we may want to record the sound and then replay it. But the principle remains the same. The hard part is designing the microphone, the amplifier, and the loudspeaker so that they reproduce the waveforms accurately at each step. It’s a significant challenge, which is why accurate sound reproduction can be elusive.

Time now to think about what happens inside the wire when it generates a magnetic field. Obviously, some of the power in the wire is being transformed into magnetic force. But just what exactly is going on?














origin of LoudSpeakers

Loudspeakers utilize the fact that if you run a varying electrical current through a coil situated in a magnetic field, the coil will move in response to the current. This idea was introduced in 1874 by Ernst Siemens, a prolific German inventor. (He also built the world’s first electrically powered elevator in 1880.) Today, Siemens AG is one of the largest electronics companies in the world.

When Alexander Graham Bell patented the telephone in 1876, he used Siemen’s concept to create audible frequencies in the earpiece. From that point on, sound-reproduction devices gradually increased in quality and power, until Chester Rice and Edward Kellogg at General Electric published a paper in 1925 establishing basic principles that are still used in loudspeaker design today.

 As sound amplifiers became more powerful, speaker efficiency became less important compared with quality reproduction and low manufacturing costs. Today’s loudspeakers convert only about 1% of electrical energy into acoustical energy.


XBEE Cheatsheet


    Source: www.tunnelsup.com

Atmega AT328P pin mapping


Arduino:Reading Digital Inputs with Pulldown Resistors

All digital inputs use a pullup or pulldown resistor to set the “default state” of the input pin. Imagine the circuit in Figure below without the 10kΩ resistor. In this scenario, the pin would obviously read a high value when the button is pressed.But, what happens when the button is not being pressed? In that scenario, the input pin you would be reading is essentially connected to nothing—the input pin is said to be “floating.” And because the pin is not physically connected to 0V or 5V, reading it could cause unexpected results as electrical noise on nearby pins causes its value to fluctuate between high and low. To remedy this, the pulldown resistor is installed as shown in Figure .

Now, consider what happens when the button is not pressed with the pulldown resistor in the circuit: The input pin will be connected through a 10kΩ resistor to ground. While the resistor will restrict the flow of current, there is still enough current flow to ensure that the input pin will read a low logic value. 10kΩ is a fairly common pulldown resistor value. Larger values are said to be weak pulldowns because it easier to overcome them, and smaller resistor values are said to be strong pulldowns because it is easier for more current to flow through them to ground. When the button is pressed, the input pin is directly connected to 5V through the button. 

Now, the current has two options:
■It can flow through a nearly zero resistance path to the 5V rail.
■It can flow through a high resistance path to the ground rail

Pulldown and pullup resistors are important because they ensure that the button does not create a short circuit between 5V and ground when pressed and that the input pin is never left in a floating state.

Sketch
simple LED control using push button

const int LED=9; //The LED is connected to pin 9
const int BUTTON=2; //The Button is connected to pin 2
void setup()
{
pinMode (LED, OUTPUT); //Set the LED pin as an output
pinMode (BUTTON, INPUT); //Set button as input
}
void loop()
{
if (digitalRead(BUTTON) == LOW)
{
digitalWrite(LED, LOW);
}
else
{
digitalWrite(LED, HIGH);
}
}

Arduino: Pulse-Width Modulation with analogWrite()

we can generate analog output values by using a trick called pulse-width modulation(PWM). Select pins on each Arduino can use the analogWrite()command to generate PWM signals that can emulate a pure analog signal when used with certain peripherals. These pins are marked with a ~ on the board.On the Arduino Uno, Pins 3, 5, 6, 9, 10, and 11 are PWM pins. If you’re using an Uno, you can continue to use the circuit from Figure 2-1 to test out the analogWrite()command with your LED. Presumably, if you can decrease the voltage being dropped across the resistor, the LED should glow more dimly because less current will flow. That is what you will try to accomplish using PWM via the analogWrite()command. The analogWrite()command accepts two arguments: the pin to control and the value to write to it.The PWM output is an 8-bit value. In other words, you can write values from 0 to 28-1, or 0 to 255. Try using a similar forloop structure to the one you used previously to cycle through varying brightness values .

SKETCH:
const int LED=9; //define LED for Pin 9
void setup()
{
pinMode (LED, OUTPUT); //Set the LED pin as an output
}
void loop()
{
for (int i=0; i<256; i++)
{
analogWrite(LED, i);
delay(10);
}
for (int i=255; i>=0; i--)
{
analogWrite(LED, i);
delay(10);
}
}

What does the LED do when you run this code? You should observe the LED fading from off to on, then from on to off. Of course, because this is all in the main loop, this pattern repeats ad infinitum. Be sure to note a few differences in this forloop. In the first loop, i++is just shorthand code to represent i=i+1. Similarly, i--is functionally equivalent to i=i–1. The first for loop fades the
LED up, and the second loop fades it down.

Pulse Width Modulation

PWM control can be used in lots of circumstances to emulate pure analog control, but it cannot always be used when you actually need an analog signal. For instance, PWM is great for driving direct current (DC) motors at variable speeds, but it does not work well for driving speakers unless you supplement it with some external circuitry. Take a moment to examine how PWM actually works.


PWM works by modulating the duty cycle of a square wave (a signal that 
switches on and off). Duty cycle refers to the percentage of time that a square 
wave is high versus low. You are probably most familiar with square waves that 
have a duty cycle of 50%—they are high half of the time, and low half of the time.

The analogWrite()command sets the duty cycle of a square wave depending
on the value you pass to it:

■Writing a value of 0 with analogWrite()indicates a square wave with a
duty cycle of 0 percent (always low).
■Writing a 255 indicates a square wave with a duty cycle of 100 percent
(always high).
■Writing a 127 indicates a square wave with a duty cycle of 50 percent
(high half of the time, low half of the time).

The graphs in Figure show that for a signal with a duty cycle of 25 percent, it is high 25 percent of the time, and low 75 percent of the time. The frequency of this square wave, in the case of the Arduino, is about 490Hz. In other words, the signal varies between high (5V) and low (0V) about 490 times every second.So, if you are not actually changing the voltage being delivered to an LED, why do you see it get dimmer as you lower the duty cycle? It is really a result of your eyes playing a trick on you! If the LED is switching on and off every 1ms (which is the case with a duty cycle of 50 percent), it appears to be operating at approximately half brightness because it is blinking faster than your eyes can perceive. Therefore, your brain actually averages out the signal and tricks you into believing that the LED is operating at half brightness.