2

Okay, I've written a small piece of code for reading analog values from MCP3008 and it all works good I would say. But the problem is, the value changes depending on a frequency of which I'm reading them. Any ideas what could cause such behaviour?

Update: Here's my code. Maybe I did something wrong...

enum {
    MCP3008_RESOLUTION = 1024,
    MCP3008_CONFIG_LO = 0x80,
    MCP3008_CONFIG_HI = 0x01
};
uint16_t MCP3008::Read(uint8_t channel)
{
    if (channel > 7)
        throw "Out of range.";

    uint8_t writeBuffer[] = { MCP3008_CONFIG_LO, MCP3008_CONFIG_HI | (channel << 4), 0x00 };
    auto readBuffer = ref new Array<uint8_t>(3);

    _device->TransferFullDuplex(ref new Array<uint8_t>(writeBuffer, 3), readBuffer);

    uint16_t buf = readBuffer[2];
    buf += (readBuffer[1] & 0x03) << 8;
    return buf;
}

void MCP3008::CreateDevice(Platform::String ^ friendlyName, uint8_t chipSelectLine,
    Windows::Devices::Spi::SpiMode mode, uint32_t dataBitLength, uint32_t clockFrequency)
{
    Platform::String^ aqs;
    if (friendlyName)
        aqs = SpiDevice::GetDeviceSelector(friendlyName);
    else
        aqs = SpiDevice::GetDeviceSelector();

    auto dis = concurrency::create_task(
        DeviceInformation::FindAllAsync(aqs)).get();
    if (dis->Size < 1)
        throw "SPI Initialization failed. Could not find SPI controller.";

    auto id = dis->GetAt(0)->Id;

    auto settings = ref new Windows::Devices::Spi::SpiConnectionSettings(chipSelectLine);
    if (int(mode) != -1)
        settings->Mode = mode;
    if (dataBitLength)
        settings->DataBitLength = dataBitLength;
    if (clockFrequency)
        settings->ClockFrequency = clockFrequency;

    _device = concurrency::create_task(
        SpiDevice::FromIdAsync(id, settings)).get();

    if (!_device)
        throw "SPI Initialization failed. Device is already in use.";
}
  • What sensor(s) are you using? Can you add your code to your question? What do you mean the values are changing with the frequency? I would expect certain types of sensors to vary on every reading. – Steve Robillard Jul 5 '16 at 21:07
  • @SteveRobillard I've added the code. It's actually a voltage meter I'm building. Just a simple voltage divider and ADC. But when I'm reading the value 10 times per second it gives me 256 for example, but on the other side when I'm reading it 20 times per second it gives me 128. – Quest Jul 5 '16 at 21:10
  • Just out of curiosity what happens when you read it once or twice a second – Steve Robillard Jul 5 '16 at 21:17
  • What is with the ^ in this line? void MCP3008::CreateDevice(Platform::String ^ friendlyName, uint8_t chipSelectLine, – Steve Robillard Jul 5 '16 at 21:19
  • Gimme like 5 minutes I'll check that out! – Quest Jul 5 '16 at 21:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.