0

I am using MCP3021 for my ambient light sensor. I am getting bytes successfully on reading but unable to process them properly. I am using MPLABX as my IDE.

My code is as follows,

UINT32 res, val, upper, lower;
UINT8  i2cbyte[10];  // I2C values get stored in this one...

// example values : i2cbyte[0]=0x0e, i2cbyte[1]=0x32
upper = i2cbyte[0];  
lower = i2cbyte[1];

val = ( upper << 6) + (lower >> 2);
//after this value is: upper = 0x00000380, lower = 0x01000032 & val is same as lower

No idea why variable lower has a 01 in it.Sometimes value is 0x00cccc32.

res = upper + lower;  // res = 0x0000320E
res = (3.3/1024) * val;

Can someone help me with this?

Abin
  • 87
  • 1
  • 9
  • 2
    If the value of `i2cbyte[1]` (and therefore `lower` too) is `0x32` then `lower >> 2` should be `0x0a`. How do you check these values? In a debugger? By "printing" (or sending over a serial line etc) the values? – Some programmer dude Dec 15 '16 at 12:50
  • 1
    Well as the [datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/21805B.pdf) on page 17 describes the data, it looks like you are decoding it properly (although I would use a bitwise or `|` when combining bytes). What microcontroller are you using ? And what is the code you are using to read the I2C bytes ? – frostblue Dec 15 '16 at 13:04
  • @Someprogrammerdude in a debugger. – Abin Dec 15 '16 at 13:05
  • @LudaOtaku I am using PIC32MX. – Abin Dec 15 '16 at 13:06
  • 1
    @Someprogrammerdude, I believe you mean that `0x32 >> 2 == 0x0c` (not `0x0a`). – John Bollinger Dec 15 '16 at 14:07
  • @JohnBollinger Yes I do. :) – Some programmer dude Dec 15 '16 at 14:08
  • 1
    @Abin, supposing that `UINT8` is an unsigned 8-bit integer type and that `UINT32` is an unsigned 32-bit integer type, about all we can say from strictly a C perspective is that the behavior you describe is non-conforming. Specifically, the result of evaluating the last statement does not conform, both in that `upper` and `lower` are modified, and in that `val` receives the value it does. It may be that your C implementation is buggy, but I think it's more likely that the code you've presented is not characteristic of the program that's actually running. – John Bollinger Dec 15 '16 at 14:18

1 Answers1

0

How do you check these values? – Some programmer dude

in a debugger.

You can't take the values shown by the debugger for granted in the sense that a variable could only assume values which would occur in an abstract machine. (An optimizing C compiler may do all kinds of rearrangements to the code, including using unneeded parts of registers for other purposes.) You can rely only on the observable behavior.

That said, it may as well be that your program (which you actually didn't show) indeed overwrites parts of variables, e. g. by overflowing i2cbyte[10] when reading data.

Community
  • 1
  • 1
Armali
  • 18,255
  • 14
  • 57
  • 171