Přeskočit na hlavní obsah

MDF MCAL Module

Supported STM32 families: H5
Not supported: F4, F7, G4, H7, L4, U3, U5

This module provides an abstraction layer for the multi-function digital filter (MDF) of STM32 MCUs: the receiver of the serial bit-streams of the sigma-delta modulators (PDM digital microphones, sigma-delta ADCs, digital sensors on a SPI-like or Manchester coded interface) with the parallel digital filter paths that turn them into PCM samples - the CIC (sinc) filter with the adjustable decimation, the reshape filter, the high-pass filter, the offset and the gain correction - and the monitoring functions: the out-of-limit detector, the short-circuit detector and the clock-absence detector. It offers the continuous and the single acquisition and the transfer of the samples by the DMA. It is a low-level MCAL module: it owns the MDF hardware, the application and the other modules never touch the registers.

The public interface (Mdf_Port.h, Mdf_Types.h) is identical for all supported families. The implementation for a family lives in its own branch (Dev/<Family> for development, Releases/<Family> for the released versions), so a module or an application written against the interface does not change when the MCU family changes.

This README is the landing page and the specification of the interface (master). The family branches contain their own README with everything that is specific to the family: the instances of the device, their settings and the status of the implementation.

Status: design. No implementation exists yet, the interface below is a proposal. Stories and branches follow.


Intent and purpose​

  • A PDM microphone outputs a 1-bit stream at a few MHz whose density is the sound; to get the audio samples the stream has to be filtered and decimated by a factor of 64 ... 128. A sigma-delta current / voltage ADC of a motor drive or a power meter does the same with its own bit-stream. The MDF is a multi-channel hardware decimator: six serial inputs, six filter paths, a flexible matrix that connects any input to any filter (the stereo microphone pair, the multi-microphone array, the three-phase current sensing), and the filter coefficients are programmable in the form of the decimation ratio and the orders.
  • The user describes the result - "16 kHz, 16-bit samples from the microphone pair on the clock of 2 MHz" - and the module calculates the serial clock divider, the CIC order and the decimation ratio, the reshape filter, the high-pass corner and the gain, and reports the achieved output rate and its error.
  • Several filters can run synchronously (the stereo or the array acquisition starts all of them on the same clock edge), triggered by the software or a hardware signal; the DMA transfers the samples of every filter to its own buffer with the half and the complete callbacks (the same model as the audio streams of the Sai module).
  • The detectors make the monitoring part of the hardware: the out-of-limit detector raises an event (and a break for the timers) when the filtered value crosses a threshold - the overcurrent protection without the CPU; the short-circuit detector finds a stuck bit-stream; the clock absence detector finds a dead modulator clock.
  • The module hides the differences between the families: the number of the serial inputs and the filters, the digital sensor interface modes, the connection to the internal ADCs and the break outputs differ, the interface stays the same.

