Page 107 - Programming the Photon Getting Started With the Internet of Things
P. 107
void loop() {
int val = analogRead(POT);
int ledval = map(val, 0, 4095, 0, 255);
analogWrite(led, ledval);
delay(200);
}
We can take a look at the code in the following stages to understand better what it is
doing:
Create an integer called val and assign it a value of 0.
Scale the analog read value, which runs from 0 to 4095, to the analog output value,
which ranges from 0 to 255.
Write the potentiometer value to the LED.
Pause for a few milliseconds and repeat the process.
analogRead
Just like the function digitalRead, which returned a value of either HIGH or LOW,
analogRead returns a value as well. In contrast to HIGH or LOW, analogRead returns an
integer value from 0 to 4095. That value represents a voltage from 0 to 3V3.
The return value can be stored in a variable for use later on in our code, or it can be
used right away using an if statement such as:
if (analogRead(POT) > 2000 {
analogWrite(led, 129);
}
In our sketch the analogRead value is stored in a variable called val.
The syntax for analogRead() is
analogRead(pin);
The parameter is
Pin, the analog pin that the sensor is connected to on the Photon.
analogRead() returns an integer value between 0 and 4095, which represents ground
and 3V3.