# CircuitPython Analog Out

This quick-start example shows how you can set the DAC (true analog voltage output) on Trinket M0 pad D1 (no other pins do analog out). There's a little squiggle on the pin so you know its analog output.

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

```# Trinket IO demo - analog output

from analogio import AnalogOut
import board
import time

aout = AnalogOut(board.D1)

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(D1)`

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

## Setting the analog output

The DAC on the Trinket M0 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.

Bigger boards like the Metro or Feather M0 have more code space and can perform audio playback capabilities via the DAC.

Last updated on 2017-12-01 at 04.45.54 PM Published on 2017-08-23 at 05.57.02 PM