Analog input

The goal

We want to get the value of an analog signal

This time we don't need to init the pin

By default, all pins are set as INPUT

N.B. only specific pins can be used,
these are the pins
marked with an "A" (A0, A1, ...)

Read the analog value

With the function analogRead

analogRead(pin)

Reads the value from the specified
analog pin.[...]
it will map input voltages between 0
and the operating voltage(5V or 3.3V) into
integer values between 0 and 1023.
int v = analogRead(A1);

Let's introduce an useful math function

map(value, fromLow, fromHigh, toLow, toHigh)
Re-maps a number from one range to
another. That is, a value of fromLow
would get mapped to toLow,
a value of fromHigh to toHigh,
values in-between to values in-between
int x = map(512, 0, 1023, 0, 255);  //128

The task

We want to control the LED
brightness with a potentiometer

What's a potentiometer?

It's essentially a resistor(R)
divided in two parts (R1 & R2)
of which we can change
the size with a knob

If we apply a voltage to the two external
pins (1 & 2) of a potentiometer we'll find
on the middle pin(3) a voltage that
varies with the position of the knob

The circuit

The sketch

int v, x;

void setup() {
	pinMode(9, OUTPUT);	// initializes LED pin as output
}

void loop() {
	v = analogRead(A1);				// reads the analog value
	x = map(v, 0, 1023, 0, 255);	// rescales value to PWM range
	analogWrite(9, x);				// writes the output as PWM
	delay(100);						// waits a moment
}

What (is supposed to) happen?

Turning the potentiometer
changes the LED brightness