These last few weeks were mostly focused on getting the microphones of the e-puck2 working. If you want to know why microphones are important for the project and how the code was implemented, stick around!

Why sound?

Sound is notoriously hard to work with, especially for a first-timer like me. However, I think that going through the trouble of implementing working microphones is worth it for a couple of reasons:

  1. It enables users to essentially command the robot in a very granular way.

Now that we have quite capable speech-to-text recognition, as well as cheap slot-intent mapping through embedded LLMs, it has never been easier to express a desire through speech and have a system react to it. Implementing full microphone support essentially opens up all the possibilities of linking speech to behavior, allowing students to interact with their robot in a much more fun and playful way.

  1. Sound is the most granular sensor on the time axis.

On the robot, the microphones are sampled at a pretty standard 16 kHz—that’s 16,000 measurements per second! Such granular measurements open up quite interesting capabilities. For example, with just three microphones, one can pretty accurately determine where a sound came from by triangulating the peak volume with the time difference between each microphone (although I haven’t put this into practice yet).

Generally, it’s a hard—but cool—input to work with. Of course, since the students don’t have prior sound experience, the Python API will be adapted to enable them to easily extract voice commands—or at least I’ll put up a comprehensive guide on how to do it, which could also be quite a good learning experience for them. On a side note, I haven’t planned to create a Lua API for sound yet. Since processing audio can be quite resource-intensive, allowing students to do it in an interpreted language on a resource-constrained environment will almost certainly choke the robot’s chip.

The hardware & configuration

There are four microphones on the robot: one on the front, next to the camera, and three on the top of the robot, on the left, right, and back respectively. All the microphones are physically connected to timer 9 (TIM9, on pin PA2) clocked by an external crystal. The microphones produce data over two channels: I2S and SPI (the I2S2 and SPI3 connections specifically), the right/left being connected to the first, and the front/back to the latter.

The way the microphones are able to produce output on the same channel is through bit interleaving. See, instead of outputting binary data on those binary channels, the analog output of the microphones is being converted to a density of 1’s and 0’s, where more 1’s or 0’s packed together mean high or low pressure (remember, sound is essentially just pressure waves traveling through the air) and alternating ones mean complete silence.

This format is called “PDM”, short for pulse-density modulation, a common technique to convert the amplitude of analog signals into binary. This also allows us to compact two channels into one. Since the bits are produced on TIM9’s rising or falling edge, we can tell that one microphone (say the right or front one) outputs its density bit on the rising clock, whereas the left/back ones output on the falling edge, essentially taking their turn putting their bits into the bitstream.

While this is efficient to minimize the number of hardware connections needed to output the signals, it creates an extra step to de-interleave the bits for use. This step is usually called “demuxing” and essentially involves a bit of binary math to restore each channel. To support the two microphone streams, the I2S and SPI channels are configured for a 32 kHz audio frequency with 32-bit frames, which produces a 2.048 MHz bit clock (double the 1.024 MHz rate needed for a single 64x-oversampled microphone at 16 kHz).

The software

The processing of the sound data is separated into a few steps:

  1. Data collection over DMA
  2. Demuxing the bit-interleaved data stream
  3. Conversion from PDM data to PCM
  4. 4:1 compression through IMA ADPCM
  5. Attaching metadata and packaging data to send

While the first three steps run on 1 ms loops, the last two steps run on 10 ms loops to minimize overhead. Here is a breakdown of each step:

Data collection over DMA

To get clean 16 kHz audio out of a PDM microphone, you can’t just sample it 16'000 times a second. You have to oversample it and then filter it down. In our case, the decimation factor is 64, meaning each microphone produces $16'000 \times 64 = 1'024'000$ bits per second (1.024 MHz).

Because we interleave two microphones onto a single data line (one on the rising edge, one on the falling edge), we double the rate to 2.048 MHz. To generate that frequency, we configure the STM32 chip for 32 kHz stereo audio input with 32-bit frames ($32\text{ kHz} \times 2\text{ channels} \times 32\text{ bits} = 2.048\text{ MHz}$).

Doing the math per millisecond for two channels, every 1 ms of audio takes up 2'048 bits, or 256 bytes, or 128 half-words (uint16_t). To avoid dropping bits while the CPU is busy processing, we use a double-buffer and effectively store 2 ms of audio in 256 half-words—once for each pair of channels.

1
2
uint16_t I2S_DMA_Buffer[256];
uint16_t SPI_DMA_Buffer[256];

Every 1 ms, the first 128 half-words (256 bytes) fill up and fire half-transfer interrupts (HAL_I2S_RxHalfCpltCallback and HAL_SPI_RxHalfCpltCallback). This triggers our processing task, which demuxes the channels into single-channel buffers and converts them to PCM while DMA fills up the second half of each buffer.

Demuxing the bit-interleaved data stream

Remember that we use bit interleaving to capture two microphones—left/right and front/back channels—on a single data line (I2S2 and SPI3). Before analyzing the audio, we need to separate the channels into their own buffers so we can apply filters and compression to them independently.

