@@ -18,6 +18,9 @@ uint dmaChannel = 0;
1818PIO pio = pio0;
1919uint sm = 0 ;
2020
21+ // PIO program offset
22+ static uint offset;
23+
2124// raw buffers contain PDM data
2225#define RAW_BUFFER_SIZE 512 // should be a multiple of (decimation / 8)
2326uint8_t rawBuffer0[RAW_BUFFER_SIZE];
@@ -103,8 +106,13 @@ int PDMClass::begin(int channels, int sampleRate)
103106
104107 // Configure PIO state machine
105108 float clkDiv = (float )clock_get_hz (clk_sys) / sampleRate / decimation / 2 ;
106- uint offset = pio_add_program (pio, &pdm_pio_program);
107- pdm_pio_program_init (pio, sm, offset, _clkPin, _dinPin, clkDiv);
109+ if (pio_can_add_program (pio, &pdm_pio_program)) {
110+ offset = pio_add_program (pio, &pdm_pio_program);
111+ pdm_pio_program_init (pio, sm, offset, _clkPin, _dinPin, clkDiv);
112+ } else {
113+ mbed_error_printf (" Cannot load pio program\n " );
114+ mbed_die ();
115+ }
108116
109117 // Wait for microphone
110118 delay (100 );
@@ -137,8 +145,12 @@ int PDMClass::begin(int channels, int sampleRate)
137145
138146void PDMClass::end ()
139147{
148+ pio_remove_program (pio, &pdm_pio_program, offset);
140149 dma_channel_abort (dmaChannel);
141150 pinMode (_clkPin, INPUT);
151+ decimation = 128 ;
152+ rawBufferIndex = 0 ;
153+ offset = 0 ;
142154}
143155
144156int PDMClass::available ()
0 commit comments