I'm trying to make a simple project that lets someone control the RGB values of an RGB LED with a Wii Nunchuck. I just got a Nunchucky (a simple breakout board to use the Wiimote Nunchuck peripheral) today, along with an Arduino Mega, and wanted to test both out. I'm just reading the values of the X axis of the Nunchuck's joystick and mapping the values to 0-255. You can only control one value - either red, green, or blue - at a time, by pressing and holding a tact switch.
I'll include most of my code. I removed the redundant parts for the green and blue leads of the LED, which are exactly the same, with different respective variables for the button and LED pin.
#include "Wire.h"
#include "WiiChuck.h"
WiiChuck chuck = WiiChuck();
// pins for push buttons
const int redButton = 26;
// pins for color of RGB LED
const int redPin = 11;
int joyX = 0;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(redButton, INPUT);
Serial.begin(9600);
chuck.begin();
chuck.update();
}
void loop() {
int rBtnState = digitalRead(redButton);
if (rBtnState == HIGH) {
chuck.update();
joyX = map(chuck.readJoyX(), -103, 90, 0, 255);
setColor(redPin, joyX);
joyX = 0;
rBtnState = 0;
}
}
void setColor(int currentPin, int color)
{
//Serial.println(color);
analogWrite(currentPin, color);
}
The problem is, it only works when the second-to-last line of code (Serial.println(color);) is uncommented. With absolutely zero changes whatsoever to any other code in this sketch or wiring in my circuit, commenting the serial print line breaks it. Instead of writing the mapped value from the joystick, it just seems to use a value of 255, regardless of the actual value.
This might not be a big problem if my Mega didn't freeze and cease all processing after a couple seconds of using serial. It's not just that serial stops sending anything; the sketch stops completely and nothing will work at all. Still, I don't see why using the serial console would make something completely unrelated to serial work. The Nunchuck library uses I2C, but even if I leave Serial.begin(9600); it still doesn't work, which should make sense.
Is my Mega defective? Either I'm doing something horribly wrong, or something is wrong with the serial capabilities of my new Mega.
Thank you to anyone who can help me!