1
+ #include < Arduino.h>
2
+ #include " BLE/Server.h"
3
+ #include " esp_log.h"
4
+ #include < driver/i2s.h>
5
+
6
+ BluetoothServer BLEServer;
7
+
8
+ // you shouldn't need to change these settings
9
+ #define BUFFER_SIZE 182
10
+ #define SAMPLE_RATE 8000
11
+ // most microphones will probably default to left channel but you may need to tie the L/R pin low
12
+ #define I2S_MIC_CHANNEL I2S_CHANNEL_FMT_ONLY_LEFT
13
+ // either wire your microphone to the same pins or change these to match your wiring
14
+ #define I2S_MIC_SERIAL_CLOCK 3 // bck, bclk, sclk
15
+ #define I2S_MIC_LEFT_RIGHT_CLOCK 2 // ws, lrclk, fs
16
+ #define I2S_MIC_SERIAL_DATA 4 // sd
17
+
18
+ i2s_config_t i2s_config = {
19
+ .mode = (i2s_mode_t )(I2S_MODE_MASTER | I2S_MODE_RX),
20
+ .sample_rate = SAMPLE_RATE,
21
+ .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
22
+ .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
23
+ .communication_format = I2S_COMM_FORMAT_I2S,
24
+ .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
25
+ .dma_buf_count = 4 ,
26
+ .dma_buf_len = 1024 ,
27
+ .use_apll = false ,
28
+ .tx_desc_auto_clear = false ,
29
+ .fixed_mclk = 0 };
30
+
31
+ i2s_pin_config_t i2s_mic_pins = {
32
+ .bck_io_num = I2S_MIC_SERIAL_CLOCK,
33
+ .ws_io_num = I2S_MIC_LEFT_RIGHT_CLOCK,
34
+ .data_out_num = I2S_PIN_NO_CHANGE,
35
+ .data_in_num = I2S_MIC_SERIAL_DATA};
36
+
37
+ void setup ()
38
+ {
39
+ ESP_LOGW (" LOG" , " Starting BLE Server" );
40
+ BLEServer.startAdvertising ();
41
+ ESP_LOGW (" LOG" , " BLE Server started" );
42
+
43
+ // start up the I2S peripheral
44
+ i2s_driver_install (I2S_NUM_0, &i2s_config, 0 , NULL );
45
+ i2s_set_pin (I2S_NUM_0, &i2s_mic_pins);
46
+ ESP_LOGW (" LOG" , " I2S pins set" );
47
+ }
48
+
49
+ #define LOG_BUFFER_BYTES_PER_LINE 16 // Adjust as needed for readability
50
+
51
+ void logBufferHex (const uint8_t *buffer, size_t length)
52
+ {
53
+ for (size_t i = 0 ; i < length; i += LOG_BUFFER_BYTES_PER_LINE)
54
+ {
55
+ char line[LOG_BUFFER_BYTES_PER_LINE * 3 + 1 ] = {0 }; // Initialize with 0 to ensure null-terminated
56
+ size_t lineIndex = 0 ;
57
+ for (size_t j = i; j < i + LOG_BUFFER_BYTES_PER_LINE && j < length; ++j)
58
+ {
59
+ lineIndex += snprintf (&line[lineIndex], sizeof (line) - lineIndex, " %02X " , buffer[j]);
60
+ if (lineIndex >= sizeof (line) - 3 )
61
+ break ; // Prevent buffer overrun
62
+ }
63
+ ESP_LOGW (" LOG" , " %s" , line);
64
+ }
65
+ }
66
+
67
+ uint8_t raw_samples[BUFFER_SIZE];
68
+ void loop ()
69
+ {
70
+ // read from the I2S device
71
+ size_t bytes_read = 0 ;
72
+ i2s_read (I2S_NUM_0, raw_samples, sizeof (uint8_t ) * BUFFER_SIZE, &bytes_read, portMAX_DELAY);
73
+ // logBufferHex(raw_samples, bytes_read);
74
+
75
+ // Send the data over BLE
76
+ if (bytes_read > 0 )
77
+ {
78
+ BLEServer.setValue (reinterpret_cast <uint8_t *>(raw_samples), bytes_read);
79
+ }
80
+ }
0 commit comments