[Seeeduino XIAO] Piezo buzzer not working properly

this is code I wrote to operate a timer for activating a device
for some reason, the buzzer on pin 3 does not turn on when it's supposed to (I switched it to be on all of the time and it still doesn't work) and instead just beeps slightly at random times (possibly related to a cycle but I have now clue what it is

long timer = 300;
unsigned long prevTime = 0;
int red = 0;
int blue = 0;
int green = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(4, INPUT_PULLUP);
  pinMode(5, INPUT_PULLUP);
  pinMode(3, OUTPUT);
  SerialUSB.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  tone(3, 523);
  if (digitalRead(4) == 0) {
    timer += 300000;
  }
  if (digitalRead(5) == 0 && timer >= 0) {
    timer -= 300000;
    if (timer < 0) {
      timer = 0;
    }
  }
  timer -= millis() - prevTime;
  if (timer <= 1) {
    if (timer <= -300000) {
      digitalWrite(10, HIGH);
      delay(500);
      digitalWrite(10, LOW);
      timer = 0;
    }
  }
  prevTime = millis();
  analogWrite(9, red);
  analogWrite(7, blue);
  analogWrite(8, green);
  SerialUSB.println(timer);
  green = map(timer, -300000, 3600000, 255, 0);
  //red = map(timer, -300000, 3600000, 0, 255);
  //blue = (green + red)/2;
}

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