Recording Sound to an SD Card with a Microcontroller.
In one of my previous articles we learned to work with an SD card, and of course it would be good to put that knowledge into practice. That's how the idea of recording sound to an SD card and then listening to it on a computer was born. We won't be able to make anything worthwhile, because we can't create new files or increase their size; these limitations are imposed by the library. But the principles of working with sound laid out in this article can be used later.
First, let's look in general terms at what we want to do. We want to record sound, but what is sound? Sound is nothing other than oscillations of a medium (air, water, etc.) in a certain frequency range; in other words, sound is a wave that propagates through a medium. That is, sound can't propagate in a vacuum (no medium, no sound), and if we tried to talk to each other in a vacuum, we simply wouldn't hear each other. These oscillations of the medium can be picked up by a microphone and converted into an electrical signal that carries the information contained in the sound. But the electrical signal at the microphone output is very weak, so it has to be amplified; we'll do this with an op-amp amplifier. The circuit was taken from an Atmel app note, a translation of which can be read here. Depending on the microphone, the value of R5 can be changed; it determines the gain.

The first thing I did after building this circuit was to see what simple sounds look like: would the letter "a" be just a harmonic (a wave of one specific frequency) or something more complex? Below is an oscillogram of a drawn-out "aaaaaa" taken from the op-amp output.

It turned out that a simple sound is much more complex than it might seem; after all, we don't feel our vocal cords making such complex movements.
Now this analog signal has to be converted into the zeros and ones a microcontroller understands; for this we'll use the MCU's built-in analog-to-digital converter (ADC). At certain intervals (the sampling rate), the ADC will convert the analog signal at its input into a corresponding digital code (a set of zeros and ones). Next, the data obtained from the ADC needs to be written to an open file on the card, but there's a catch: we won't be able to play such a file on a computer afterwards, because it has no format. For the computer to understand that this is an audio file, or more precisely a wav file, this and other metadata must be written at the beginning of the file. A wav file is divided into sections (chunks) of different types. The minimum number of chunks in a wav file is two: the first is the format chunk ("fmt ") and the second is the data chunk ("data"). You can read about the structure of a wav file here, and we'll describe these chunks with the structure below.
The question arises: at what rate should the ADC capture data, in other words, what should the sampling rate be? The answer is very simple: the ADC sampling rate must match the sampling rate of the wav file.
A wav file can be played at different sampling rates; we'll use 11025 samples per second for playback, so the ADC must also take 11025 samples per second.
To get this sampling rate, we'll trigger the ADC from a timer. We'll configure the timer itself in compare match mode, i.e. we'll set a number, and when the timer counts up to it, an interrupt will be called and an ADC conversion started.
I think someone may wonder how the value was calculated
Now, using the fact that the period is the reciprocal of frequency, T = 1/F, let's invert the whole expression and get
Since the timer frequency is the MCU frequency divided by 8, we get
That's the calculation; so every time the timer matches, an interrupt will occur, which we'll declare
so that no code is generated for it, only reti (return from interrupt).
This interrupt will start the ADC conversion, and when the conversion ends, an ADC interrupt will occur.
Now our digitized data is collected in a buffer. Since writing is only possible in 512-byte blocks, we'll make the buffer the same size. That is, we wait until the buffer fills up and write it to the card, having first written the header information there; and yes, recording will only be possible while the button is pressed. The wiring diagram looks like this.

Of course, some samples will be lost while writing to the card, and the MCU's memory size doesn't allow creating a second buffer, but the task is accomplished: although primitively, we've learned to record sound to an SD card with an MCU.
I'll leave the project and a sample recording in the archive Desktop.rar
First, let's look in general terms at what we want to do. We want to record sound, but what is sound? Sound is nothing other than oscillations of a medium (air, water, etc.) in a certain frequency range; in other words, sound is a wave that propagates through a medium. That is, sound can't propagate in a vacuum (no medium, no sound), and if we tried to talk to each other in a vacuum, we simply wouldn't hear each other. These oscillations of the medium can be picked up by a microphone and converted into an electrical signal that carries the information contained in the sound. But the electrical signal at the microphone output is very weak, so it has to be amplified; we'll do this with an op-amp amplifier. The circuit was taken from an Atmel app note, a translation of which can be read here. Depending on the microphone, the value of R5 can be changed; it determines the gain.

The first thing I did after building this circuit was to see what simple sounds look like: would the letter "a" be just a harmonic (a wave of one specific frequency) or something more complex? Below is an oscillogram of a drawn-out "aaaaaa" taken from the op-amp output.

