Help me find a problem with my code

This code is supposed to wait 10 seconds and than play a simple tune. i dont include the pithces.h file here. Insted of doing what I want my arduino just plays this tune over and over again from the power on no matter what. I tried a few things but i just cant get it to work.

const int ledpin = 2;
const int speakpin = 3;
int runtime;
int melody1[] = {NOTE_G4, NOTE_D4, NOTE_G4, 0, };
int dur1 [] = {4, 2, 4};
void setup() {
  Serial.begin(9600);
  pinMode(ledpin, OUTPUT);
  pinMode(speakpin, OUTPUT);
  runtime = 0;
}

void loop() {
  unsigned long runtime = millis();
  if (runtime = 10000) {
    
    tone(speakpin, NOTE_G4);
    ;
    delay(500);
    tone(speakpin, NOTE_D4);
    
    delay(250);
    tone(speakpin, NOTE_G4);
    
    delay(250);
    
    noTone(speakpin);
    
  }

Welcome to the forum

    if (runtime = 10000)

Whoops !
That sets runtime to 10000 instead of comparing it to 10000

1 Like

Oh well that`s a rookie mistake. Thanks guys! Also that response was blazing fast! :smile:

Add a delay(10000) to the end of setup()

When you are ready to do other things at the same time, we can help you ditch the delays and work with time differently.

Working with time in unsigned long variables (to start with) and millis() or micros(),... elapsed time always equals end time minus start time

What delay() does is to allow Nothing Else Can Run During Delay.
That means you can have a stop button or led to blink, etc, that a delay() will block.
If you change the dealys to "timer-code", you can add buttons, leds and etc, to take your sketch beyond what it is now.

What you have now though is almost perfect to learn how! It is simple enough to not distract from learning how!

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