borntoleave / catMini

This is the course repository for catMini.
51 stars 39 forks source link

Buzzer code explanation #3

Open correderadiego opened 6 years ago

correderadiego commented 6 years ago

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.

borntoleave commented 6 years ago

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.

fititnt commented 6 years ago

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

borntoleave commented 6 years ago

Neat! Thank you!

correderadiego commented 6 years ago

Thank you so much !