Français

Lessons · Lesson K3 · Code basics · 25 min

Analog values and thresholds

Read a changing voltage with analogRead(), turn it into a decision with a threshold, then stop the stutter with two thresholds. About 25 minutes, with a live graph you can drag.

From yes / no to “how much”

In lesson S1 the sensor gave two answers: the beam is clear, or it is broken. Many sensors do better than that. A light sensor, for example, produces a voltage that slides smoothly between “dark” and “bright”. A digital pin cannot describe that: it only knows high and low.

The part that can is the ADC, the analog-to-digital converter. It measures a voltage and hands your code a number [1]. The ESP32 has two of them, each with 12 bits, wired to 18 input pins [3].

The ruler. Picture a ruler with 4096 marks. Hold a voltage against it and read the closest mark. That number is what analogRead() gives you. Twelve bits make 2 to the power of 12 = 4096 levels, numbered 0 to 4095 [2]. (A classic Arduino board has a 10-bit converter, so it counts 0 to 1023 instead [6].)

Where the picture stops. A ruler measures length in a straight, even way. The ESP32 ruler has its own quirks, mostly near its two ends, and we will meet them on screen 4.

In this lesson the number comes from a light sensor, and it will drive the LED and the buzzer from K2. Then we make the decision robust.


The sensor: a light-controlled divider

An LDR (light-dependent resistor) changes its resistance with the light on it. Put it in series with a fixed resistor and read the voltage at the point where they meet. As the light grows, the LDR’s resistance falls, and the voltage across the fixed resistor rises [4]. Lesson E5 explains this voltage divider in detail. Here we use it as a recipe, and the voltage U on the pin rises with the light:

  • 3V3 to one leg of the LDR.
  • The other leg of the LDR to GPIO 34, and from that same point a 10 kΩ resistor to GND.

Adafruit shows this arrangement with a 5 V supply and notes that 3.3 V works just as easily [4]. More light, higher voltage, higher number.

Choosing the pin. The ESP32’s analog inputs are split between two converters, ADC1 and ADC2. GPIO 34 belongs to ADC1 (channel 6) and is input only [3][5]. GPIO 32 to 39 are on ADC1, while GPIO 25, 26 and 27 (our buzzer, LED and button) are on ADC2 [3]. We only use those three as plain digital pins here. But ADC2 pins cannot be used while Wi-Fi is on [5], so we keep analog sensors on ADC1 pins, and Wi-Fi cannot get in the way later.

Add the LED on GPIO 26 and the active buzzer on GPIO 25 as in K2. Those parts stay the same.

The LDR voltage divider, bright and dark IEC schematic, two states side by side. In each, 3V3 at the top feeds the LDR, a light-dependent resistor, down to a junction; the junction is wired to GPIO 34, and a 10 kilohm resistor goes from the junction down to GND. Left, bright: light falls on the LDR, its resistance is small, the junction voltage is high and analogRead(34) gives a high number. Right, dark: little light, the LDR's resistance is large, the junction voltage is low and the reading is low. More light, higher voltage, higher number. FIG. 1 — LDR DIVIDER (IEC)aBright3V3lamp or daylightLDRsmall resistance10 kΩGPIO 34V highjunctionanalogRead(34)04095high numberbDark3V3hand over itLDRlarge resistance10 kΩGPIO 34V lowjunctionanalogRead(34)04095low numberMore light → smaller LDR resistance → higher voltage → higher number.Bars are a picture of the idea, not a measurement: read your own numbers in the Serial Monitor.
Tap the diagram to open it full screen.
K3 wiring: LDR divider on 34, LED on 26, buzzer on 25 Breadboard seen from above, DevKitC across the centre gap, USB on the left, column j free. Nine numbered wires. 1 black: GND pin to the top minus rail. 2 red: 3V3 pin to the top plus rail. 3 red: plus rail to row 20, where one leg of the LDR sits (h20); its other leg is in h22, the junction row. 4 yellow: GPIO 34 to row 22. The 10 kilohm resistor bridges i22 and i26; 5 black: row 26 to the minus rail. 6 orange: GPIO 25 to row 29, the active buzzer's plus leg; its other leg is in row 32; 7 black: row 32 to the minus rail. 8 green: GPIO 26 to row 35; the 220 ohm resistor bridges rows 35 and 39; the LED's long leg is in row 39, its short leg in row 40; 9 black: row 40 to the minus rail. FIG. 2 — WIRING, BREADBOARD VIEW+−−+jihgfedcba1510152022262932353944ENBOOT5VCMDD3D213GND121427262533323534VNVPEN3V3++468157923LDR10 kΩactive buzzer220 ΩLEDrow 22 = junction1black: GND pin → top − rail2red: 3V3 pin → top + rail3red: + rail → LDR leg (row 20)4yellow: GPIO 34 → junction (row 22)5black: 10 kΩ (row 26) → − rail6orange: GPIO 25 → buzzer + (row 29)7black: buzzer − (row 32) → − rail8green: GPIO 26 → 220 Ω (row 35)9black: LED − (row 40) → − railGPIO 34 is an ADC1 pin, input only. The LED and buzzer parts are the same as in K2, moved along.Hand over the LDR gives a low number? Good. The other way round: swap the LDR and the 10 kΩ.
Tap the diagram to open it full screen.

