DAC to play audio samples I have a buffer which contains 16000 PCM samples of 8Khz 8-bit mono. I am trying to play it using 12 bit MCP4725 DAC. I have tried using micros() to control the write interval for the DAC. Here's my code:

uint8_t soundData[16000] = { 234,206,79,255,249,....,210,222 }; // 8Khz 8-bit mono
long previousMicros = 0; // Sorry for missing this out!!

void setup() {

Serial.begin(115200);
Wire.begin(D2, D1);
delay(100); // delay 100 ms
Serial.flush();
delay(1000);

} 

void value_write(uint16_t temp){

  Wire.beginTransmission(0x62);
  Wire.write(64); 
  Wire.write(temp &gt;&gt; 4);        // the 8 most significant bits...
  Wire.write((temp &amp; 15) &lt;&lt; 4); // the 4 least significant bits...
  Wire.endTransmission();

}

void loop() {

  unsigned long currentMicros = micros();

// 125 uS sampling for 8KHz signal    
if(currentMicros - previousMicros &gt; 125) {
  Serial.print("Index: ");
  Serial.println(indx);
  uint16_t temp = map(soundData[indx++], 0, 255, 0, 4095);

  value_write(temp);
}

}


The write should logically be completed within 2 seconds but takes way more time. Any help regarding successfully writing the PCM values to the DAC at 8000Hz is greatly appreciated.
One sample takes 38 I2C clock cycles to write. That's:

1 START
7 Address
1 R/W
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
1 STOP


At the default 100kHz clock speed that's 100,000/38 = 2631.58 samples per second absolute maximum.

You can increase the clock speed to 400kHz, which would allow you 400,000 / 38 = 10526 samples per second absolute maximum.  That would just about be do-able.

I am unsure what the ESP8266 can support, but the DAC also supports "High Speed" mode - 3.4MHz I2C.  If the ESP8266 supports that you can then run at 3,400,000 / 38 = 89474 samples per second, which is better still.

There's also the matter of the map() function which is just nasty in this situation. You can just bit-shift.

So besides just removing the Serial commands (which will slow things down massively) you should also:


Change the I2C clock to at least 400kHz
Change map() to soundData[indx++] &lt;&lt; 4
Consider using a timer to trigger the sending of the samples


But, with all that said. an I2C DAC is really not suited to audio playback. I2C is just too slow and clunky for audio. You'd be better off with an SPI DAC which can run much much faster than I2C. Better still you should investigate I2S on the ESP8266. This is designed specifically for audio, although it's much harder to set up owing to the increased number of special clocks you need to provide ("master" clock, "bit" clock and "l/r" clock). Also the DACs (also known as CODECs) tend to be at least 16 bit or even higher, and capable of proper audio sampling frequencies, like 44100ksps and above.