Program Listing for File mcp3x0x.cpp
↰ Return to documentation for file (src/mcp3x0x.cpp
)
#include "mcp3x0x/mcp3x0x.hh"
using iplo::MCP3X0X;
std::int16_t MCP3X0X::readAnalogValue(std::uint8_t channel, bool single) {
if (channel > _channels) {
return 0;
}
std::uint8_t txData[3] = {0, 0, 0};
std::uint8_t bytes = buildRequest(channel, single, txData);
std::uint8_t rxData[3];
const auto bytesTransferred = _spi.xfer(txData, sizeof(txData), rxData, sizeof(rxData));
if (bytesTransferred < 0 || bytesTransferred != bytes) {
return -1;
}
if (bytes == 2) {
return (256 * rxData[0] + rxData[1]) & _maxValue;
}
return (256 * rxData[1] + rxData[2]) & _maxValue;
}
MCP3X0X::MCP3X0X(SPI& spi) : _spi(spi) {}
std::int16_t MCP3X0X::analogRead(std::uint8_t channel) {
if (channel >= _channels) {
return 0;
}
return readAnalogValue(channel, true);
}
std::int16_t MCP3X0X::differentialRead(std::uint8_t channel) {
if (channel >= _channels) {
return 0;
}
return readAnalogValue(channel, false);
}
std::int16_t MCP3X0X::deltaRead(std::uint8_t channel) {
if (channel >= _channels)
return 0;
const auto firstValue = differentialRead(channel & 0xFE);
const auto secondValue = (firstValue > 0) ? 0 : differentialRead(channel | 0x01);
if (channel & 0x01) {
return secondValue - firstValue;
}
return firstValue - secondValue;
}
std::uint8_t MCP3X0X::channels() {
return _channels;
}