I2C ADC library

I am trying to make a library for the MAX1361 ADC but when running the code below I get random output I know that the ADC is working because it shows up on an I2C scan. I am configuring the ADC to read from two of the four channels I think the problem is with how I am reading the values, I have attached an image of a diagram of how reading is suppose to happen any ideas what I'm doing wrong?

#include <Wire.h>
#include "windVane.h"

bool ADC::begin(){
    Wire.begin();
    Wire.beginTransmission(ADC_ADDR);
    Wire.write(0x03);//config byte
    Wire.write(0x8A);//setup byte
    Wire.endTransmission();
    return true;
}

float ADC::read(){
    static int16_t vals[2];
    Wire.requestFrom(ADC_ADDR, 4, true);
    vals[0] = (Wire.read() | Wire.read() << 8) & 0b0000001111111111;
    vals[1] = (Wire.read() | Wire.read() << 8) & 0b0000001111111111;
    Particle.publish("1", String(vals[0]));
    Particle.publish("1", String(vals[1]));
    return atan2(vals[0], vals[1]) * (180/3.14159);
}

It looks like the wire format is MSB0 MSB1 LSB0 LSB1 but your code is assuming that the order is LSB0 MSB0 LSB1 MSB1. I think it should be something like this, unless I'm reading it incorrectly:

vals[0] = Wire.read() << 8;
vals[1] = Wire.read() << 8;
vals[0] |= Wire.read();
vals[1] |= Wire.read();

so I tried the changes to the code and I'm getting this error: expected primary-expression before '|' token and expected primary-expression before '=' token
(the error repeats with the second value)

vals[0] = Wire.read() << 8;
vals[1] = Wire.read() << 8;
vals[0] | = Wire.read() & 0b0000001111111111;
vals[1] | = Wire.read() & 0b0000001111111111;

There's no space between | and =. It's the bitwise or operator |=.

Also if you really need to mask off the lower 10 bits, and discard the high bits, you need to do it this way; you can't have it in the bitwise or code.

vals[0] &= 0b0000001111111111;
vals[1] &= 0b0000001111111111;
1 Like

by the way the reason I'm masking the first six bits is that according to the datasheet
"The result is transmitted in 2 bytes. The 1st byte consists of a leading 1 followed by a 2-bit binary channel
address tag, a 12/10 bit flag (0 for the MAX1361/
MAX1362), 2 bits of 1s, the first 2 bits of the data result,
and the expected ACK from the master." and therefore I want to remove all but the last two bits

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.