Capacitor Charging with micro:bit (MakeCode Python)

by | May 8, 2022

This project illustrates how a capacitor can be charged at different rates using a potentiometer (variable resistor) and displays the current voltage using the micro:bit LEDs and a set of four coloured LEDs.

It is based on a project from the Kitronic Inventor’s Kit for micro:bit. See here for more and links to a circuit diagram: https://kitronik.co.uk/blogs/resources/inventors-kit-experiment-9-help

The Python code is for use in MakeCode: https://makecode.microbit.org/_LYa9MF0Tpcdz

Capacitor Charging using micro:bit and Python in MakeCode

# Manage Capacitor Voltage using micro:bit
# Copyright R J Zealley 06/05/2022
# Licence: copy and resuse with attribution 
# Based on Kitronic Inventor's Kit project 10
# https://kitronik.co.uk/products/inventors-kit-for-the-bbc-micro-bit

# Actual capacitor voltage as read from pin 0
cap_voltage = 0

# Percentage of max voltage (3V)
percentage = 0

# Show percentage voltage using 25 microbit LEDs
def show_voltage(v):
    # Convert percentage to a fraction for 25 (LEDs)
    leds = int(v / 4)
    # Check whether each LED should be lit and plot if within range
    for x in range(0, 5):
        for y in range(0, 5):
            check = (x * 5) + y + 1
            if check <= leds:
                led.plot(x, y)
            else:
                led.unplot(x, y)
    return

# Light four LEDs based on percentage voltage
def light_leds(v):
    # tun all LEDs off
    pins.digital_write_pin(DigitalPin.P1, 0)
    pins.digital_write_pin(DigitalPin.P2, 0)
    pins.digital_write_pin(DigitalPin.P8, 0)
    pins.digital_write_pin(DigitalPin.P12, 0)
    if v > 25:
        # Light first LED
        pins.digital_write_pin(DigitalPin.P1, 1)
    if v > 50:
        # Light second LED
        pins.digital_write_pin(DigitalPin.P2, 1)
    if v > 75:
        # Light third LED
        pins.digital_write_pin(DigitalPin.P8, 1)
    if v > 90:
        # Light fourth LED
        pins.digital_write_pin(DigitalPin.P12, 1)
    return

def on_forever():
    global cap_voltage, percentage

    # read capacitor voltage from pin 0
    cap_voltage = pins.analog_read_pin(AnalogPin.P0)

    # Convert value (max 1023) into an (approx) percentage
    percentage = cap_voltage / 10

    # Display voltage using microbit LEDs
    show_voltage(percentage)

    # Display voltage on circuit LEDs
    light_leds(percentage)

basic. forever(on_forever)