Analog Input and Output
Sensors like buttons produce only two states, which is convenient for the digital pins on the ItsyBitsy, but there are plenty of examples of sensors that produce voltages proportional to signals that cannot be read digitally. For example, the potentiometer can be wired to produce a voltage proportional to the angle of the knob. Microcontrollers, including the ItsyBitsy, have an analog to digital converter (ADC), to read the voltage and turn it into a digital number.
Visualizing Analog Voltages
The potentiometer is a knob that can be used as an angle sensor, using the following circuit diagram:
The potentiometer in the kit rotates 270 degrees, and the output voltage is linearly proportional to the angle (there are also logarithmic potentiometers, used as volume knobs). The output voltage can be read by any of the A pins on the ItsyBitsy. The number returned is an integer from 0 (0V) to 65535 (3.3V).
Add the analog input library:
from analogio import AnalogIn
Make a variable to read the voltage:
analog1in = AnalogIn(board.A1)
Read the voltage into a variable
a = analog1in.value # will be 0 to 65535
Read the voltage value every 0.05 seconds and print to the computer. Can you see the column of text using the Serial button?
Edit the code so that the numbers are printed inside of parenthesis, something like:
print("("+str(analog1in.value)+")")
Try opening the Plotter, and because the number is formatted inside (), the data is plotted.
Set the brightness of the LED based on the potentiometer
Most microcontrollers don’t have the ability to generate analog voltages (using an internal digital to analog converter)((the ItsyBitsy does have a DAC, but we won’t use it for this purpose)). Instead, the microcontroller can digitally pulse a pin at high frequency so that the average value is an analog signal. The function that does this is called PWM. The amount that the pin is on is called the duty cycle, and on the ItsyBitsy ranges from 0 (off) to 65535 (full on).
Add the PWM library:
import pulseio
Replace the led variable with a pulseio variable:
led = pulseio.PWMOut(board.D9, frequency=5000, duty_cycle=0)
Set the duty cycle to some number
led.duty_cycle = #0 to 65535