Välj en sida

A blinking LED is perhaps not the most exciting thing in the world, but if you can get it to pulsate instead it would be a little more interesting. Build the circuit from project 001, but use the code below instead. Here we use a for-loop to gradually increase the intensity of the LED and when we’ve reached the maximum we use a new loop to lower the intensity again.

### Analogue values in a digital world.

Earlier we used `digitalWrite()` to activate the LED, but with that function we can only set anoutput to either 0 volts or the full voltage of the power supply, i.e. 5 volts. In order to set the light intensity instead we use `analogWrite()` which makes it possible to set an output to what appears to be any voltage between 0 and 5 volts in 256 steps. It is however important to note that the an Arduino board really can’t give out anything other than digital signals, i.e. 0 or 5 volts, but by switching very fast between 0 and 5 volts it looks as if the voltage is somewhere in between. This is called PWM – Pulse Width Modulation. For this project with our LEDit doesn’t matter that the output pulses because the switching is too fast for our eyes to see and the same is true if we want to control a motor – the pulses are too fast for the motor to vibrate and it will instead just run at a speed proportional to the pulses. There are however times when this won’t work so it is important to verify that whatever you connect to your Arduino board can actually handle PWM-signals or if it requires a genuine analogue signal. To create proper analogue signals a special circuit or module is required which logically is called a Digital to Analog Converter or DAC for short.

### The code

```void setup() {
// Set pin 2 to be an output.
pinMode(2, OUTPUT);
}

void loop() {
// Increase the intensity of the LED from completely off to fully lit.
for (int i = 0; i < 255; i++) {
// Set the intensity of the LED.
analogWrite(2, i);
// Wait 10ms.
delay(10);
}
// Decrease the intensity of the LED from fully lit to completely off.
for (int i = 255; i > 0; i--) {
// Set the intensity of the LED.
analogWrite(2, i);
// Wait 10ms.
delay(10);
}
}
```