QUERY · ISSUE
dac.write_timed() does not work with NUCLEO_G474RE
bugport-stm32
The example code from micropython document does not work with NUCLEO_G474RE.
import math
from array import array
from pyb import DAC
# create a buffer containing a sine-wave, using half-word samples
buf = array('H', 2048 + int(2047 * math.sin(2 * math.pi * i / 128)) for i in range(128))
# output the sine-wave at 400Hz
dac = DAC(1, bits=12)
dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR)
The DAC1 output of PA4 pin (A2 pin on arduino connector) shows no waveform.
After a little research, I found the root cause is that DMA_PDATAALIGN_WORD should be used for the "DMA + DAC" operation of STM32G4 cpu.
Here is my modification of dac.c to make dac.write_timed() work with NUCLEO_G474RE.
STATIC void dac_start_dma(uint32_t dac_channel, const dma_descr_t *dma_descr, uint32_t dma_mode, uint32_t bit_size, uint32_t dac_align, size_t len, void *buf) {
uint32_t dma_align;
if (bit_size == 8) {
dma_align = DMA_MDATAALIGN_BYTE | DMA_PDATAALIGN_BYTE;
} else {
#if defined(STM32G4)
dma_align = DMA_MDATAALIGN_HALFWORD | DMA_PDATAALIGN_WORD;
#else
dma_align = DMA_MDATAALIGN_HALFWORD | DMA_PDATAALIGN_HALFWORD;
#endif
}
CANDIDATE · PULL REQUEST
stm32: Add DAC feature for STM32G0.
port-stm32
Summary
This PR adds DAC feature for STM32G0.
DAC.write() and DAC.write_timed() is now available.
Testing
The following code works with NUCLEO-G01BRE.
A sine wave is output via PA4 when ch=1, PA5 when ch=2.
import math
from pyb import DAC
ch = 1
# create a buffer containing a sine-wave
buf = bytearray(100)
for i in range(len(buf)):
buf[i] = 128 + int(127 * math.sin(2 * math.pi * i / len(buf)))
# output the sine-wave at 600Hz
dac = DAC(ch, bits=8)
dac.write_timed(buf, 600 * len(buf), mode=DAC.CIRCULAR)
import math
from array import array
from pyb import DAC
ch = 2
# create a buffer containing a sine-wave, using half-word samples
buf = array('H', 2048 + int(2047 * math.sin(2 * math.pi * i / 128)) for i in range(128))
# output the sine-wave at 400Hz
dac = DAC(ch, bits=12)
dac.write_timed(buf, 400 * len(buf), mode=DAC.CIRCULAR)
Trade-offs and Alternatives
This PR increases code size by 1800 Bytes.
Before:
text data bss dec hex filename
297528 108 4004 301640 49a48 build-NUCLEO_G0B1RE/firmware.elf
After:
text data bss dec hex filename
299312 108 4020 303440 4a150 build-NUCLEO_G0B1RE/firmware.elf