Skip to content

Commit c00f56c

Browse files
committed
stm32 support for 1 channel
1 parent 4013206 commit c00f56c

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

src/AudioI2S/I2SSTM32.h

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ class I2SBase {
3838
LOGE("Bits per second not supported: %d", cfg.bits_per_sample);
3939
return false;
4040
}
41-
if (cfg.channels!=2){
41+
if (cfg.channels>2 || cfg.channels<=0){
4242
LOGE("Channels not supported: %d", cfg.channels);
4343
return false;
4444
}
@@ -90,11 +90,48 @@ class I2SBase {
9090

9191
/// writes the data to the I2S interface
9292
size_t writeBytes(const void *src, size_t size_bytes){
93-
return p_tx_buffer->writeArray((uint8_t*)src, size_bytes);
93+
size_t result = 0;
94+
if (cfg.channels == 2){
95+
result = p_tx_buffer->writeArray((uint8_t*)src, size_bytes);
96+
} else {
97+
// write each sample 2 times
98+
int samples = size_bytes / 2;
99+
int16_t *src_16 = (int16_t *)src;
100+
int16_t tmp[2];
101+
int result = 0;
102+
for (int j=0;j<samples;j++){
103+
tmp[0]=src_16[j];
104+
tmp[1]=src_16[j];
105+
if (p_tx_buffer->availableForWrite()>=4){
106+
p_tx_buffer->writeArray((uint8_t*)tmp, 4);
107+
result = j*2;
108+
} else {
109+
// abort if the buffer is full
110+
break;
111+
}
112+
}
113+
}
114+
return result;
94115
}
95116

96117
size_t readBytes(void *dest, size_t size_bytes){
97-
return p_rx_buffer->readArray((uint8_t*)dest, size_bytes);
118+
if (cfg.channels == 2){
119+
return p_rx_buffer->readArray((uint8_t*)dest, size_bytes);
120+
} else {
121+
// combine two channels to 1: so request double the amout
122+
int req_bytes = size_bytes*2;
123+
uint8_t tmp[req_bytes];
124+
int16_t *tmp_16 = (int16_t*) tmp;
125+
int eff_bytes = p_rx_buffer->readArray((uint8_t*)tmp, req_bytes);
126+
// add 2 channels together
127+
int16_t *dest_16 = (int16_t *)dest;
128+
int16_t eff_samples = eff_bytes / 2;
129+
int16_t idx = 0;
130+
for (int j=0;j<eff_samples;j+=2){
131+
dest_16[idx++] = static_cast<float>(tmp_16[j])+tmp_16[j+1] / 2.0;
132+
}
133+
return eff_bytes / 2;
134+
}
98135
}
99136

100137
static void writeFromReceive(uint8_t *buffer, uint16_t byteCount){

0 commit comments

Comments
 (0)