Can somebody help me with fixing the errors in this code?

So, I am coding an arduino nano for this lightsaber i am making. However, there seems to be far too many errors in this code. Can you guys help me fix them?

#include <Wire.h>
#include <Adafruit_NeoPixel.h>
#include <SD.h>
#include <TMRpcm.h>
#include <MPU6050.h>

#define BUTTON_PIN 2               // Pin for the button
#define NUM_PIXELS 80              // Number of pixels in each LED strip
#define LED_PIN 6                  // Pin for the RGB LED strips (shared for 3 strips)
#define SD_PIN 10                  // Pin for SD card
#define SPEAKER_PIN 9              // Pin for speaker output
#define I2C_SDA 21                 // I2C SDA Pin
#define I2C_SCL 22                 // I2C SCL Pin

// Declare the NeoPixel strip
Adafruit_NeoPixel strip(NUM_PIXELS, LED_PIN, NEO_GRB + NEO_KHZ800);

// Set up the TMRpcm for sound playback from the microSD card
TMRpcm audioPlayer;

// Set up MPU6050
MPU6050 mpu;

int buttonState = 0;
int lastButtonState = 0;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;

bool saberOn = false;
bool clashMode = false;
bool tipDragMode = false;

void setup() {
  // Initialize serial communication
  Serial.begin(9600);

  // Initialize the LED strip
  strip.begin();
  strip.show();  // Initialize all pixels to 'off'

  // Initialize the microSD card
  if (!SD.begin(SD_PIN)) {
    Serial.println("SD Card failed or not present.");
    while (1);  // Stop execution if SD card fails
  }

  // Initialize the audio player
  audioPlayer.attach(SPEAKER_PIN);
  audioPlayer.setVolume(5); // Set volume (0 to 7)

  // Initialize the MPU6050 sensor
  Wire.begin(I2C_SDA, I2C_SCL);
  mpu.initialize();

  // Initialize button pin
  pinMode(BUTTON_PIN, INPUT_PULLUP);

  Serial.println("Setup complete. Lightsaber is ready!");
}

void loop() {
  // Read button state with debounce logic
  int reading = digitalRead(BUTTON_PIN);
  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      if (buttonState == LOW) {
        handleButtonPress();
      }
    }
  }
  lastButtonState = reading;

  // Handle motion (impact, swing, tip drag)
  handleMotion();
}

// Handle different button press behaviors
void handleButtonPress() {
  if (!saberOn) {
    turnOnSaber();
  } else if (tipDragMode) {
    tipDragEnd();
  } else {
    randomBlasterShot();
  }
}

// Turn on the saber with effect and sound
void turnOnSaber() {
  saberOn = true;

  // Light up the LEDs from bottom to top as blue, 3 pixels per second
  for (int i = 0; i < NUM_PIXELS; i++) {
    for (int j = 0; j < 3; j++) {
      int pixelIndex = i + j;
      if (pixelIndex < NUM_PIXELS) {
        strip.setPixelColor(pixelIndex, strip.Color(0, 0, 255)); // Blue color
      }
    }
    strip.show();
    delay(333); // Delay to light up 3 pixels per second
  }

  // Play "Turn on" sound
  audioPlayer.play("0001.wav");  // Assuming sound file for 'Turn On' is 0001.wav

  // Start playing normal sound
  audioPlayer.play("0002.wav");  // Normal sound (0002.wav)
}

// Turn off the saber with effect and sound (3 pixels per second from top to bottom)
void turnOffSaber() {
  saberOn = false;

  // Turn off the LEDs from top to bottom as blue, 3 pixels per second
  for (int i = NUM_PIXELS - 1; i >= 0; i--) {
    for (int j = 0; j < 3; j++) {
      int pixelIndex = i - j;
      if (pixelIndex >= 0) {
        strip.setPixelColor(pixelIndex, strip.Color(0, 0, 0)); // Off (turning off)
      }
    }
    strip.show();
    delay(333); // Delay to turn off 3 pixels per second
  }

  // Play "Turn off" sound
  audioPlayer.play("0008.wav");  // Assuming sound file for 'Turn Off' is 0008.wav
}