It turned out that a simple sound is much more complex than it might seem; after all, we don't feel our vocal cords making such complex movements.
Now this analog signal has to be converted into the zeros and ones a microcontroller understands; for this we'll use the MCU's built-in analog-to-digital converter (ADC). At certain intervals (the sampling rate), the ADC will convert the analog signal at its input into a corresponding digital code (a set of zeros and ones). Next, the data obtained from the ADC needs to be written to an open file on the card, but there's a catch: we won't be able to play such a file on a computer afterwards, because it has no format. For the computer to understand that this is an audio file, or more precisely a wav file, this and other metadata must be written at the beginning of the file. A wav file is divided into sections (chunks) of different types. The minimum number of chunks in a wav file is two: the first is the format chunk ("fmt ") and the second is the data chunk ("data"). You can read about the structure of a wav file here, and we'll describe these chunks with the structure below.
struct wave_header {
// RIFF header
uint32_t riffsig; // Chunk ID - "RIFF" (0x52494646)
uint32_t filesize; // file size
uint32_t wavesig; // RIFF Type - "WAVE" (0x57415645)
// format chunk
uint32_t fmtsig; // Chunk ID - "fmt " (0x666D7420)
uint32_t fmtsize; // Chunk Data Size - 16
uint16_t type; // Compression code - WAVE_FORMAT_PCM = 1
uint16_t nch; // Number of channels - 1
uint32_t freq; // Sample rate
uint32_t rate; // Data rate - Average Bytes Per Second
uint16_t block; // BlockAlign = SignificantBitsPerSample / 8 * NumChannels; Number of bytes per sample
uint16_t bits; // Significant bits per sample - 8, 16, 24 or 32.
// data chunk
uint32_t datasig; // chunk ID - "data" (0x64617461)
uint32_t datasize; // data size
uint8_t data[]; // sample data
} wave_hdr;
The question arises: at what rate should the ADC capture data, in other words, what should the sampling rate be? The answer is very simple: the ADC sampling rate must match the sampling rate of the wav file.
A wav file can be played at different sampling rates; we'll use 11025 samples per second for playback, so the ADC must also take 11025 samples per second.
To get this sampling rate, we'll trigger the ADC from a timer. We'll configure the timer itself in compare match mode, i.e. we'll set a number, and when the timer counts up to it, an interrupt will be called and an ADC conversion started.
void start_capture(uint16_t freq)
{
// Configure the ADC, selecting channel ADC0
//left-adjust the result
ADMUX = 1<<ADLAR;
//trigger on timer compare match
SFIOR |= (1<<ADTS1) | (1<<ADTS0);
//enable the ADC, auto-trigger mode, enable the interrupt, Fadc = F_CPU/8
ADCSRA = (1<<ADEN) | (1<<ADATE) | (1<<ADIE) | (1<<ADPS1) | (1<<ADPS0);
//Configure timer0
//select CTC mode, divide the frequency by 8, Ftim = F_CPU/8
TCCR0 = (1<<WGM01) | (1<<CS01);
//enable the compare match interrupt
TIMSK |= 1<<OCIE0;
//set the OCR0 value
OCR0 = F_CPU/8UL/freq;
}
I think someone may wonder how the value was calculated
OCR0 = F_CPU/8UL/freq;time_of_one_timer_tick x number_of_ticks = period of one sampleNow, using the fact that the period is the reciprocal of frequency, T = 1/F, let's invert the whole expression and get
timer frequency x 1/number of ticks = sample ratenumber of ticks = timer frequency/sample rateOCR0 = Ftim/freq;Since the timer frequency is the MCU frequency divided by 8, we get
OCR0 = F_CPU/8UL/freq;That's the calculation; so every time the timer matches, an interrupt will occur, which we'll declare
EMPTY_INTERRUPT(TIMER0_COMP_vect);so that no code is generated for it, only reti (return from interrupt).
This interrupt will start the ADC conversion, and when the conversion ends, an ADC interrupt will occur.
ISR(ADC_vect)
{
//if the buffer isn't full, save the conversion result in the buffer
if(capture_pointer < CAPTURE_BUFLEN)
{
capture_buf[capture_pointer] = ADCH;
capture_pointer ++;
}
}Now our digitized data is collected in a buffer. Since writing is only possible in 512-byte blocks, we'll make the buffer the same size. That is, we wait until the buffer fills up and write it to the card, having first written the header information there; and yes, recording will only be possible while the button is pressed. The wiring diagram looks like this.

