2017년 4월 8일 토요일

[Arduino Uno R3] The doremi sound by buzer.

You can control the buzer sound tone using delay and digitalWrite.
The buzer tone is controlled by vibration period.
Following is vibration period for doremi.
C - 262
D - 294
E - 330
F - 349
G - 392
A - 440
B - 494
High C - 523
...

Demo


Code

#define DX 12
int abc[] = {262, 294, 330, 370, 392, 440, 494, 523};

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(DX, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  for(int i = 0; i < 8; i++)
  {
    mtone(DX, abc[i], 500); // abc[i] tone sound for 0.5 second
    delay(50);
  }
}

void mtone(int dx, int hz, unsigned long tm)
{
  unsigned long t = millis();
  unsigned long ns = (long)500000 / hz;
  
  // Repeats for tm milliseconds.
  // Sounds for tm milliseconds
  while(millis() - t < tm)
  {
    digitalWrite(dx, HIGH);
    delayMicroseconds(ns);
    digitalWrite(dx, LOW);
    delayMicroseconds(ns);
  }
}

Description

millics() : The function to get past time by milliseconds since starting Arduino.
tone() : It's a function provide by Arduion which is the same as mtone. So you can change the code mtone -> tone.

댓글 없음:

댓글 쓰기