// Handle motion (impact, swing, tip drag)
void handleMotion() {
  // Read accelerometer data
  Vector rawAccel = mpu.getAcceleration();
  Vector rawGyro = mpu.getRotation();

  // Check for impact (force detection)
  if (abs(rawAccel.x) > 15000 || abs(rawAccel.y) > 15000 || abs(rawAccel.z) > 15000) {
    handleImpact();
  }

  // Check for swing (fast or slow)
  if (rawGyro.x > 500 || rawGyro.y > 500 || rawGyro.z > 500) {
    handleSwing(rawGyro);
  }

  // Handle tip drag (sensor-based detection for downward and motion)
  if (rawAccel.z < -7000) { // Threshold for pointing down
    if (buttonState == LOW && !tipDragMode) {  // Button pressed while pointing down
      tipDragMode = true;
      tipDragStart();
    }
  }
}

// Impact behavior (random 3 pixels turn white and play clash sound)
void handleImpact() {
  if (tipDragMode) {
    return;  // Don't trigger clash sound if tip drag is active
  }

  clashMode = true;

  // Set 3 random pixels to white for 1 second
  for (int i = 0; i < 3; i++) {
    int pixelIndex = random(NUM_PIXELS);
    strip.setPixelColor(pixelIndex, strip.Color(255, 255, 255)); // White color
  }
  strip.show();
  delay(1000); // Keep them white for 1 second

  // Play random clash sound (from 5 possible clash sounds)
  int soundIndex = random(1, 6); // Random number between 1 and 5
  audioPlayer.play("clash" + String(soundIndex) + ".wav");  // Clash sound (e.g., clash1.wav, clash2.wav)

  // Reset to normal sound after clash
  audioPlayer.play("0002.wav");  // Normal sound
}

// Handle swing detection (fast and slow)
void handleSwing(Vector rawGyro) {
  if (rawGyro.x > 1000 || rawGyro.y > 1000 || rawGyro.z > 1000) {
    // Fast swing detected
    audioPlayer.play("0004.wav");  // Fast swing sound (0004.wav)
  } else {
    // Slow swing detected
    audioPlayer.play("0005.wav");  // Slow swing sound (0005.wav)
  }

  // Reset to normal sound
  audioPlayer.play("0002.wav");  // Normal sound
}

// Random blaster shot behavior (button press when saber is on)
void randomBlasterShot() {
  // Set 3 random pixels to white and play blaster sound
  for (int i = 0; i < 3; i++) {
    int pixelIndex = random(NUM_PIXELS);
    strip.setPixelColor(pixelIndex, strip.Color(255, 255, 255)); // White color
  }
  strip.show();
  delay(1000); // Keep them white for 1 second

  // Play blaster shot sound
  audioPlayer.play("0006.wav");  // Blaster sound (0006.wav)

  // Reset to normal sound
  audioPlayer.play("0002.wav");  // Normal sound
}

// Tip drag behavior (button press while pointing downwards)
void tipDragStart() {
  // Turn the top pixels white
  for (int i = 0; i < 10; i++) { // Top 10 pixels for tip drag
    strip.setPixelColor(i, strip.Color(255, 255, 255)); // White color
  }
  strip.show();

  // Play tip drag sound
  audioPlayer.play("0007.wav");  // Tip drag sound (0007.wav)
}

void tipDragEnd() {
  // Reset to normal sound and LEDs
  for (int i = 0; i < NUM_PIXELS; i++) {
    strip.setPixelColor(i, strip.Color(0, 0, 255)); // Blue color
  }
  strip.show();

  // Play normal sound again
  audioPlayer.play("0002.wav");  // Normal sound
}

How do you know there are errors?

1 Like

I don't see any error log in code tags.

Which board are you compiling for?

The first two errors from the long list when I compile for a Mega:

C:\Users\bugge\AppData\Local\Temp\.arduinoIDE-unsaved2025115-19016-1my0cag.yatf\sketch_feb15a\sketch_feb15a.ino:217:18: error: variable or field 'handleSwing' declared void
 void handleSwing(Vector rawGyro)
                  ^~~~~~
