Subscribe via RSS
16Feb/107

Wii Nunchuck + Arduino Mega + Model Railway = Fun

Well, it had to happen... I bought the header/adapter from here and then, after a little rewiring to fit the Arduino Mega, got the Wii Nunchuck reporting data to my Arduino. Note that this has been done already in multiple places:



If you have an Arduino Mega, then make sure you have the Negative pin to GND, the Positive to 3.3v, the "d"/"data" pin to SDA20 and the "c"/"clock" pin to SCL 21.

You can then use this code to get the little train moving:

#include <Wire.h>
#include "nunchuck_funcs.h"
#define PWM_INPUT_PIN_1         2
#define PWM_INPUT_PIN_2         3
#define PWM_ENABLE_PIN_1        7
int throttle = 0;
int loop_cnt=0;
void setup() {
  Serial.begin(19200);
  nunchuck_setpowerpins();
  nunchuck_init(); // send the initilization handshake
}
void loop() {
  if( loop_cnt > 100 ) { // every 100 msecs get new data
    loop_cnt = 0;           
    nunchuck_get_data();
  }
  loop_cnt++;
  throttle = nunchuck_joyx() - 127;
  if (throttle < 10 && throttle > -10) throttle = 0;
  UpdateTrackPower();
}
void UpdateTrackPower() {
  if (throttle == 0) {
    digitalWrite(PWM_INPUT_PIN_1, LOW);
    digitalWrite(PWM_INPUT_PIN_2, LOW);
  } else {
    if (throttle > 0) {
      digitalWrite(PWM_INPUT_PIN_1, HIGH);
      digitalWrite(PWM_INPUT_PIN_2, LOW);
    } else if (throttle < 0) {
      digitalWrite(PWM_INPUT_PIN_1, LOW);
      digitalWrite(PWM_INPUT_PIN_2, HIGH);
    }
  }
  analogWrite(PWM_ENABLE_PIN_1, abs(throttle));
}

Note that you need to have the L298 Motor controller from the previous post connected to get power to tracks!

Now I just need to think of a cool way to use the buttons on this controller. Currently I just have the top joystick controlling the train on the X axis with center being stopped.

Comments (7) Trackbacks (1)
  1. This looks like a fun way to do it. You could use the button as an independent brake (independent from the throttle, I mean, not from the linked airbrakes ;) Is the button pressure sensitive?

    • Don, the buttons aren’t pressure sensitive unfortunately… Although the trigger on the other part of the Wii Remote is pressure sensitive. It would require bluetooth communications though (which is also possible! :))

    • I’d seen this on eBay for quite a bit of money (but they came with the game too.) Actually, I’ve just looked again… they plug in to the Wii Remote as this nunchuck does! Which means they’d be directly compatible with this setup!
      Please send me US$125 and I’ll show you how well it works :)

  2. Have you thought of using the Y axis for acceleration / braking?

    • Dave,
      After proving that this would work, I haven’t done any further work on it. This is a good idea though; once I’ve got the current track sensors going and have done a bit more scenery I will get back to this.
      Steven.


Leave a comment


*