Go Down

Topic: Wii nunchuck code (Read 2291 times) previous topic - next topic

Dan_68

Hi all,

Just new here and struggling to work out where to put this so if this needs to be in a different spot let me know.

I am working on the wii nunchuck code as from todbot. I have got it all working just trying to understand the code i understand most of it just not the bit where it grabs the least significant bits of the x,y,z axis.

  if ((nunchuck_buf[5] >> 2) & 1)
    accel_x_axis += 2;
  if ((nunchuck_buf[5] >> 3) & 1)
    accel_x_axis += 1;

I understand the >> is shift/move so it moved to the 3 bit in,
Why is it in a if statement to start with and also whats the & 1 for is that if its a 0 it makes it a 1 and vise versa.

Then why the et al of +=2 i understand what it does the += but whats it to here.

Thanks all . Hope someone can explain this to me.

markB

Dan_68
Looks like no-one wanted to help you.

I had to get my head around this as well, because some of the code examples actually misread the information, which contributed to some serious number jumping.

>> is a shift.
You need to think of 8 bits of data (1's or 0's). ie 11001100
if you >> 2 it becomes 00110011

when you &1 it does a bitwise comparison with 00000001 and the result in this case of the shifted data is 00000001 (or simply 1, or true)
(if you had done it before shifting the result would be 00000000)

So in reality they are actually only interested in checking if 2nd bit in the buffer is a one, and then adding the value the data at that position represents.
The same as the next line is checking the 3rd bit.
In my opinion the two values should be reversed, as according to the wiki link below bits 3 and 2 represent AX 1 and 0 respectively.
ie I believe it should be :-
  if ((nunchuck_buf[5] >> 2) & 1)
    accel_x_axis += 1;
  if ((nunchuck_buf[5] >> 3) & 1)
    accel_x_axis += 2;

i found some good info at http://wiibrew.org/wiki/Wiimote/Extension_Controllers#Nunchuk
and of course at http://www.arduino.cc/playground/Code/BitMath

As I said be careful as some code posted (earlier) is using the wrong bits to determine things, and ends up with strange results.

Mark

markB

Dan_68
Some time ago I posted this code for checking Nunchuk.
Not sure if it might help you or not.

Mark

http://arduino.cc/forum/index.php/topic,17716.0/topicseen.html

Go Up