arduino-audio-tools
I2SBitBang.h
1 #pragma once
2 #include "AudioConfig.h"
3 #ifndef USE_I2S
4 # define USE_I2S
5 # define CREATE_I2S
6 #endif
7 #include "AudioTools/CoreAudio/AudioStreams.h"
8 #include "AudioTools/CoreAudio/AudioI2S/I2SConfig.h"
9 #include "SPI.h"
10 
11 namespace audio_tools {
12 
19 class I2SBitBang : public AudioStream {
20 public:
21  bool begin() {
22  buffer.resize(i2s_config.bits_per_sample / 8);
23  uint32_t speed = i2s_config.sample_rate * i2s_config.channels * i2s_config.bits_per_sample;
24  SPISettings settings{speed, MSBFIRST, SPI_MODE0};
25 #ifdef USE_SPI_SET_PINS
26  SPI.setCS(PIN_I2S_WS);
27  SPI.setSCK(PIN_I2S_BCK);
28  SPI.setTX(PIN_I2S_DATA);
29 #endif
30  SPI.begin();
31  SPI.beginTransaction(settings);
32  return true;
33  }
34 
35  void setAudioInfo(AudioInfo cfg) {
36  i2s_config.copyFrom(cfg);
37  begin(i2s_config);
38  }
39 
40  bool begin(I2SConfig info) {
41  //AudioStream::setAudioInfo(info);
42  i2s_config = info;
43  return begin();
44  }
45 
46  void end() { SPI.end(); }
47 
48  size_t write(const uint8_t *data, size_t len) {
49  for (int j = 0; j < len; j++) {
50  buffer.write(data[j]);
51  if (buffer.availableForWrite() == 0) {
52  digitalWrite(i2s_config.pin_ws, ws_state);
53  SPI.transfer(buffer.data(), buffer.size());
54  // toggle word select
55  ws_state = !ws_state;
56  buffer.reset();
57  }
58  }
59  return len;
60  }
61 
62 protected:
63  I2SConfig i2s_config;
64  bool ws_state = false;
65  SingleBuffer<uint8_t> buffer{0};
66 };
67 
68 // Make sure that we have one and only one I2SStream
69 #ifdef CREATE_I2S
70 using I2SStream = I2SBitBang;
71 #endif
72 
73 } // namespace audio_tools
Base class for all Audio Streams. It support the boolean operator to test if the object is ready with...
Definition: BaseStream.h:109
I2S emulated with the help of the Arduion SPI api.
Definition: I2SBitBang.h:19
void setAudioInfo(AudioInfo cfg)
Defines the input AudioInfo.
Definition: I2SBitBang.h:35
Configuration for ESP32 legacy i2s.
Definition: I2SConfigESP32.h:23
T * data()
Provides address of actual data.
Definition: Buffers.h:252
bool write(T sample) override
write add an entry to the buffer
Definition: Buffers.h:194
int availableForWrite() override
provides the number of entries that are available to write
Definition: Buffers.h:224
void reset() override
clears the buffer
Definition: Buffers.h:254
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition: AudioConfig.h:823
Basic Audio information which drives e.g. I2S.
Definition: AudioTypes.h:52
void copyFrom(AudioInfo info)
Same as set.
Definition: AudioTypes.h:107
sample_rate_t sample_rate
Sample Rate: e.g 44100.
Definition: AudioTypes.h:55
uint16_t channels
Number of channels: 2=stereo, 1=mono.
Definition: AudioTypes.h:57
uint8_t bits_per_sample
Number of bits per sample (int16_t = 16 bits)
Definition: AudioTypes.h:59