tags:

views:

388

answers:

3

I'm trying to take a 16 bit unsigned integer from a structure, mask the first 8 bits of it, and use it as an index to an array with the function analogWrite which takes the output pin on the Arduino and the output byte as arguments. The code in question looks something like this: analogWrite(outputPin, my_array[myStructure->data & 0xFF00 >> 8]);

Unfortunately, this code doesn't work. I always get zero as an output. Any ideas?

+3  A: 

I suspect operator precedence. Try:

analogWrite(outputPin, my_array[(myStructure->data & 0xFF00) >> 8]);
Kim Gräsman
A: 

Looking at a precedence table for C you do the following:

  1. Get data from myStructure
  2. Right-shift 0xFF00 8 steps
  3. Bit-wise and it with data

    Use more rows or parenthesis!

Key
+5  A: 

Operator precedence.

This:

myStructure->data & 0xFF00 >> 8

Is equivalent to:

myStructure->data & (0xFF00 >> 8)

But you want:

(myStructure->data & 0xFF00) >> 8
Tim Sylvester
Key
My microcontroller outputs sure have voltage on the pins now! Thanks!
Bitrex
The precedence of -> is the highest possible in C, so you never need parentheses around it.
starblue
starblue: Yes, but it shares the highest position with others, with left-to-right associativity.
Key