ESPMegaPRO-v3-SDK/ESPMegaPRO-firmware/lib/ESPMegaPRO/AnalogCard.cpp

138 lines
3.4 KiB
C++

#include <AnalogCard.hpp>
#include "esp_log.h"
AnalogCard::AnalogCard() : dac0(DAC0_ADDRESS),
dac1(DAC1_ADDRESS),
dac2(DAC2_ADDRESS),
dac3(DAC3_ADDRESS),
analogInputBankA(),
analogInputBankB(),
dac_change_callbacks()
{
this->handler_count = 0;
}
void AnalogCard::dacWrite(uint8_t pin, uint16_t value)
{
ESP_LOGV("AnalogCard", "DAC Write: %d, %d", pin, value);
this->setDACState(pin, value > 0);
this->setDACValue(pin, value);
}
void AnalogCard::setDACState(uint8_t pin, bool state)
{
ESP_LOGD("AnalogCard", "Setting DAC state: %d, %d", pin, state);
this->dac_state[pin] = state;
this->sendDataToDAC(pin, this->dac_value[pin] * state);
for (const auto& callback : this->dac_change_callbacks)
{
callback.second(pin, state, this->dac_value[pin]);
}
}
void AnalogCard::setDACValue(uint8_t pin, uint16_t value)
{
ESP_LOGD("AnalogCard", "Setting DAC value: %d, %d", pin, value);
this->dac_value[pin] = value;
this->sendDataToDAC(pin, value * this->dac_state[pin]);
for (const auto& callback : this->dac_change_callbacks)
{
callback.second(pin, this->dac_state[pin], value);
}
}
uint16_t AnalogCard::getDACValue(uint8_t pin)
{
return this->dac_value[pin];
}
bool AnalogCard::getDACState(uint8_t pin)
{
return this->dac_state[pin];
}
void AnalogCard::sendDataToDAC(uint8_t pin, uint16_t value)
{
switch (pin)
{
case 0:
this->dac0.writeDAC(value);
break;
case 1:
this->dac1.writeDAC(value);
break;
case 2:
this->dac2.writeDAC(value);
break;
case 3:
this->dac3.writeDAC(value);
break;
}
}
uint16_t AnalogCard::analogRead(uint8_t pin)
{
if (pin >= 0 && pin <= 3)
{
return this->analogInputBankA.readADC_SingleEnded(pin);
}
else if (pin >= 4 && pin <= 7)
{
return this->analogInputBankB.readADC_SingleEnded(pin - 4);
}
return 65535;
}
bool AnalogCard::begin()
{
if (!this->dac0.begin())
{
ESP_LOGE("AnalogCard", "Card Analog ERROR: Failed to install DAC0");
return false;
}
if (!this->dac1.begin())
{
ESP_LOGE("AnalogCard", "Card Analog ERROR: Failed to install DAC1");
return false;
}
if (!this->dac2.begin())
{
ESP_LOGE("AnalogCard", "Card Analog ERROR: Failed to install DAC2");
return false;
}
if (!this->dac3.begin())
{
ESP_LOGE("AnalogCard", "Card Analog ERROR: Failed to install DAC3");
return false;
}
if (!this->analogInputBankA.begin())
{
ESP_LOGE("AnalogCard", "Card Analog ERROR: Failed to install analog input bank A");
return false;
}
if (!this->analogInputBankB.begin())
{
ESP_LOGE("AnalogCard", "Card Analog ERROR: Failed to install analog input bank B");
return false;
}
return true;
}
void AnalogCard::loop()
{
}
uint8_t AnalogCard::getType()
{
return CARD_TYPE_ANALOG;
}
uint8_t AnalogCard::registerDACChangeCallback(std::function<void(uint8_t, bool, uint16_t)> callback)
{
this->dac_change_callbacks[this->handler_count] = callback;
return this->handler_count++;
}
void AnalogCard::unregisterDACChangeCallback(uint8_t handler)
{
this->dac_change_callbacks.erase(handler);
}