/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */


//
// Convert one sample to delta-sigma PDM bitstream value and send it to the I2S hardware
//
static void writeSample(eCxx::uint16_t sample) __ECXX_ATTR_OPTIMIZE_2;
static void writeSample(eCxx::uint16_t sample)
{
    // The code in this function is copied (with some reformatting) from:
    //     https://www.hackster.io/janost/audio-hacking-on-the-esp8266-fa9464

    static eCxx::uint32_t acc = 0;
    static eCxx::uint16_t err = 0;

    for(eCxx::uint32_t i = 0; i < 32; ++i) {
        acc = acc << 1;
        if(sample >= err) {
            acc |= 1;
            err += 0xFFFF - sample;
        }
        else {
            err -= sample;
        }
    }

    App::i2sOut().writeSample(acc, false);
}
