Project 4.00 Using the Piezo

This project shows how to use the MC Trainer to produce a noise from the piezo onboard when SW1 is pressed.

Project Code:

/////////////////////////////////////////
// 4.00 - Using the Piezo

byte piezoPin = 12;

byte SW1 = 1;
bool pressed = LOW;

void setup() {
  pinMode(piezoPin, OUTPUT);
  pinMode(SW1, INPUT);
}

void loop() {
  if (digitalRead(SW1) == pressed) {
    digitalWrite(piezoPin, HIGH);
    delay(1);
    digitalWrite(piezoPin, LOW);
    delay(1);
  }
}
/////////////////////////////////////////

*If you’re copying and pasting the code, or typing from scratch, delete everything out of a new Arduino sketch and paste / type in the above text.

The piezo is connected to pin 12 on the MC Trainer.

byte piezoPin = 12;

Since we are writing to this pin, it’s an output.

pinMode(piezoPin, OUTPUT);

The piezo buzzer creates sound through the rapid physical deformation of an internal crystal. When a voltage is applied, the crystal changes shape. By quickly fluctuating the applied voltage, a sound is generated with a frequency that matches the rate of these voltage changes. Since we know how to turn a pin on and off (digitalWrite) we can create noise! To prevent a continuous annoying buzzing, we will only write to the Piezo when SW1 is pressed.

  if (digitalRead(SW1) == pressed) {
    digitalWrite(piezoPin, HIGH);
    delay(1);
    digitalWrite(piezoPin, LOW);
    delay(1);
  }

Frequency, expressed in Hertz (Hz), indicates the number of cycles that occur per second. In the context of a piezo buzzer, understanding the frequency requires identifying the number of these cycles within a one-second timeframe. A “cycle”, in this case, is defined as one complete sequence of the buzzer turning “on” and then “off”. This sequence is also referred to as a “period”, marking the duration of one full cycle of operation.

In our case the period is 2 milliseconds. It takes 2 milliseconds to make a full cycle. How many of those cycles happen in one second? Remember, 1 second is 1000ms.

1000ms / 2ms = 500Hz

The noise you hear is at a frequency of 500Hz!

Previous
Previous

Project 4.01 Using Functions

Next
Next

Project 3.04 NOT Logic