glennedi
Published © GPL3+

DC piezo buzzer volume control

A novel variant of the Arduino Fade sketch

BeginnerFull instructions provided25,422
DC piezo buzzer volume control

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
DC piezo buzzer
The type with an in built driver circuit
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

Modified fade sketch

C/C++
/*
 Fade

 This example shows how to fade an buzzer on pin XX
 using the analogWrite() function.

 The analogWrite() function uses PWM, so if
 you want to change the pin you're using, be
 sure to use another PWM capable pin. On most
 Arduino, the PWM pins are identified with 
 a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.

 This example code is in the public domain.
 */

/*
 * following cut from https://playground.arduino.cc/Main/TimerPWMCheatsheet  
How to adjust Arduino PWM frequencies by macegr in this forum post http://forum.arduino.cc/index.php?topic=16612#msg121031

Pins 11 and 3: controlled by timer 2 in phase-correct PWM mode (cycle length = 510)

Setting   Divisor   Frequency
0x01      1       31372.55
0x02      8       3921.16
0x03      32      980.39
0x04      64      490.20   <--DEFAULT
0x05      128     245.10
0x06      256     122.55
0x07      1024    30.64

TCCR2B = (TCCR2B & 0b11111000) | <setting>;

All frequencies are in Hz and assume a 16000000 Hz system clock.

*/

int buzzer = 11;           // the PWM pin the buzzer is attached to
int volume = 0;          // how loud the buzzer is
int fadeAmount = 5;     // how many points to fade the buzzer volume by

int duty_cycle = 127;         // 0-255 so 50% = 127 approx

int setting=0x01;

// the setup routine runs once when you press reset:
void setup() {

    TCCR2B = TCCR2B & 0b11111000 | setting;//to adjust divider for timer
    
  // declare buzzer pin to be an output:
  pinMode(buzzer, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the volume of pin 9:
  analogWrite(buzzer, volume);

  // change the volume for next time through the loop:
  volume = volume + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (volume <= 0 || volume >= 255) {
    fadeAmount = -fadeAmount;
  }
  // wait for 100 milliseconds to see the volume effect
  delay(100);
}

Credits

glennedi

glennedi

5 projects • 23 followers

Comments