Arduino Tone Generator
This method is to generate a simple square wave tone using Arduino.
Connect the output pin 9 to a buzzer or speaker.
Code 1
void setup() {
pinMode(9, OUTPUT);
tone(9,260);
}
void loop() {
}
In the above program, the tone() function generates a square wave of frequency 260HZ with a duty cycle of 50%. Tone() function can generate only square waves of fixed 50% duty cycle.
The output pin and frequency can be varied by changing the values in the tone function.
tone(pin, frequency)
The frequency value should be between minimum 31HZ and maximum 65535HZ; the minimum and maximum frequency values that can be produced by the AVR boards.
An optional duration value can be added if the tone required only to ON for a short period of time.
tone(pin, frequency, duration)
Code 2
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
tone(9,260,500);
delay(1000);
}
Here the tone will be ON only for 500ms and OFFs, then repeats function after a 1s delay in OFF state which generates a beep-beep sound; half-second beep with a one-second gap between each beep.
If the function tone is used without a duration value then the function noTone() should be called to turn OFF the tone. Otherwise, it continues the tone generation.
Code 3
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
tone(9,260);
delay(500);
noTone(9);
delay(500);
}
Arduino half-hour Beeping Timer
The Arduino beeping timer generates a beep tone with an interval of 30 minutes between each beeping sound. The beep sound has a duration of 3 seconds and a frequency of 1500Hz. Instead of the delay function, the code uses millis() function to obtain the time. So between each tone, additional codes can be added to execute in the 30 minutes time interval.
Beeping Timer code
const int output_pin = 9;
int frequency = 1500, duration = 3000;
unsigned long delays = 0, times=0;
void setup() {
pinMode(output_pin, OUTPUT);
/* 30 minutes delay
30mnts x 60 = 1800 sec
1800sec = (1800*1000) ms */
delays = 1800000;
}
void loop() {
times = millis();
tone(output_pin, frequency, duration);
while(millis() < times + delays ){
// Other codes to run during the 30 minutes.
}
}