Read the number

Upload this first sketch and open the Serial Monitor at 115200 baud:

// Tinker Mission, lesson K3: read an analog value (LDR divider on GPIO 34) and average it
// Wiring (a voltage divider, see lesson E5):
//   3V3 -> LDR -> GPIO 34 -> 10 kohm resistor -> GND
//   (the LDR and the resistor meet at the wire that goes to GPIO 34)
// Open the Serial Monitor at 115200 baud. Cover the LDR with your hand, then shine a light on it.

const int LDR_PIN = 34;   // an ADC1 pin, input only

// Average several readings to smooth out small jumps.
int readAveraged(int howMany) {
  long total = 0;
  for (int i = 0; i < howMany; i++) {
    total = total + analogRead(LDR_PIN);
    delay(2);
  }
  return total / howMany;
}

void setup() {
  Serial.begin(115200);
  analogReadResolution(12);                  // 12 bits: values from 0 to 4095 (this is already the default)
  analogSetPinAttenuation(LDR_PIN, ADC_11db); // widest input range (keep readings away from both ends of the scale)
}

void loop() {
  int single = analogRead(LDR_PIN);   // one raw reading, 0 to 4095
  int smooth = readAveraged(16);      // average of 16 readings
  Serial.print("single: ");
  Serial.print(single);
  Serial.print("   averaged: ");
  Serial.println(smooth);
  delay(200);
}

Download the sketch folder (.zip)

Cover the LDR with your hand, then shine a lamp or a phone torch on it, and watch both columns.

What the new lines do:

  • analogRead(34) returns the raw reading of the pin, a whole number [1].
  • analogReadResolution(12) sets the size of the ruler. 12 bits is already the default, and the line is there to make the idea visible [1].
  • analogSetPinAttenuation(...) sets the attenuation: a built-in shrinker that lets the converter measure higher voltages. The higher the attenuation, the higher the voltage you can measure [1]. We set it ourselves, so the lesson does not depend on a default.
  • readAveraged(16) is our own function. Its for loop repeats the lines inside it 16 times: it adds up 16 readings, then divides the total by 16. The decimals are dropped, because the result is stored in a whole-number int.

If you would rather see millivolts than raw steps, analogReadMilliVolts() returns a calibrated value in millivolts [1]. We stay with raw numbers here, because thresholds work fine on them.

Wiring check. Hand over the LDR gives a low number, lamp on it gives a high one. If it is the other way round, the LDR and the resistor are swapped. With a 10 kΩ resistor, a very bright LDR (around 1 kΩ, typical, depends on the part) puts about 3.0 V on the pin, just under the 3100 mV top of the 11 dB range, so the reading lands near the top of the scale, and a brighter light can push it to 4095 [1][4]. Deep darkness gives a voltage close to 0, so it reads near 0. Seeing 4095 under a lamp, or 0 in the dark, is normal: the voltage is off one end of the ruler. Your thresholds only need to sit in the middle. In a bright room, use a smaller fixed resistor (for example 1 kΩ) so the reading stays out of the unreliable top zone [4]. Adafruit notes that a 10 kΩ resistor saturates in bright light and suggests a smaller one, at the cost of less detail in the dark [4].


The ends of the ruler

The ruler is not perfect. Espressif’s documents say so, and the details matter:

Usable range. Attenuation sets the range of voltages the converter can measure, and the ends of that range are not reliable. For the largest setting, the Arduino documentation lists 150 mV to 3100 mV [1], while the datasheet gives an effective range of 150 mV to 2450 mV and says that accuracy gets worse above a reading of about 3000, roughly 2450 mV [3]. Different Espressif pages use different names for the steps (11 dB, 12 dB, “atten = 3”) [1][2][3], and their numbers differ. When sources disagree, take the cautious one: keep the readings you rely on away from both ends of the scale.

