nRF52840 turns off after 11772 iterations of the tone() function

I’m having a problem with an nRF52840 which I want to use as a motion-based alarm with a buzzer and the IMU. I wrote the two following barebones programs:

//Alternating Alarm

int buzzerPin = D0;
int iterations = 0;

void setup() {
  Serial.begin(9600);
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  tone(buzzerPin, 4250);
  delay(125);
  tone(buzzerPin, 3750);
  delay(125);
  tone(buzzerPin, 4250);
  delay(125);
  tone(buzzerPin, 3750);
  delay(125);
  tone(buzzerPin, 4250);
  delay(125);
  tone(buzzerPin, 3750);
  delay(125);
  tone(buzzerPin, 4250);
  delay(125);
  tone(buzzerPin, 3750);
  delay(125);
  tone(buzzerPin, 4250);
  delay(125);

  Serial.print("Iterations: ");
  Serial.println(iterations += 9);

  noTone(buzzerPin);
  delay(500);
}

//Sine-wave Alarm

#include <math.h>

int buzzerPin = D0;
int iterations = 0;

void setup() {
  Serial.begin(9600);
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  for(float i = 0; i < M_PI * 2; i += M_PI / 1024) {
    tone(buzzerPin, 4000 - (1000 * sin(i)));
    delay(2);
    Serial.print("Iterations: ");
    Serial.println(iterations++);
  }
  noTone(buzzerPin);
  delay(500);
}

In both cases, the board will run until it hits exactly 11772 iterations and then it quits (see below for serial output at the moment it stops working). This number of 11772 is true for both programs above, and with the sine-wave alarm it’s of course reached faster because the individual tones are much shorter.

I assume it’s something to do with a watchdog timer, but I couldn’t find any documentation on how to feed or reset the watchdog on this board.

Thanks!

#include <Adafruit_TinyUSB.h> // for Serial.print()

Please try adding this line.
I tried both of your sketches, and they work without any issues. They didn’t stop at 11772.

1 Like