How the volts Function Works

The micro:bit module’s A/D0, A/D1, and A/D2 sockets are connected to its Nordic chip's pins that are configured for analog to digital conversion.  Analog to digital conversion, called "A to D" and abbreviated A/D, is how microcontrollers measure voltage. The microcontroller splits a voltage range into many numbered, equal divisions, with each number representing a voltage level. More divisions provide a higher resolution, with more precise voltage measurements.

Each of the micro:bit module’s analog inputs has a 10-bit resolution, meaning that it uses 10 binary digits to describe its voltage measurement.  With 10 binary digits, you can count from 0 to 1023; that’s a total of 1024 voltage levels if you include zero.

By default, the cyber:bot’s read_analog function is configured to use the 0…1023 values to describe where a voltage measurement falls in a 3.3 V scale.  If you split 3.3 V into 1024 different levels, each level is 3.3/1024ths of a volt apart.  3.3/1024ths of a volt is approximately 0.00322266 V, or about 3.22 thousandths of a volt.  So, to convert a value returned by read_analog to a voltmeter-style value, all the volts function has to do is multiply by 3.3 and divide by 1024.

Example: The read_analog function returns 742; how many volts is that?
Answer:
V = 742 x 3.3 V / 1024
  = 2.39121094 V
  = 2.39 V

 
The previous scripts have been storing the read_analog function values as the variable ad2.  This variable is stored as an integer since it returns the values between 0 and 1023.  It is then multiplied by 3.3 and divided by 1024 to get the voltage value (just like we converted 742), and this is being stored as the float variable volts.

    ad2 = pin2.read_analog()
    volts = ad2 * (3.3/1024)

The script phototransistor_voltage displays the value returned by volts with the display.scroll function.

The script halt_under_shadow script uses that value to bring the cyber:bot to a stop when it detects a shadow (if volts < 0.1).

Binary vs. Analog and Digital

A binary sensor can transmit two different states, typically to indicate the presence or absence of something.  For example, a whisker sends a high signal if it is not pressed, or a low signal if it is pressed.

An analog sensor sends a continuous range of values that correspond to a continuous range of measurements.  The phototransistor circuits in this activity are examples of analog sensors. They provide continuous ranges of values that correspond to continuous ranges of light levels.

A digital value is a number expressed by digits.  Computers and microcontrollers store analog measurements as digital values.  The process of measuring an analog sensor and storing that measurement as a digital value is called analog to digital conversion.  The measurement is called a digitized measurement.  Analog to digital conversion documents will also call them quantized measurements.