Steps that are not equal. The datasheet quotes a differential non-linearity of up to ±7 LSB and an integral non-linearity of up to ±12 LSB [3]. An LSB is one step of the 4096. In plain words: the steps of the ruler are not all the same size, and the whole ruler leans a little. Twelve steps out of 4096 is about 0.3 %, small for a threshold. Those figures were measured in good conditions: a 100 nF capacitor on the input, a steady voltage, and Wi-Fi and Bluetooth off [3].

Chip to chip. By default, measured results differ by ±6 % from one chip to another, and ESP-IDF offers calibration methods to do better [3]. So your 1500 is not your friend’s 1500. Never copy a threshold from a tutorial. Measure your own.

Noise. The datasheet itself suggests taking several samples with a filter, or averaging them, to get smoother, more even steps (better DNL) [3]. We do that on screen 7.

The ESP32 ruler: 0 to 4095 A horizontal scale from 0 to 4095, the 4096 steps of the 12-bit converter. Both ends are hatched as less reliable: the very low readings on the left, and readings above about 3000 on the right. The middle band is marked work here. Below, a magnified view of a few steps: the ideal staircase, dashed, has equal steps; the real one, drawn solid, has steps of slightly different sizes, exaggerated here. Notes: the whole ruler leans by about 12 steps out of 4096, about 0.3 percent, small for a threshold; readings differ by about 6 percent from one chip to another, so measure your own threshold. FIG. 3 — THE ESP32 RULER01024204830724095very low readings:less reliableabove ≈ 3000:less reliablework hereOne step = 1 LSB = 1/4096 of the range.Magnified: 7 stepsvoltage in →reading ↑idealrealunequal steps (exaggerated)The ruler leans a little:≈ 12 LSB of 4096 ≈ 0.3 %.Small for a threshold.Chip to chip: about ±6 %.Your 1500 is notyour friend's 1500.Measure your own threshold.
Tap the diagram to open it full screen.

Choosing a threshold

A threshold is a number your code compares the reading with, to turn “how much” back into yes or no:

if (value < 1500) {
  // dark: switch the alarm on
}

Choosing it takes three steps:

  1. Measure the normal situation. Leave the room as it usually is, and note the values the Serial Monitor shows, from lowest to highest.
  2. Measure the event. Cover the LDR, or do whatever you want to detect, and note those values too.
  3. Pick a number between the two groups, with room on both sides. The middle is a good first guess, then test it at both extremes and in between.

Example (invented numbers, not a measurement): room light reads 2300 to 2500, a hand over the LDR reads 500 to 700. The two groups are far apart, so a threshold near 1500 leaves lots of room.

The easy case is when the groups are far apart. Real situations are messier, as the next screen shows.


The stutter

Now imagine dusk. The light slides slowly down, and the reading drifts toward your threshold, say 1500. Near the line, tiny wobbles are enough to cross it: 1502, 1498, 1503, 1497. The code sees dark, light, dark, light. The LED stutters and the buzzer rattles, though nothing real changed.

The cause is not a bug. Any reading carries a bit of noise, and any single threshold is a line that noise can cross back and forth. Try it in the graph below: drag the line, turn the noise up, and count how often the alarm toggles. Then switch on the second line.

Live graph with a draggable threshold (interactive)
Live graph with a draggable threshold (interactive) Interactive simulation of a light sensor, not a real one: a slow slope, like dusk falling and the light coming back, plus adjustable noise. The graph scrolls and shows analogRead values from 0 to 4095. Drag the horizontal threshold line, or focus it and use the arrow keys. The alarm is on while the value is below the threshold; a strip under the graph shows when the alarm was on, and a counter shows how many times it switched since the last change of settings. Near the line, noise makes the alarm flicker. Fixes: the Average buttons take 1, 4 or 16 readings and calm the noise; Two thresholds adds LOW_LIMIT and HIGH_LIMIT with a margin band between them: the alarm turns on below LOW_LIMIT and off only above HIGH_LIMIT, and the counter stops climbing. FIG. W — THRESHOLDS, LIVESimulation: a fake light sensor, not a real one.above ≈ 3000: less reliable01024204830724095analogRead(34)time →1400alarmONOFFQuietvalue: 2400threshold 1400Switches since last change: 0Stable: no flicker in the last 5 s.

Swipe the drawing sideways to see all of it.


Fix 1: average

