Buzzer not working correctly (code issues)

Hi,

I have a buzzer setup that is working correctly with another piece of code I've written as well as the example buzzer code. But it is not working with this one and I'm struggling. It starts off playing the melody correctly but veers off into really weird variations very quickly.

#include "pitches.h"

class Buzzer{
 
  // These maintain the current state
  int melodyState;                 // state of the melody
  unsigned long previousMillis;   // last time the melody changed state
  bool running;
 
  int buzzerPin;      // the number of the buzzer pin
  int melodySize;
  int* melodyPitches;       // use constants from pitches.h, 0 = silence
  int* melodyDurations;    // milliseconds
  
  // Constructor
  public:
  Buzzer(int pin, int size, int pitches[], int durations[]) {
    buzzerPin = pin;   

    melodySize = size;
    melodyPitches = new int[size];
    melodyPitches = pitches;
    melodyDurations = new int[size];
    melodyDurations = durations;
    
    melodyState = 0; 
    previousMillis = 0;
    running = false;
  }
 
  void Update() {
    // check to see if it's time to change the state of the buzzer
    unsigned long currentMillis = millis();

    if (!running) {
      return;
    }
     
    if (currentMillis - previousMillis >= melodyDurations[melodyState]) {
      noTone(buzzerPin);
      previousMillis = currentMillis;  // Remember the time

      // next state
      melodyState++;
      if (melodyState >= melodySize) {
        melodyState = 0;
      }

      // play the new state
      tone(buzzerPin, melodyPitches[melodyState], melodyDurations[melodyState]);
    }
  }

  void StopRunning() {
    running = false;
    noTone(buzzerPin);
    melodyState = 0;
  }

  void StartRunning() {
    if (!running) {
      running = true;
      previousMillis = millis();
    }
  }

};

In your constructor you do this:

    melodyPitches = new int[size];  // allocate a new vector of integers
    melodyPitches = pitches; // throw that away immediately and set melodyPitches to point to the argument pitches.
    melodyDurations = new int[size];  // same pattern.
    melodyDurations = durations;

You mean to copy the data into the locally created vectors I think. The way you do it means that if the
caller uses a stack based vector of int it will be overwritten while the Buzzer class is using it.

Hi thanks for the reply.

I am not sure what you mean. The arguments are arrays of int, not vectors. What would be a good way of writing the assignments for melodyPitches and melodyDurations?

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