6. Voltage Divider Basics

Objective

Voltage dividers are indispensable circuits in electronics. Voltage dividers bring a high voltage down to a smaller one and can be tuned by the resistors you have. In this challenge, you will make a basic voltage divider and read the values of the voltage off your CircuitPython.

Components

  • 1 Metro M0 Express

  • 1 breadboard

  • 1 1K Ω Resistor

  • 2 330 Ω Resistors

  • Wires

Wiring

Change the values of the two resistors you use in your circuit and observe the changes you notice in the printed values. Follow the schematic provided to wire the Metro M0 Express.

Image from Intro to Arduino

Coding/Programming

import board

from analogio import AnalogIn

import time


analog = AnalogIn(board.A1)


def get_voltage(pin):

return (pin.value * 3.3) / 65536


while True:

print("Raw values: " + str(analog.value))

#use str(<numeric-value>) to be able to print it along with other words/characters

time.sleep(0.1)

print("Converted values: " + str(get_voltage(analog)))

time.sleep(0.1)

The above code allows you to create a function named get_voltage that converts the analog readings you receive through pin A1. Another way to achieve the goal of this challenge is to use a mapping function to make the conversion of any analog reading in the range 0-65535 to voltage value in the range 0-3.3 possible.

In CircuitPython, modules are open-source libraries that contain classes to make useful functions accessible to you. simpleio module contains classes to provide simple access to IO. simpleio.map_range(x, in_min, in_max, out_min, out_max) maps a number from one range to another. Use the link at the bottom of this page to learn more about accessing map_range function in simpleio.


To see how simpleio module could be used, now try the below code:

import board

from analogio import AnalogIn

import time

import simpleio


analog = AnalogIn(board.A1)


while True:

print("Raw values: " + str(analog.value))

time.sleep(0.1)

conv = simpleio.map_range(analog.value, 0, 65535, 0, 3.3)

print("Converted values: " + str(conv))

time.sleep(0.1)