The first remedy is to calm the reading. Instead of trusting one reading, take several in a row and use their average [3]. A random wobble that goes up on one reading goes down on the next, and the average smooths it. That is what readAveraged(16) does, and it costs about 32 ms of waiting (16 readings, 2 ms apart), which you will not notice.

Two limits:

  • A bigger average reacts more slowly. Sixteen is a reasonable start.
  • Averaging cannot stop the stutter when the true value rests right on the line. A smooth 1500 against a threshold of 1500 is still a coin toss.

So we add a second idea.


Fix 2: two thresholds

Think of a thermostat. The heating does not switch on at 20 degrees and off at 20 degrees: it would click all night. Instead it switches on when the room falls below, say, 19, and off only once it is above 21. Between the two, it keeps doing what it was doing.

That is hysteresis: different switching thresholds depending on the direction the signal is moving [7]. An electronic part that does this is called a Schmitt trigger [7]. In code you do not need a part, just a memory (alarmOn) and two numbers:

  • the alarm turns on when the value falls below LOW_LIMIT,
  • the alarm turns off only when the value rises above HIGH_LIMIT,
  • in between, nothing changes. A toggle switch behaves like this: it stays where you left it [8].

The gap between the two numbers is the margin. Choose it bigger than the wobble you see when holding still (look at the lowest and highest numbers in the Serial Monitor), and smaller than the gap between your two situations.

Where the picture stops. A thermostat has a slow room behind it. Our code reacts as fast as it reads, so the margin is our main protection.

The whole sketch:

// Tinker Mission, lesson K3: a light alarm with two thresholds (hysteresis)
// Wiring:
//   LDR divider: 3V3 -> LDR -> GPIO 34 -> 10 kohm resistor -> GND
//   LED: GPIO 26 -> 220 ohm -> LED long leg; LED short leg -> GND
//   Active buzzer: + leg to GPIO 25, other leg to GND (3-pin module: VCC to 3V3, GND to GND, I/O to GPIO 25)
// The alarm turns ON when the reading falls below LOW_LIMIT (it got dark),
// and turns OFF again only when the reading rises above HIGH_LIMIT.
// Between the two limits nothing changes. Replace the numbers with your own measurements.

const int LDR_PIN = 34;
const int LED_PIN = 26;
const int BUZZER_PIN = 25;

const int LOW_LIMIT = 1200;    // alarm ON below this
const int HIGH_LIMIT = 1600;   // alarm OFF above this (the gap between the two limits is the margin)

int alarmOn = 0;   // 0 = quiet, 1 = alarm

int readAveraged(int howMany) {
  long total = 0;
  for (int i = 0; i < howMany; i++) {
    total = total + analogRead(LDR_PIN);
    delay(2);
  }
  return total / howMany;
}

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  analogSetPinAttenuation(LDR_PIN, ADC_11db);
}

void loop() {
  int value = readAveraged(16);

  if (alarmOn == 0) {
    if (value < LOW_LIMIT) {
      alarmOn = 1;       // it just got dark
    }
  } else {
    if (value > HIGH_LIMIT) {
      alarmOn = 0;       // it is clearly bright again
    }
  }

  if (alarmOn == 1) {
    digitalWrite(LED_PIN, HIGH);
    digitalWrite(BUZZER_PIN, HIGH);
  } else {
    digitalWrite(LED_PIN, LOW);
    digitalWrite(BUZZER_PIN, LOW);
  }

  Serial.print("value: ");
  Serial.print(value);
  Serial.print("   alarm: ");
  Serial.println(alarmOn);
  delay(100);
}

Download the sketch folder (.zip)

alarmOn is a variable that remembers the state: 0 for quiet, 1 for alarm. The two nested if blocks are the whole trick. Which one runs depends on what alarmOn says. The symbols < and > mean “smaller than” and “greater than”.

Troubleshooting.

  • The alarm never switches on: your LOW_LIMIT is below the darkest reading you get. Raise it, after checking your own numbers.
  • The alarm switches on but never off: HIGH_LIMIT is above the brightest reading. Lower it.
  • It still stutters: widen the margin, or keep the LDR away from flickering light and moving shadows.

Try your own changes

Change one thing, upload, observe.

  1. No margin. Set HIGH_LIMIT equal to LOW_LIMIT. Does the stutter come back at dusk?
  2. Fewer readings. Change readAveraged(16) to readAveraged(1). What changes in the Serial Monitor?
  3. Reverse it. Make the alarm sound when the room gets brighter, as a “light switched on” alarm. Which parts of the sketch swap?

Check yourself