#define F_CPU 8000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include "spi.h"
#include "pff.h"
#include "diskio.h"
//buffer size for samples
#define CAPTURE_BUFLEN 512 // 512 samples is about 46 ms.
#define led_off PORTB &= ~(1<<PB1);
#define led_on PORTB |= (1<<PB1);
#define button_off ( (PINB & (1<<PINB0)) == 0 )
#define button_on ( (PINB & (1<<PINB0)) != 0 )
struct wave_header {
// RIFF header
uint32_t riffsig; // Chunk ID - "RIFF" (0x52494646)
uint32_t filesize; // file size
uint32_t wavesig; // RIFF Type - "WAVE" (0x57415645)
// format chunk
uint32_t fmtsig; // Chunk ID - "fmt " (0x666D7420)
uint32_t fmtsize; // Chunk Data Size - 16
uint16_t type; // Compression code - WAVE_FORMAT_PCM = 1
uint16_t nch; // Number of channels - 1
uint32_t freq; // Sample rate
uint32_t rate; // Data rate - Average Bytes Per Second
uint16_t block; // BlockAlign = SignificantBitsPerSample / 8 * NumChannels; Number of bytes per sample
uint16_t bits; // Significant bits per sample - 8, 16, 24 or 32.
// data chunk
uint32_t datasig; // chunk ID - "data" (0x64617461)
uint32_t datasize; // data size
uint8_t data[]; // sample data
} wave_hdr;
uint8_t capture_buf[CAPTURE_BUFLEN];
uint16_t capture_pointer = 0;
uint8_t last_button_state = 3;
EMPTY_INTERRUPT(TIMER0_COMP_vect);
// ADC interrupt.
ISR(ADC_vect)
{
//if the buffer isn't full, save the conversion result in the buffer
if(capture_pointer < CAPTURE_BUFLEN)
{
capture_buf[capture_pointer] = ADCH;
capture_pointer ++;
}
}
void start_capture(uint16_t freq)
{
// Configure the ADC, selecting channel ADC0
//left-adjust the result
ADMUX = 1<<ADLAR;
//trigger on timer compare match
SFIOR |= (1<<ADTS1) | (1<<ADTS0);
//enable the ADC, auto-trigger mode, enable the interrupt, Fadc = F_CPU/8
ADCSRA = (1<<ADEN) | (1<<ADATE) | (1<<ADIE) | (1<<ADPS1) | (1<<ADPS0);
//Configure timer0
//set the OCR0 value
OCR0 = F_CPU/8UL/freq;
//select CTC mode, divide the frequency by 8, Ftim = F_CPU/8
TCCR0 = (1<<WGM01) | (1<<CS01);
//enable the compare match interrupt
TIMSK |= 1<<OCIE0;
}
void record (UINT br)
{
// RIFF header
wave_hdr.riffsig = 0x46464952;
wave_hdr.filesize = sizeof(wave_hdr);
wave_hdr.wavesig = 0x45564157;
// format chunk
wave_hdr.fmtsig = 0x20746D66;
wave_hdr.fmtsize = 16;
wave_hdr.type = 1;
wave_hdr.nch = 1;
wave_hdr.freq = 11025;
wave_hdr.rate = 11025;
wave_hdr.block = 1;
wave_hdr.bits = 8;
// data chunk
wave_hdr.datasig = 0x61746164;
wave_hdr.datasize = 1000000;//we set the file size ourselves
//set the write pointer
pf_lseek(0);
//write the header
pf_write(&wave_hdr, wave_hdr.filesize, &br);
}
int main(void)
{
_delay_ms(700);
FATFS fs;//declare an object of type FATFS
UINT br; //counter of bytes read
DDRB |= 1<<PB1;//configure the pin for the LED
DDRB &= ~(1<<PB0);//configure the pin for the button
PORTB |= (1<<PB0);//pull-up
while(pf_mount(&fs) != FR_OK);
//blink the LED to indicate that the card has been mounted
led_on
_delay_ms(700);
led_off
//open the file
if(pf_open("hello.wav") == FR_OK)
{
//blink the LED to indicate that the file is open
led_on
_delay_ms(700);
led_off
//write the header information
record(br);
//start recording
start_capture(wave_hdr.freq);
//enable interrupts
sei();
for (;;)
{
//if the button is pressed
if (button_on)
{
//if the button was released before
if (last_button_state == 0)
{
sei(); //enable interrupts
}
//if the buffer is full,
if (capture_pointer == (CAPTURE_BUFLEN - 1))
{
pf_write(capture_buf, CAPTURE_BUFLEN,&br);//write the buffer to the card
if(br == CAPTURE_BUFLEN)
{
PORTB ^= 1<<PB1;// toggle the LED
}
capture_pointer = 0;//set the write pointer to the beginning of the buffer
}
last_button_state = 1;
}
// if the button is released
if (button_off && last_button_state != 0)
{
cli();//disable interrupts
last_button_state = 0;
led_off//turn off the LED
}
}
}
while(1)
{
}
}
Of course, some samples will be lost while writing to the card, and the MCU's memory size doesn't allow creating a second buffer, but the task is accomplished: although primitively, we've learned to record sound to an SD card with an MCU.
I'll leave the project and a sample recording in the archive Desktop.rar