MakeCode

Reading a potentiometer value takes one analog pin on a microcontroller. Analog pins read in a voltage and provide a value based on the voltage it reads. The number depends on the accuracy of the analog to digital conversion..

The basic code to read the value in MakeCode is shown below:

This code reads the analog pin A1 (it can be changed from A1 to A7 for Circuit Playground Express) and the result is put in a variable called value. The number ranges from 0 (corresponding to 0 volts) at full counterclockwise to 512 (1.65 volts) at the center point to 1023 (3.3 volts) at the far clockwise point.

This code would be more useful if we could see the reading. The following code, Circuit Playground-specific, lights the LEDs from 0 to 9 based on the reading from the potentiometer and the analog read pin:

This code will light the Circuit Playground Express LEDs proportional to the travel of the potentiometer wiper.

Also if you have console capability (Windows 10 MakeCode App), you can see the value printed out, shown below.

Changing Music

The second example varies a tone on the Circuit Playground Express speaker depending on the value read from the potentiometer:

This example makes really annoying noises!

You will find this example somewhat hard on the ears. The potentiometer will set the tone value from 0 to 1023 hertz - the volume will cut off at a value more than zero. And the values will not often be perfect musical note values. You can change 1/8 to other values for interesting effects.

This guide was first published on Sep 16, 2018. It was last updated on Sep 16, 2018. This page (MakeCode) was last updated on Oct 18, 2019.