typestar

tone in Arduino

Drive a piezo at a frequency; noTone silences it.

// tone drives a piezo at a frequency; noTone silences the pin.
const int BUZZER_PIN = 8;
const int ALERT_HZ[] = {880, 988, 1047};

void setup() {
  pinMode(BUZZER_PIN, OUTPUT);
}

void loop() {
  // Rising three-note alert, then two seconds of quiet.
  for (int i = 0; i < 3; i++) {
    tone(BUZZER_PIN, ALERT_HZ[i]);
    delay(180);
  }
  noTone(BUZZER_PIN);
  delay(2000);
}

How it works

  1. tone(pin, hz) starts a square wave at the frequency.
  2. The array holds a rising three-note alert.
  3. noTone releases the pin for two seconds of quiet.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
357
Tokens
83
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 2 of 3 in Peripherals, step 23 of 27 in Language basics.

← Previous Next →