To do this, we perform some bitwise operations using a clever pre-computed lookup table to make the calculations faster. In C, the algorithm looks like this (for this example, the implementation has been reduced to two channels instead of the four we have for simplicity):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
uint8_t raw[2];
uint16_t right = 0, left = 0;
uint8_t demux[256] = {
    [0x00] = 0x0, // 0b00000000 -> 0b0000
    [0x01] = 0x1, // 0b00000001 -> 0b0001
    [0x04] = 0x2, // 0b00000100 -> 0b0010
    [0x05] = 0x3, // 0b00000101 -> 0b0011
    [0x10] = 0x4, // 0b00010000 -> 0b0100
    [0x11] = 0x5, // 0b00010001 -> 0b0101
    [0x14] = 0x6, // 0b00010100 -> 0b0110
    [0x15] = 0x7, // 0b00010101 -> 0b0111
    [0x40] = 0x8, // 0b01000000 -> 0b1000
    [0x41] = 0x9, // 0b01000001 -> 0b1001
    [0x44] = 0xA, // 0b01000100 -> 0b1010
    [0x45] = 0xB, // 0b01000101 -> 0b1011
    [0x50] = 0xC, // 0b01010000 -> 0b1100
    [0x51] = 0xD, // 0b01010001 -> 0b1101
    [0x54] = 0xE, // 0b01010100 -> 0b1110
    [0x55] = 0xF, // 0b01010101 -> 0b1111
};

right  = demux[raw[0] & 0x55];
right |= demux[raw[1] & 0x55] << 4;

left  = demux[(raw[0] >> 1) & 0x55]; 
left |= demux[(raw[1] >> 1) & 0x55] << 4;

Here is how it works. When using bit interleaving, the bits from both channels are packed together. For example, it could look like this:

raw[0] = [l3, r3, l2, r2, l1, r1, l0, r0]

The objective of the above algorithm is to extract the bits from the respective left and right channels and pack them together into two clean bytes. The objective of the demux table is to extract a compressed four-bit nibble (0x0 to 0xF) out of a mixed byte.

The first step is to mask out the bits that don’t correspond to the first channel. This is done with the mask 0x55, which is 0b01010101 in binary:

      [l3, r3, l2, r2, l1, r1, l0, r0]
AND     0   1   0   1   0   1   0   1
 =      0   r3  0  r2   0  r1   0   r0

For example, if we had $r_3 = 1$, $r_2 = 0$, $r_1 = 1$, and $r_0 = 1$, we would be left with 0b01000101. For the left channel, we simply shift the byte holding the interleaved bits to the right by one bit so that the left bits align with the mask—that way, we don’t need separate logic for the left channel.

This calculation corresponds to the C line:

1
right  = demux[raw[0] & 0x55];

We’ve essentially removed the left component from the byte. The next step is to map the sparse nibble into a compact nibble. This is where the demux table comes into play. It essentially maps every possible sparse nibble to a compact nibble. Taking our previous example again, which gave us 0b01000101 (or 0x45), we want to map it to 0b1011 (or 0xB). To spare us some complicated math, we use a lookup table of integers to store this. For the previous example, that corresponds to the entry:

1
uint8_t demux[256] = {[0x45] = 0xB};

Finally, to complete a full byte of data, we repeat the process on the second byte of the raw buffer, shift it over by the width of a nibble (4 bits), and bitwise-OR the second nibble with the first one, giving us one complete demuxed byte of data.

Conversion from PDM data to PCM

PDM and PCM are essentially two different ways of representing sound. At its core, sound is the compression and decompression of air reaching our eardrums.

PDM, short for Pulse Density Modulation, represents pressure changes as sequences of 1s and 0s, with the density of the bits representing the intensity of positive (1) or negative (0) pressure. For example, in a sound wave, the peak loudness of positive pressure could be represented as 11110111, the peak loudness of negative pressure as 00100000, and complete silence (no pressure change) as 01010101.

PCM, short for Pulse Code Modulation, follows the exact same logic, but instead of representing the intensity of pressure changes with bit density, it represents them with a number (code)—often a signed 16-bit integer—where the number’s value represents the sound’s amplitude.

Technically, one could implement a PDM-to-PCM filter with a simple moving average and a sliding window. However, this typically produces really bad sound quality, so real-world applications use more complex algorithms.

In my case, I used the proprietary PDM2PCM library provided by STM for their chips.

Wrapping up

This is what I’ve done so far for sound. Of course, it is far from finished. One of the most important additions still lacking is compression—specifically IMA ADPCM compression, a lossy format that provides a 4:1 reduction and is natively supported by the popular .wav file format. This will allow us to transport data from all four channels in the bandwidth of a single one.

After that, another important step will be providing Python and Lua interfaces to compute the volume of the audio data (useful for determining where a sound came from while using less compute) and a speech-to-text endpoint for the Python API, so students can use it more easily.

I’ve also spent a lot of time trying to get the camera to work, without any luck (this is about the third time I’ve tried getting it going…). It looks like DCMI is working fine, but the I2C link to the camera seems broken, as it isn’t discoverable on the I2C bus. This is problematic, because without it, I can’t configure the camera and tell it to start capturing images. I even tried flashing the old firmware back onto my robot and another unit, and the camera didn’t seem to respond there either for some reason. I’d like to think that this is a hardware fault, though I find it very unlikely that two different robots had the exact same issue.

Anyway, if I can’t get it to work, the next devlog will probably be about audio again—this time about using the speakers to play some music!

See you soon!


Comments

Have a Mastodon or Fediverse account? Reply to the post below and your public comment will appear here. Inspired by Carl Schwan's Mastodon comment system.

Reply on Mastodon

Scroll down or click here to load comments...