C:\Users\bugge\AppData\Local\Temp\.arduinoIDE-unsaved2025115-19016-1my0cag.yatf\sketch_feb15a\sketch_feb15a.ino:217:18: error: 'Vector' was not declared in this scope
C:\Users\bugge\AppData\Local\Temp\.arduinoIDE-unsaved2025115-19016-1my0cag.yatf\sketch_feb15a\sketch_feb15a.ino:217:18: note: suggested alternative: 'perror'
 void handleSwing(Vector rawGyro)
                  ^~~~~~
                  perror

I suspect that the second one is the important one with 'Vector' was not declared in this scope. Which brings the question if you wrote this code or copied it from somewhere. If you wrote it, where is Vector defined, if you copied it, from where.

Hi @sterretje ,

haven't found the declaration of Vector so far but quite likely the specific library where it is used

https://github.com/jarzebski/Arduino-MPU6050/blob/dev/MPU6050.cpp

As far as I can see (smartphone;-) ) it's not the standard MPU6050 lib ...

Hope it's of assistance...
Greetings
ec2021

Edit: It's in the .h file

I assume that the wrong lib has been downloaded...

Thanks ec2021, that's resulting in other errors :wink:

C:\Users\bugge\AppData\Local\Temp\.arduinoIDE-unsaved2025115-19016-1my0cag.yatf\sketch_feb15a\sketch_feb15a.ino:56:7: error: 'class MPU6050' has no member named 'initialize'
   56 |   mpu.initialize();

When compiling for a Mega, there is also this error (which disappears when compoiling for a ESP32 Dev Module.

C:\Users\bugge\AppData\Local\Temp\.arduinoIDE-unsaved2025115-19016-1my0cag.yatf\sketch_feb15a\sketch_feb15a.ino:55:30: error: no matching function for call to 'TwoWire::begin(int, int)'
   Wire.begin(I2C_SDA, I2C_SCL);

And something about the TMRpcm library

C:\Users\bugge\AppData\Local\Temp\.arduinoIDE-unsaved2025115-19016-1my0cag.yatf\sketch_feb15a\sketch_feb15a.ino:51:15: error: 'class TMRpcm' has no member named 'attach'
   audioPlayer.attach(SPEAKER_PIN);

I'm going to wait till maxkim131031 provides feedback

  1. Which board he's compiling for?
  2. Which libraries and versions of all libraries and where we can find those libraries.
  3. How the sketch was written?
    • From scratch by OP?
      Were all individual functionalities tested?
    • Copied from the web?
      Link please.

There might be more.

1 Like

I am connecting this with an Arduino nano.
I knew there were errors because when I tried to verify it in Arduino ide, it kept pointing out errors.
Also I asked ChatGPT to make the code and I made a few adjustments
In addition I am a newbie to Arduino coding so please explain things in easy words.

Easy Words:
ChatGPT-generated code tends to be crap. Most people here won't help you fix code generated by a robot.

So did the ChatGPT code compile? Or did your adjustments cause the problems? If tge latter, what did you change?

The ChatGPT code did not compile, and the few adjustments I made were like changing blue to red and fixing some errors. I think the ChatGPT one and my adjustments switched it.
Are there any reliable Arduino code generators that I can use for this project?

I don't know but I doubt it. But I would suggest that you look at examples for the involved libraries, study them and learn from them and after that write your own sketch.

You can always ask chatGPT what is wrong :smiley:

1 Like

You should change over to describe in normal words
what exact microcontroller
what buttons, switches
what sensors
how many leds of what exact type RGB or RGBW
what lighting pattern your leds shall do
depending on what button-presses, sensor-readings etc.

This description will give a clear and detailed picture of what you want to do.

If you have posted such a description the user here will help.
Without such a detailed description most of it is guessing.

This is a snake bites into its own tail problem:
For making any AI-code-generator generate code that compiles and code that does what you want you have to have knowledge about coding to be able to write a sufficient precise description. And if your code is medium complex it will still take 10 to 20 iterations to make any AI generate functional code.

Though people who don't know how to write code try to make an AI write the code and fail because they don't know how to code. They don't know what is important in the description = the prompt for the AI. You would have to know about coding to be able to write down this prompt.

conclusion: learn coding yourself with the help of the users here in the forum.

1 Like

Ask for a connection and wiring diagram too.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.