analog-output.py
We use the built-in CircuitPython library called analogio
for analog output (as well as input). There are two pins on the SAMD51 capable of digital-to-analog conversion (DAC), one of which is convenient to access from the GPIO header below the microcontroller.
⚙ Hardware Needed
- PyCubed mainboard
📚 External Libraries Needed
None
📑 Code
import board
import analogio
dac = analogio.AnalogOut(board.DAC0)
# DAC output is 16-bit value scaled from 0V to 3.3V
dac.value = 32768 # output 1.65V
How to scale a number into a range:
Our DAC output a voltage from 0V to 3.3V, but we need to scale that value into the appropriate 16-bit range:
def scale_vout(target_voltage):
return int((target_voltage/3.3) * 0xFFFF)
print(scale_vout(1.65)) # would print 32767
print(scale_vout(1)) # would print 19859
print(scale_vout(2)) # would print 39718
Using our scale_vout
helper function with the above analogio
example:
import board
import analogio
def scale_vout(target_voltage):
return int((target_voltage/3.3) * 0xFFFF)
dac = analogio.AnalogOut(board.DAC0)
dac.value = scale_vout(1.65) # output 1.65V