# Microphone

Record sound and measure its level with the Kode Dot's microphone.

## What it is

Your app records with the microphone to measure how loud something is, draw the
waveform or save the sound to the microSD card. For that it uses
`kode_audio_record_samples`, which leaves the samples in a buffer your app provides,
or `kode_audio_record_file`, which saves them to a WAV. The microphone is a small analogue
MEMS capsule, the **ZTS6211E**.

![Animation. Close-up of the bottom edge of the Kode Dot, under the buttons. On the left, the USB-C port. To its right, near the corner, a small hole circled, with a label: microphone, the hole next to the USB-C port. On the right is what this page's example measures with kode_audio_record_samples(), the largest sample in each 100 ms, as a bar from 0 to 32767. In silence the bar stays low. Then a sound arrives, blue rings close in on the hole and the bar jumps and moves up and down well above. At the end it goes quiet again and the bar drops. Label: sound goes in through the hole and the app measures how loud it is.](/device/microphone/listen.webp)

Each recording lasts 30 s at most, and the [speaker](/device/speaker)
cannot play while you record.

## How it is connected

The microphone goes to the audio codec, the ES8311 that
[Speaker](/device/speaker#what-it-is) explains. The codec turns its sound into
samples and passes them to the P4 over I2S, on GPIO33 and with the same clock
as the speaker. Its settings, such as the gain, reach it over the
[shared I2C bus](/device/overview#how-it-is-connected). The microphone has no
address of its own, so it does not show up when you scan the I2C bus.

![The ESP32-P4, which runs your code, reaches the audio codec, an ES8311, over two buses. One is the I2C bus at address 0x18, on GPIO4 and GPIO5, and the other is the I2S bus, on GPIO33, GPIO34, GPIO36 and GPIO37. On the right, the microphone, a ZTS6211E, sends its sound to the codec.](/device/microphone/connection.webp)

The full circuit is in the [main board schematic](/hardware/main-board).

## Specifications

- **Always powered**: The capsule has no switch of its own, so it is powered whenever the Kode Dot is on, whether you record or not.
- **48 kHz, 16-bit, mono**: The format of what it records.
- **Gain from 0 to 42 dB**: Set with `kode_audio_set` and `"mic_gain"`, in 6 dB steps, until the next reset.
- **Up to 30 s**: The longest each recording lasts.
- **A WAV on the microSD or the flash**: `kode_audio_record_file` saves the WAV in `sd/...` or in `flash/...`, inside a folder that already exists.
- **Recording in the background**: `kode_audio_record_start` records while your app goes on. To check on it, stop it and save it, see [the SDK API](/sdk/kode#api-the-standard-layer-audio).

The calls to record are `kode_audio_record_samples`,
`kode_audio_record_file` and `kode_audio_record_start`, in `kode.h`.

## Gotchas

- **A call fails with “audio is busy”**: The microphone and the speaker share the codec and take turns, so while a sound plays in the background or a recording runs, the other audio calls fail. Wait for the first to end, or stop the background sound with `kode_audio_play_stop`.
- **A recording returns fewer frames than you expected**: It stops after the `ms` you ask for or when the buffer is full, whichever comes first. At the end, the codec may also deliver a few fewer frames. Use the count it returns in `frames`.

## Apps that use it

- https://apps.kode.diy/app/1f307daf-bf92-433e-b7ca-ed4cd0ac59f9
- https://apps.kode.diy/app/a75664fd-b105-4712-9f36-ee1e03214554

## Example code

Run the program and, while it is quiet, you see a small number that goes up
as soon as you speak or tap the case. That number, from 0 to 32767, comes out
every half second and is the highest sample the program heard in that time, so
it tells how loud the sound is. The first line can come out high, from a pop
the codec makes as it starts to record ([kode-sdk#286](https://github.com/kodediy/kode-sdk/issues/286)).

```c
/* SPDX-License-Identifier: GPL-3.0-or-later */
/**
 * @file mic_level.c
 * @brief Prints how loud the room is, twice a second.
 *
 * Each line is the largest sample of the last half second, from 0 to 32767.
 * Speak or tap the front of the case and the number jumps.
 *
 * from Kode with love
 */
#include "kode.h"

#define MIC_WINDOW_FRAMES 4800U  /**< Samples in one window: 100 ms at 48 kHz. */
#define MIC_WINDOW_MS     100U   /**< Length of one window. */
#define MIC_WINDOWS       5U     /**< Windows per line: one line every half second. */
#define MIC_RETRY_MS      1000U  /**< Wait after a failed recording. */

/** @brief One window of samples. */
static int16_t s_buf[MIC_WINDOW_FRAMES];

/** @brief Record five windows, keep the loudest sample, print it, repeat. */
void app_main(void)
{
    kode_init();
    kode_print("Running: speak or tap the case");

    while ( true )
    {
        int32_t peak = 0;
        bool    ok   = true;

        for ( uint32_t w = 0U; (MIC_WINDOWS > w) && ok; ++w )
        {
            uint32_t got = 0U;

            ok = kode_audio_record_samples(s_buf, MIC_WINDOW_FRAMES, MIC_WINDOW_MS, &got);
            for ( uint32_t i = 0U; ok && (i < got); ++i )
            {
                int32_t level = s_buf[i];

                if ( 0 > level )
                {
                    level = -level;
                }
                if ( level > peak )
                {
                    peak = level;
                }
            }
        }
        if ( !ok )
        {
            kode_print("no recording: %s", kode_error());
            kode_delay(MIC_RETRY_MS);
            continue;
        }
        kode_print("level %d / 32767", (int)peak);
    }
}
```

If you would rather build it yourself, follow [the steps shared by every example](/device/overview#run-the-example-of-a-page).

## In the SDK

- [`kdrv/audio`](https://github.com/kodediy/kode-sdk/tree/v0.1.5/components/kdrv/audio): the ES8311 driver in `kode-sdk`, both directions, described in [the ES8311 driver](/sdk/kdrv/es8311).
- [`examples/audio`](https://github.com/kodediy/kode-sdk/tree/v0.1.5/examples/audio): an SDK example for sound out and in.