Three short questions. Nothing is saved, take your time.

  1. By default, what range of values does analogRead() return on an ESP32?

    • 0 to 1023
    • 0 to 4095
    • 0 to 255
    Show the answer

    0 to 4095. The ESP32 reads with 12 bits by default, which makes 4096 levels, numbered 0 to 4095 [1][2]. The 0 to 1023 range belongs to the 10-bit converter of a classic Arduino board [6].

  2. In bright light your sensor reads about 2400, and with your hand over it, about 600. Which first threshold is the most sensible?

    • 4095
    • 600
    • About 1500, between the two
    Show the answer

    About 1500, between the two. A threshold goes between the two situations you want to tell apart, with room on both sides. Reading the numbers in your own setup comes first, because chips differ from each other by several per cent [3]. (2400 and 600 are example numbers, not a measurement.)

  3. With LOW_LIMIT at 1200 and HIGH_LIMIT at 1600, the alarm is ON and the reading rises to 1400. What happens?

    • The alarm stays on: it only switches off above 1600
    • The alarm switches off, because 1400 is above 1200
    • The alarm switches off, because the value changed
    Show the answer

    The alarm stays on: it only switches off above 1600. Between the two limits nothing changes. Different switching thresholds for rising and falling inputs is what hysteresis means [7].


Sources

Show the 8 sources
  1. Espressif, Arduino-ESP32 documentation, “ADC” (analogRead returns the raw, non-calibrated value of a conversion; analogReadMilliVolts returns calibrated millivolts; analogReadResolution default 12 bits, 0 to 4095; analogSetPinAttenuation; higher attenuation allows higher measurable voltage; table of measurable ranges per attenuation for the ESP32) — https://docs.espressif.com/projects/arduino-esp32/en/latest/api/adc.html
  2. Espressif, ESP-IDF Programming Guide, “Analog to Digital Converter (ADC)” (raw results are 12 bits by default, which divides the input range into 4096 levels; attenuation levels 0, 2.5, 6 and 12 dB; reference voltage 1100 mV by design, actual value between 1000 and 1200 mV depending on the chip) — https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/adc/index.html
  3. Espressif, ESP32 Series Datasheet v5.3, section 4.9.1 “Analog-to-Digital Converter (ADC)” and pin tables (two 12-bit SAR ADCs, 18 channels; ADC characteristics: DNL up to ±7 LSB, INL up to ±12 LSB, measured with a 100 nF capacitor on the input, DC input, 25 °C, Wi-Fi and Bluetooth off; effective measurement range 150 to 2450 mV at atten = 3, and worse accuracy above a reading of 3000; by default ±6 % difference between chips; take several samples with a filter or average them for better results; GPIO 34 is ADC1_CH6, GPIO 32 to 39 are ADC1, GPIO 25, 26 and 27 are ADC2) — https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf
  4. Adafruit, “Photocells”, “Using a Photocell” (photocell wired to power and a fixed pull-down resistor to ground, with the analog input at their junction; as the photocell’s resistance decreases, the voltage across the fixed 10 kΩ resistor increases; works with a 3.3 V supply as well as 5 V; a 10 kΩ resistor saturates in bright light, a smaller one helps) — https://learn.adafruit.com/photocells/using-a-photocell
  5. Espressif, ESP-IDF Programming Guide, “GPIO & RTC GPIO” (GPIO 34 to 39 can only be inputs; ADC2 pins cannot be used when Wi-Fi is used, use an ADC1 pin instead) — https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/gpio.html
  6. SparkFun, “Analog to Digital Conversion” (the Arduino has a 10-bit ADC, 2^10 = 1024, and analogRead returns 0 to 1023) — https://learn.sparkfun.com/tutorials/analog-to-digital-conversion
  7. All About Circuits, “555 Lab - Schmitt Trigger”, Lessons in Electric Circuits, DIY Electronics Projects (a Schmitt trigger is an analog comparator with hysteresis: different switching threshold voltages depending on whether the input is going from low to high or from high to low) — https://www.allaboutcircuits.com/textbook/experiments/chpt-8/555-schmitt-trigger/
  8. All About Circuits, “Hysteresis”, Lessons in Electric Circuits, Semiconductors (hysteresis is the property of a system that does not return to its original state after the cause of the change is removed; a toggle switch is a simple example) — https://www.allaboutcircuits.com/textbook/semiconductors/chpt-7/hysteresis/

Pinch or double-tap to zoom, swipe to change diagram.Scroll with Ctrl or double-click to zoom. Arrow keys change diagram.