Adding an alarm is the easiest hardware modification for your Arduino Clock Project. You only need to attach the piezoelectric sounder. With that added, you simply create a function to play the alarm. Add the following code to the bottom of your Arduino sketch:

```void soundAlarm() {
float alarmFrequency=1400; // The value for the alarm tone in Hz
float period = (1.0 / alarmFrequency) * 1000000;
long beepDuration=250000; // the time in microseconds (0.25 seconds)
long elapsedTime = 0;
while (elapsedTime < beepDuration) {
digitalWrite(piezoPin,HIGH);
delayMicroseconds(period / 2);
digitalWrite(piezoPin, LOW);
delayMicroseconds(period / 2);
elapsedTime += (period);
}
digitalWrite(piezoPin, LOW);
delayMicroseconds(beepDuration);
// Listen for either button to be pressed and if so, turn off the alarm
if (hrs==HIGH || mins==HIGH){
alarm=false;
}
}```

This code uses the standard formula to obtain the period of a frequency; the period is the duration of a single cycle in a repeating event and is the reciprocal of the frequency. You specify the frequency of your alarm tone in Hertz (Hz) and assign it to the float variable alarmFrequency.

Your alarm will alternate between playing a tone at this frequency.

Two long integers, beepDuration and elapsedTime, store the elapsed time the tone has been playing and the duration that you want it to play. The while loop uses these to limit the time the note is played to 0.25 seconds (beepduration).

With the period calculated, you use this value to rapidly write HIGH and LOW values to the piezoPin. One cycle includes both on and off times, so the amount of time to write the pin HIGH and LOW is half the total period. This is written to the digital pins using:

```digitalWrite(piezoPin,HIGH);
delayMicroseconds(period / 2);
digitalWrite(piezoPin,LOW);
delayMicroseconds(period / 2);```

The delayMicroseconds() function is the shortest amount of time you can delay the Arduino, and is needed for generating a tone. After the tone has been played, the following two lines create silence for the same duration, 0.25 seconds, by holding the piezoPin LOW:

```digitalWrite(piezoPin, LOW);
delayMicroseconds(beepDuration);```

The very last thing to do is provide a way to silence the alarm, if you press either of the buttons. The local integers, hrs and mins, store the value of the buttons used to program the alarm. If the hours button or the minutes button goes HIGH because the button was pressed, the alarm condition is set to false. The vertical bars | | indicate a logical OR evaluation:

```int hrs=digitalRead(incrementAlarmHrsPin);