mcp4822 – Audio output via MCP4822 dual-channel 12-bit SPI DAC.

The mcp4822 module provides the MCP4822 class for non-blocking audio playback through the Microchip MCP4822 SPI DAC using PIO and DMA.

All classes change hardware state and should be deinitialized when they are no longer needed. To do so, either call deinit() or use a context manager.

class mcp4822.MCP4822(clock: microcontroller.Pin, mosi: microcontroller.Pin, cs: microcontroller.Pin, *, gain: int = 1)

Output audio to an MCP4822 dual-channel 12-bit SPI DAC.

Create an MCP4822 object associated with the given SPI pins.

Parameters:
  • clock (Pin) – The SPI clock (SCK) pin

  • mosi (Pin) – The SPI data (SDI/MOSI) pin

  • cs (Pin) – The chip select (CS) pin

  • gain (int) – DAC output gain, 1 for 1x (0-2.048V) or 2 for 2x (0-4.096V). Default 1.

Simple 8ksps 440 Hz sine wave:

import mcp4822
import audiocore
import board
import array
import time
import math

length = 8000 // 440
sine_wave = array.array("H", [0] * length)
for i in range(length):
    sine_wave[i] = int(math.sin(math.pi * 2 * i / length) * (2 ** 15) + 2 ** 15)

sine_wave = audiocore.RawSample(sine_wave, sample_rate=8000)
dac = mcp4822.MCP4822(clock=board.GP18, mosi=board.GP19, cs=board.GP21)
dac.play(sine_wave, loop=True)
time.sleep(1)
dac.stop()

Playing a wave file from flash:

import board
import audiocore
import mcp4822

f = open("sound.wav", "rb")
wav = audiocore.WaveFile(f)

dac = mcp4822.MCP4822(clock=board.GP18, mosi=board.GP19, cs=board.GP21)
dac.play(wav)
while dac.playing:
    pass
deinit() None

Deinitialises the MCP4822 and releases any hardware resources for reuse.

__enter__() MCP4822

No-op used by Context Managers.

__exit__() None

Automatically deinitializes the hardware when exiting a context. See Lifetime and ContextManagers for more info.

play(sample: circuitpython_typing.AudioSample, *, loop: bool = False) None

Plays the sample once when loop=False and continuously when loop=True. Does not block. Use playing to block.

Sample must be an audiocore.WaveFile, audiocore.RawSample, audiomixer.Mixer or audiomp3.MP3Decoder.

The sample itself should consist of 8 bit or 16 bit samples.

stop() None

Stops playback.

playing: bool

True when the audio sample is being output. (read-only)

pause() None

Stops playback temporarily while remembering the position. Use resume to resume playback.

resume() None

Resumes sample playback after pause().

paused: bool

True when playback is paused. (read-only)