6. Potentiometer with LED

6.1. Connections

The LED must be placed in line with a 47 ohm resistor.
The 47 ohm resistor has Yellow, Violet, Black, Gold coloured bands.
../_images/47ohm.png

6.2. Model

  1. Place the resistor first.

  2. Place the LEDs with the long lead (leg) so that it is closest to the pin side of the circuit. In this model, the long lead is on the left side of the breadboard.

  3. Place the potentiometer.

  4. Connect with the jumper wires.

../_images/potentiometer_1_bb.png ../_images/potentiometer_2_bb.png ../_images/potentiometer_2.jpg

6.3. Read and Write analog

The code below reads the value of the potentiometer and uses it to control the LED brightness.
Try turning it from side to side to see the effect.
from microbit import *

while True:
    potval = pin2.read_analog()
    pin0.write_analog(potval)
    sleep(40)

Tasks

  1. Connect a second LED with its own resistor via pin1. Control it via the potentiometer as well.

  2. With 2 LEDs connected, adjust the code so that they have opposite brightness. e.g when the potentiometer value is 1023, one LED is powered by write_analog(1023) and the other LED is powered by write_analog(0).

Connect a second LED with its own resistor via pin1. Control it via the potentiometer as well.

from microbit import *


while True:
    potval = pin2.read_analog()
    pin0.write_analog(potval)
    pin1.write_analog(potval)
    sleep(40)

With 2 LEDs connected, adjust the code so that they have opposite brightness. e.g when the potentiometer value is 1023, one LED is powered by write_analog(1023) and the other LED is powered by write_analog(0).

from microbit import *

while True:
    potval = pin2.read_analog()
    pin0.write_analog(potval)
    pin1.write_analog(1023 - potval)
    sleep(40)

Exercise

  1. Use a red and yellow led on separate pins. When the potentiometer value is 500 or more, use digital write to turn on the yellow led and turn the red led off. When the potentiometer value is under 500, use digital write to turn on the red led and turn the yellow led off.

  2. Add to the code above to display a yes image when the yellow led is on and a no image when the red led is on.

  3. Use pin 8 or pin 12 for a third led and control the three leds using if and elif such that each led has atleast a 300 units range for itself from the potentiometer reading.

Some starting code to build from:

from microbit import *


while True:
    potval = pin2.read_analog()
    if potval >= 500:
        pin0.write_digital(0)
        pin1.write_digital(1)
    else:
        pin0.write_digital(1)
        pin1.write_digital(0)
    sleep(40)