CircuitPython Analog Out

This quick-start example shows how you can set the DAC (true analog voltage output) on pad A0 (no other pins do analog out)

Copy and paste the code block into main.py using your favorite text editor, and save the file, to run the demo

# CircuitPython IO demo - analog output
     
from analogio import AnalogOut
import board
import time
    
aout = AnalogOut(board.A0)
     
while True:
  # Count up from 0 to 65535, with 64 increment
  # which ends up corresponding to the DAC's 10-bit range
  for i in range (0,65535,64):
    aout.value = i

Creating an analog output

aout = AnalogOut(A0)

Creates an object aout that is connected to the only DAC pin available - A0.

Setting the analog output

The DAC on the SAMD21 is a 10-bit output, from 0-3.3V. So in theory you will have a resolution of 0.0032 Volts per bit. To allow CircuitPython to be general-purpose enough that it can be used with chips with anything from 8 to 16-bit DACs, the DAC takes a 16-bit value and divides it down internally.

E.g. writing 0 will be the same as setting it to 0 - 0 Volts out

Writing 5000 is the same as setting it to 5000 / 64 = 78
And 78 / 1024 * 3.3V = 0.25V output

Writing 65535 is the same as 1023 which is the top range and you'll get 3.3V output

Main Loop

The main loop is fairly simple, it just goes through the entire range of the DAC, from 0 to 65535, but increments 64 at a time so it ends up clicking up one bit for each of the 10-bits of range available.

CircuitPython is not terribly fast, so at the fastest update loop you'll get 4 Hz. The DAC isn't good for audio outputs as-is.

If you have an 'Express' board like the Circuit Playground Express, Metro M0 or Feather M0, these have more code space and can perform audio playback capabilities via the DAC. Gemma/Trinket M0 cannot!

Last updated on 2017-12-01 at 04.59.09 PM Published on 2017-10-12 at 10.43.39 PM