Arduino piezo tone

Piezo Transducer with Arduino

This example generates a tone via a piezo transducer connected across pins D8 & D9 of a ‘duino UNO.

/* Generate a tone for a piezo transducer.
The piezo is connected between two ports, one high, one low, which flip output
states every half cycle. This doubles the amplitude of the square wave signal
across the transducer.

const int sounder_A = 8;
const int sounder_B = 9;

void setup()
pinMode(sounder_A, OUTPUT); //connect the piezo across two ports
pinMode(sounder_B, OUTPUT); //to double the signal amplitude.

// Call function with parameters - duration in mSecs, freq in Hz
void beep(long duration, int freq) {
    duration *= 1000;   //convert the duration to microseconds
    int period = (1.0 / freq) * 1000000; //get the oscillation period in microseconds
    long elapsed_time = 0;
    while (elapsed_time < duration) {
        digitalWrite(sounder_A, HIGH); //Piezo ports go hi/lo then lo/hi
        digitalWrite(sounder_B, LOW);  //to generate the tone
        delayMicroseconds(period / 2);
        digitalWrite(sounder_A, LOW);
        digitalWrite(sounder_B, HIGH);
        delayMicroseconds(period / 2);
        elapsed_time += (period);
        digitalWrite(sounder_A, LOW);  //kill the output
        digitalWrite(sounder_B, LOW);
void loop()
    beep(500, 4000);
Your IP Address is:
Copyright © 2021 Bitsbox. Powered by Zen Cart