#include <Arduino.h>
#include <SPI.h>
#include "DAC.h"

uint16_t calculateDACOutput(double voltage)
{
    return (uint16_t)(voltage * 4096 / DAC_VREF);
}

void init_DAC_SPI(SPISettings spi_settings, pin_size_t CS, double voltage)
{
    Serial.printf("Initializing DAC @ %.3fv...\r\n", voltage);
    uint16_t data = calculateDACOutput(voltage);
    digitalWrite(CS, LOW);
    SPI.beginTransaction(spi_settings);
    // set DAC settings
    SPI.transfer16(DAC_IN_BUFF | DAC_OUT_GAIN | DAC_OUT_EN | data);
    // stop transfer
    SPI.endTransaction();
    digitalWrite(CS, HIGH);
}
