5.8. Analog Sensors#

Analog sensors are devices that produce a continuous electrical signal in response to a physical quantity. Unlike digital sensors, which only provide two states (on/off), analog sensors can represent a full range of values. This makes them ideal for measuring real-world phenomena that vary smoothly, such as temperature, light, or pressure.

Analog sensors typically output a voltage (or sometimes a current) that changes in proportion to what they are measuring.

Examples

  • Temperature: A thermistor changes its resistance with temperature. When placed in a circuit, it produces a voltage that rises or falls with heat.

  • Light: A photoresistor (LDR) reduces its resistance as light intensity increases, changing the voltage across it.

  • Force/Pressure: A strain-gauge load cell generates a small change in voltage when force is applied.

  • Sound: A microphone converts sound waves into a voltage waveform that follows the shape of the vibrations.

5.8.1. Analog-to-Digital Converters (ADCs)#

A microcontroller reads analog signals using an analog-to-digital converter (ADC), which translates the continuous voltage into digital numbers. Most modern microcontrollers include analog-to-digital converters.

Note

ADC functionality is more costly to produce than digital only pins on a microcontroller. Therefore only a few pins will have this functionality available.

ADCs have characteristics that govern how faithfully they are able to represent an analog signal:

  • Resolution - how many steps the ADC divides the voltage range into. For example, a 10-bit ADC (like in the micro:bit) splits 0-3.3 V into 1024 levels (0-1023). Quantisation is the term used to describe the rounding effect that happens because the ADC can only report a discrete step value.

  • Sampling rate - how often the ADC takes readings per second. Higher rates capture faster-changing signals.

5.8.2. Example: Reading Analog Values With MicroPython#

Here’s a simple example of reading an analog sensor (such as an LDR on pin0) using MicroPython on the BBC micro:bit:

from microbit import *

while True:
    sensor_value = pin0.read_analog()  # 0 to 1023
    print(sensor_value)
    sleep(500)

To convert this voltage reading to a temperature, we would have to know the calibration curve provided by the manufacturer of the LDR sensor.