Sub topic 3
Scaling readings with map()
This chapter assumes you can upload a sketch, open the Serial Monitor, wire a breadboard, and use pinMode() and digitalWrite(). You should also know that analogRead() returns 0 to 1023 on a 10-bit board.
Scaling readings with map()
map() converts a value from one range to another. The arguments are the value, the input low and high, and the output low and high. Because analogRead() returns 0 to 1023 and analogWrite() accepts 0 to 255, you usually need map() to connect them.
Dimming an LED with the potentiometer
An LED on a PWM pin (marked with ~ on an Uno, such as pin 9) can be dimmed with analogWrite(). PWM switches the pin on and off quickly, and the duty cycle sets the apparent brightness.
const int POT_PIN = A0;
const int LED_PIN = 9;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
int raw = analogRead(POT_PIN);
int brightness = map(raw, 0, 1023, 0, 255);
analogWrite(LED_PIN, brightness);
}Why readings jitter and how to average them
Electrical noise and the ADC itself cause the raw value to shift by a few counts even when the knob is still. Averaging several samples smooths this out.
const int POT_PIN = A0;
const int NUM_SAMPLES = 10;
int readAveraged() {
long sum = 0;
for (int i = 0; i < NUM_SAMPLES; i++) {
sum += analogRead(POT_PIN);
delay(2);
}
return sum / NUM_SAMPLES;
}Ignoring small changes with a deadband
A deadband is a threshold. The sketch reports a new value only when it moves at least that far from the last reported value.
const int POT_PIN = A0;
const int THRESHOLD = 4;
int lastReported = -1;
void setup() {
Serial.begin(9600);
}
void loop() {
int value = analogRead(POT_PIN);
if (lastReported < 0 || abs(value - lastReported) >= THRESHOLD) {
lastReported = value;
Serial.println(value);
}
delay(20);
}Resolution and voltage on other boards
An Uno uses a 10-bit ADC with a 5 V reference, so each step is about 4.9 mV. A 3.3 V board has a smaller reference, and some boards offer 12-bit reads through analogReadResolution(12). Check your board's documentation before you assume the 0 to 1023 range.
> Since the code above assumes 10 bits, change the map() upper limit if you change the resolution.
Exercise
Exercise
If a 12-bit ADC reads 4095 at full scale, what map() call scales that reading to 0 to 255?
Show answer
map(raw, 0, 4095, 0, 255)