Saturday, November 30, 2013

Nunchuk Arduino Coding

The code to take advantage of the Nunchuk information was all pulled from the Internet in the form of an Arduino library, and then a sample code was edited for our uses.

/*
* WiiChuckDemo --
*
* 2008 Tod E. Kurt, http://thingm.com/
*
*/
#include <Wire.h>
#include "nunchuck_funcs.h"
#include <Servo.h>
int loop_cnt=0;
Servo myservo;
byte accx,accy,zbut,cbut;
int ledPin = 13;
int valuex;
void setup()
{
Serial.begin(19200);
nunchuck_setpowerpins();
nunchuck_init(); // send the initilization handshake
Serial.print("WiiChuckDemo ready\n");
myservo.attach(9);
}
void loop()
{
if( loop_cnt > 100 ) { // every 100 msecs get new data
loop_cnt = 0;
nunchuck_get_data();
accx = nunchuck_accelx(); // ranges from approx 70 - 182
accy = nunchuck_accely(); // ranges from approx 65 - 173
zbut = nunchuck_zbutton();
cbut = nunchuck_cbutton();
Serial.print("accx: "); Serial.print((byte)accx,DEC);
Serial.print("\taccy: "); Serial.print((byte)accy,DEC);
Serial.print("\tzbut: "); Serial.print((byte)zbut,DEC);
Serial.print("\tcbut: "); Serial.println((byte)cbut,DEC);
valuex = accx;
map(valuex, 70, 182, 50, 120);
myservo.write(valuex);
}
loop_cnt++;
delay(1);
}

The code in this example was what was used to test the different axes on the Nunchuk. The final code will just take advantage of two axes, and the buttons. While the actual coding for using the button presses has not been coded, it has been planned and written on paper to get the step by step coding planned.


 


The thought process behind this code is that when the button is pressed it will keep the last value of the servo position stored, and use that as a reference value to go into 'fine tuning mode'. In this mode, the angles will be mapped to a small range that involves negative numbers. This will allow it to go clockwise and counter clockwise in small increments around the last known position. When the button is released it will go back to using the normal servo position variables.


--
Andrew Southworth

No comments:

Post a Comment