Controlling the lamp brightness

We are going now to teach you how to control the lamp’s brightness and for that purpose we are going to use the analogWrite() function.

!Important Information

Analog outputs are common and largely used to drive devices. Unlike digital outputs, which have only two possible values, analog outputs have a great variety of possible values.

The analogWrite() function allows us to pass values that vary from 0 to 255. In our example, 0 means that the lamp is off and 255 indicates that the lamp’s brightness is at its maximum.

!Identifying the Components

Lamp

!Code Components

Another output, a world of possibilities…

Analog Output: analogWrite([pin], [0-255])

The analogWrite() function has its format similar to digitalWrite(). As the first parameter, we say which pin we will use. On the second parameter, instead of a binary option of values, such as HIGH or LOW, we can choose any value from 0 to 255.

The 0 output has no intensity, while 255 has the maximum intensity and 128 will give you a median intensity and so on.

Attention! Not all Arduino pins have this resource, but only the pins which have the “#” signal (D3, D5, D6, D9, D10, D11). Therefore the analogWrite() function can only be used with one of those.

!Running on Arduino

Run the code below on you Arduino. With it you can change the brightness of the lamp to pre-defined values.

int lamp = 3;

void setup()
{
  pinMode(lamp, OUTPUT);
}

void loop() 
{ 
  analogWrite(lamp, 5);
  delay(500);
  analogWrite(lamp, 55);
  delay(500);
  analogWrite(lamp, 105);
  delay(500);
  analogWrite(lamp, 155);
  delay(500);
  analogWrite(lamp, 205);
  delay(500);
  analogWrite(lamp, 255);
  delay(500);
}

!Your Turn!

Try modifying the code so that the lamp turns on with gradual brightness. The goal is that the lamp starts turned off and then its brightness starts going up until the maximum value and then turns off (use the for() command).

Answer

int lamp = 3;
int min_value = 0;
int max_value = 255;

void setup()
{
  pinMode(lamp, OUTPUT);
}


void loop() 
{
  for (int i = min_value; i <= max_value; i ++)
  {
    analogWrite(lamp, i);
    delay(10);
  }
}