catMini icon indicating copy to clipboard operation
catMini copied to clipboard

Buzzer code explanation

Open correderadiego opened this issue 7 years ago • 4 comments

I have started with the buzzer. In this code you use some numbers that I don't understand. I understand that you switch on and off the buffer changing the period to create different tones but I don't understand the way to calculate the frequency and the period. I have attached this piece of code :

int freq = 220 * pow(1.059463, note);
  float period = 1000000.0 / freq / 2.0;
  for (byte r = 0; r < repeat; r++) {
    for (float t = 0; t < duration * 1000; t += period * 2) {
      analogWrite(BUZZER, 150);      // Almost any value can be used except 0 and 255
      // experiment to get the best tone
      delayMicroseconds(period);          // wait for a delayms ms
      analogWrite(BUZZER, 0);       // 0 turns it off
      delayMicroseconds(period);          // wait for a delayms ms
    }
    delay(pause);
}

As a programming tip you shouldn't use numbers in the code. It makes the code hard to understand. You can use #defines instead. This numbers are named magic numbers.

correderadiego avatar Mar 30 '18 16:03 correderadiego

As I'm trying to keep the code compatible with the full version (it will use up 100% of system resources), I'm shrinking down a lot of separate declarations.

Those numbers are calculated based on the simple math of music pitch, where relative pitches are calculated by: pitch = 69 + 12 * log2(frequency / 440). So the current code starts from note A3. The melody is made with a sequence of pitches.

Anyway, the music code is just for fun. I could replace it with pale beeps to indicate system status.

borntoleave avatar Mar 31 '18 04:03 borntoleave

Just a style note on markdown (used on github for issues and also to render the .md files) is to use single ` for inline and trile ``` for code and then click preview to see if it worked. See https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code

Also, to make more clear for the syntax highlighting engine, is a good idea start with ```language for multi line render, on this case ```c worked:

int freq = 220 * pow(1.059463, note);
float period = 1000000.0 / freq / 2.0;
for (byte r = 0; r < repeat; r++) {
  for (float t = 0; t < duration * 1000; t += period * 2) {
    analogWrite(BUZZER, 150); // Almost any value can be used except 0 and 255
    // experiment to get the best tone
    delayMicroseconds(period); // wait for a delayms ms
    analogWrite(BUZZER, 0); // 0 turns it off
    delayMicroseconds(period); // wait for a delayms ms
  }
  delay(pause);
}

image for reference of how I done:

captura de tela de 2018-03-31 01-31-13

fititnt avatar Mar 31 '18 04:03 fititnt

Neat! Thank you!

borntoleave avatar Mar 31 '18 04:03 borntoleave

Thank you so much !

correderadiego avatar Apr 01 '18 18:04 correderadiego