# Analog Out

### Analog Signals

In electronics, there are two types of signals: digital and analog.

A digital signal only has two states: on or off.

An analog signal can have multiple states within a range (from 0 to 1023).

Did you know that the range 0~1023 is the digital representation of an analog signal? It represents a 10-bit (2^10) resolution signal. 2^10 = 1024 values!

In this tutorial, we are going to learn how to control analog signals.

### Electronics

For this tutorial, we are going to use the expansion pack, the LED module and 3 cables.

Let’s do the following steps:

1. Grab 1 cable and connect the S pin of the LED module to the S0 pin of the expansion pack. Make sure that the cable is connected to the S0 position.
2. Next, grab another cable and connect the + pin of the LED module to the V1 pin of the expansion pack. This can be connected on any pin as long as it is a red pin of V1.
3. Finally, grab the last cable and connect the - pin of the LED module to the G pin of the expansion pack. This can be connected on any pin as long as it is a black pin of G.

You should have something like the picture below:

### Software

Start a New Project and let’s call it “AnalogOut”.

To control analog signals, we are going to use the code block analog write pin [P0▼] to (1023) from the Advanced > Pins blocks.

By default, this block is set to 1023, which means “fully on”. If you change this number to 0, it means “fully off”. Any value in between will change the brightness of the LED.

Let’s make a simple dimming LED animation that goes from “fully off” to 25%, 50%, 75% brightness, and “fully on”, with a 500ms pause between states.

If you followed the Buttons and Timings tutorial, you should be able to code this part by yourself! :)

#### Hint!

Before we can code the analog value, first we need to calculate their values. We know that “fully off” (or 0%) is 0 and “fully on” (or 100%) is 1023. What about the other numbers?

We can use the Rule of Three (a.k.a. Cross-multiplication) to calculate their values.

If 100% is to 1023, then 25% is to x. Then, we can solve for x:

$$x_{25} = \frac{1023}{100}*25 = 255.75 \approx 255$$

We do the same for 50% and 75%.

$$x_{50} = \frac{1023}{100}*50 = 511.5 \approx 511$$ $$x_{75} = \frac{1023}{100}*75 = 767.25 \approx 767$$

Finally, you should have something like this inside the forever block:

The simulation should show something like this. Notice how pin 0 changes color gradually. That means different voltages are flowing through the pin.

Try to make a program that turns on the LED when you press button A and turns off the LED when you press button B. However, if you press A + B, the LED changes to 50% brightness.