What the module is not: it does not drive the microphones or the sensors beyond the clock (their power and configuration are the board's), it does not do the audio processing and it is not the DFSDM of the older families (a different peripheral that has its own module if it is needed).


Concept​

The module keeps the serial interfaces and the filters apart:

ItemMeaning
Serial interface (mdf_SitfId_t)The input mode (MDF_SITF_PDM compatible, MDF_SITF_SPI, MDF_SITF_MANCHESTER), the clock source (the module's own clock output or an input), the sampling edge, the common clock divider for the modulators.
Filter (mdf_FilterId_t)The connected serial input (through the matrix) or the internal ADC, the CIC order and the decimation ratio, the reshape filter on / off, the high-pass filter corner, the offset, the gain, the output resolution (16 / 24 bits).
AcquisitionContinuous or single, the trigger (software / hardware), the synchronization with the other filters, the delay of a bit-stream.
DetectorsThe out-of-limit detector (the low and the high threshold, the event, the break), the short-circuit detector (the number of the equal bits), the clock absence detector.
StreamThe buffer and the callbacks for the samples of the filter.

Rules:

  1. Mdf_Init configures the clock, the serial interfaces and the pins and leaves every filter stopped; each filter is configured with Mdf_Set_FilterConfig and started by Mdf_Set_AcquisitionStart (one filter or a group that starts at once).
  2. The output sample rate is serial clock / (the decimation of the CIC x the decimation of the reshape filter); the module searches the decimation and the clock divider for the requested rate within the limits of the filter (the gain of the CIC grows with the order and decimation, the module scales the gain to avoid the overflow) and returns the achieved rate; a combination that cannot be made within the tolerance is rejected.
  3. The configuration of a filter and of the interface is changed only while the filter is stopped.
  4. The samples are delivered by the DMA to the buffer of the filter; the half / complete callbacks hand the blocks over, the overrun (the buffer not taken in time) is reported by the error callback.
  5. The detectors are configured per filter; their events are reported by the callbacks (and as a break signal to the timers where the hardware has it).
  6. All parameters are checked before a register is written.

Supported families​

Every family gets its own story, its own tasks and its own branches Dev/<Family> and Releases/<Family> cut from this master.

FamilyBranchFilterStatus
STM32H5Dev/STM32H5MDF1 on the STM32H5E / H5F lines: 6 serial inputs (SPI, Manchester, PDM compatible), 2 common clocks, the bit-stream matrix, the inputs from the internal ADCs, 6 filter paths (CIC sinc4 / sinc5, reshape, high-pass, offset, gain), the out-of-limit, the short-circuit and the clock absence detectors, 16 / 24-bit output, DMAplanned (first)
STM32U5Dev/STM32U5MDF1 and ADF1 (the audio digital filter - the Adf module) on the lines that have themplanned
STM32U3Dev/STM32U3device dependentplanned
STM32F4, STM32F7, STM32G4, STM32H7, STM32L4Dev/STM32F4 ...no MDF on the device (the DFSDM of these families is a different peripheral) - the module is a stub that returns MDF_REQUEST_ERRORplanned

A function without a meaning in a family stays in the interface, returns MDF_REQUEST_ERROR and suppresses the unused parameters (for example a filter or a serial input the device does not have, the Manchester mode of a device without it).


Public interface in short (proposal)​

GroupFunctions
Module managementMdf_Get_ModuleVersion, Mdf_Init, Mdf_Deinit, Mdf_Task, Mdf_Get_DefaultConfig
Serial interfacesMdf_Set_SitfConfig, Mdf_Set_ClockConfig, Mdf_Set_BitstreamDelay
FiltersMdf_Set_FilterConfig, Mdf_Get_FilterConfig, Mdf_Get_OutputRate, Mdf_Set_Gain, Mdf_Set_Offset
AcquisitionMdf_Set_AcquisitionStart, Mdf_Set_AcquisitionStop, Mdf_Set_AcquisitionGroup, Mdf_Get_Sample, Mdf_Get_FilterState
StreamingMdf_Set_StreamStart, Mdf_Set_StreamStop, Mdf_Get_XferError
DetectorsMdf_Set_OutOfLimitDetector, Mdf_Set_ShortCircuitDetector, Mdf_Set_ClockAbsenceDetector
InterruptsMdf_Set_IrqPriority / Get, the callbacks are a part of the configuration
PinsMdf_InitSdGpio, Mdf_InitClockGpio
mdf_ModuleVersion_t Mdf_Get_ModuleVersion ( void );

mdf_RequestState_t Mdf_Init ( const mdf_Config_t * const mdfConfig );
mdf_RequestState_t Mdf_Deinit ( void );
void Mdf_Task ( void );
mdf_RequestState_t Mdf_Get_DefaultConfig ( mdf_Config_t * const mdfConfig );

mdf_RequestState_t Mdf_Set_FilterConfig ( mdf_FilterId_t filterId, const mdf_FilterConfig_t * const filterConfig );
mdf_RequestState_t Mdf_Get_OutputRate ( mdf_FilterId_t filterId, mdf_Frequency_Hz_t * const outputRate );

mdf_RequestState_t Mdf_Set_AcquisitionStart ( mdf_FilterId_t filterId );
mdf_RequestState_t Mdf_Set_AcquisitionGroup ( mdf_FilterMask_t filterMask );
mdf_RequestState_t Mdf_Set_AcquisitionStop ( mdf_FilterId_t filterId );
mdf_RequestState_t Mdf_Get_Sample ( mdf_FilterId_t filterId, mdf_Sample_t * const sample );

mdf_RequestState_t Mdf_Set_StreamStart ( mdf_FilterId_t filterId, const mdf_StreamRequest_t * const streamRequest );
mdf_RequestState_t Mdf_Set_OutOfLimitDetector ( mdf_FilterId_t filterId, const mdf_OldConfig_t * const oldConfig );

Every function returns MDF_REQUEST_OK / MDF_REQUEST_ERROR and checks its parameters and the state of the module before it touches a register.

TypeMeaning
mdf_Config_tKernel clock source, the common clocks, the serial interface table, the filter table, transfer mode, DMA channels, pins, callbacks, interrupt priority
mdf_FilterConfig_tThe input (serial input or internal ADC), the output rate (Hz), the CIC order, the high-pass corner, the gain, the offset, the resolution, the trigger
mdf_StreamRequest_tThe buffer, the number of the samples, circular / one shot
mdf_OldConfig_tThe low and the high threshold, the break enable
CallbacksStreamHalfCallback, StreamCompleteCallback, OutOfLimitCallback, ShortCircuitCallback, ClockAbsenceCallback, ErrorCallback

Usage​

A stereo PDM microphone pair at 16 kHz​

#include "Mdf_Port.h"

static mdf_Sample_t left[ 2u * 160u ]; /* two halves of 10 ms */
static mdf_Sample_t right[ 2u * 160u ];

mdf_Config_t mdfConfig;
mdf_FilterConfig_t micConfig;

(void)Mdf_Get_DefaultConfig( &mdfConfig );
mdfConfig.Sitf[ MDF_SITF_0 ].Mode = MDF_SITF_PDM;
mdfConfig.Sitf[ MDF_SITF_0 ].ClockHz = 2048000u;
(void)Mdf_Init( &mdfConfig );

micConfig.Input = MDF_INPUT_SITF_0_RISING; /* the left microphone on the rising edge */
micConfig.OutputRate = 16000u;
micConfig.CicOrder = MDF_CIC_SINC5;
micConfig.HighPass = MDF_HIGHPASS_20_HZ;
(void)Mdf_Set_FilterConfig( MDF_FILTER_0, &micConfig );

micConfig.Input = MDF_INPUT_SITF_0_FALLING; /* the right one on the falling edge */
(void)Mdf_Set_FilterConfig( MDF_FILTER_1, &micConfig );

/* the stream requests of the two filters, then start both on the same clock edge */
(void)Mdf_Set_AcquisitionGroup( MDF_FILTER_MASK_0 | MDF_FILTER_MASK_1 );

Overcurrent protection with the out-of-limit detector​

const mdf_OldConfig_t overCurrent = { .HighThreshold = 12000, .LowThreshold = -12000, .Break = MDF_FUNCTION_ACTIVE };
(void)Mdf_Set_OutOfLimitDetector( MDF_FILTER_2, &overCurrent );

Behaviour and limits​

  • Clock and the rate. The serial clock comes from the kernel clock and the divider; the achievable rates are the ratios of integers - the audio rate 16 / 32 / 48 kHz needs an audio clock; the achieved rate is returned and the tolerance is checked.
  • Latency and settling. The CIC and the high-pass filters have a settling time after the start; the first samples are discarded by the module (a configurable count).
  • Overflow. The CIC gain D^N is large; the module scales it with the gain settings to the output resolution; the saturation is reported.
  • Synchronous start. A group start is the only way to have the samples of the several filters aligned in the time.
  • Not part of the first version: the use of the filters as a general sigma-delta ADC calibration source, the automatic microphone gain, the beam-forming across the filters.

Dependencies​

  • Rcc - peripheral clock, the kernel clock source and the frequency (the audio clock)
  • Nvic - interrupt
  • Gpio - the serial data and clock pins
  • Gpdma - DMA transfers of the samples
  • Adc - the internal ADC connection of the filter inputs (configured by its module)
  • RAL (Register Abstraction Layer) - used internally to access the registers

All mandatory RCC, NVIC, GPIO and DMA configurations are handled internally.


Testing​

  • Unit tests (host, Unity + CMock + RegMem): the search of the decimation and the clock divider for the output rates (the exact ones, the ones within the tolerance, the unreachable ones), the CIC gain scaling, the filter configuration to register mapping, the group start, the stream flow with the callbacks, the detectors, the rejected changes of a running filter.
  • Integration tests (target, probe-rs): a sigma-delta modulator signal generated by a timer / the GPIO (a known duty) converted and compared, the microphone pair capture, the out-of-limit break of a PWM timer.

Interface conventions​

The module follows the common rules of the MCAL layer, so that it behaves like the other modules:

  • Lists instead of free members. Everything that the hardware restricts (the pins, the kernel clock sources, the DMA channels, the triggers and the other selectable sources) is a typedef enum list with exactly the items that are valid for the device line; a pin is an item MDF_<SIGNAL>_PIN_<INSTANCE>_P<port><pin> and there is an *_UNUSED item. A choice that is not in the list cannot be written.
  • Own peripheral only. The module calls only the registers / LL functions of its own peripheral. The clocks, the interrupts, the pins, the DMA and the EXTI lines go through the API of the Rcc, Nvic, Gpio, Gpdma and Exti modules; a missing function is added to that module, it is not bypassed.
  • Init verifies itself. Mdf_Init checks the result at the end; when it is not as required, the module is deinitialized and an error is returned. The waiting for the hardware is a loop on the register state with a timeout, never a blind delay.
  • Transfer modes. Where the module moves data, the POLL (served by Mdf_Task), ISR and DMA modes have the same configuration structure, the same request and the same callbacks (error, half transfer, transfer complete).
  • Flags and states are enums of the module (mdf_FunctionState_t, mdf_FlagState_t), the limits and the constants are named, there are no magic numbers in the interface.
  • Unsupported functions stay. A function without a meaning in a family keeps its signature, suppresses the unused parameters and returns MDF_REQUEST_ERROR.
  • Documentation. Every function and type has a Doxygen description, the main header has the \defgroup.

Repository layout and branches​

The master holds this README and the license. The family branches (Dev/<Family>, Releases/<Family>) hold:

PathContent
README.mdREADME of the family: the instances of the device, specifics, errata, status
Mdf_Port.h, Mdf_Types.hPublic interface (identical in all families)
Mdf*.c, Mdf.hImplementation of the family
CMakeLists.txtLibrary Mdf_Lib of the EmBi platform
Tests/UnitTestsUnit tests (Unity + CMock + RegMem)
Tests/IntegrationTestsIntegration tests on the target (probe-rs)

A change of the public interface is made in all families.


CMake integration​

target_link_libraries( User_Lib PRIVATE Mdf_Lib )
  1. Link Mdf_Lib to your CMake library.
  2. Include Mdf_Port.h in your project.
  3. Configure the module as needed for your hardware.

License​

This project is licensed under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0).

You are free to use, modify, and share this work for non-commercial purposes, provided appropriate credit is given.

See LICENSE.md for full terms or visit creativecommons.org/licenses/by-nc/4.0.


Authors​

Contributions are welcome! Please open a pull request.