ã¨ããç· ãåããããã®ã§ç¾å®éé¿ãã¦ããã¾ãã
ãã¾ã¾ã§äººã®ä½ã£ãããã°ã©ã ã°ããåããã¦ããã®ã§ãèªåã§ãä½ããã£ã¦ã¿ã¾ããArduino ã§é³ãã ãã¦ã¿ã¾ããæ¢ãã¨ãhttp://arduino.cc/en/Tutorial/Melody ã«ãµã³ãã«ãããã¾ããã9 çªã¨ GND ã«åçã«ãããããªãã¶ã¼ãä»ããã¨é³ãé³´ãã¾ãããã®ããã°ã©ã ãååãããããã®ã§ãããããæä½éã®ç©ã ãæãåºãã¨ä»¥ä¸ã®ããã«ãªãã¾ããã440Hz ã®é³ãåºãããã°ã©ã ã§ããããªãããããã¦ã¤ã©ã¤ã©ãã¾ãã440Hz ã¶ãã® 2272 us ã HIGH 㨠LOW ã®åäºã§å²ã£ãæéã¦ã¨ã¤ãããã ãã§ãã
int speakerPin = 9; int pitch = 1000000 / 440; /* = 2272 us */ void setup() { pinMode(speakerPin, OUTPUT); } void loop() { digitalWrite(speakerPin, HIGH); delayMicroseconds(pitch / 2); digitalWrite(speakerPin, LOW); delayMicroseconds(pitch / 2); }
ããããã®ã¤ã©ã¤ã©ããé³ã¯ãã£ã¦ããã¾ãããdelayMicroseconds ã®ç²¾åº¦ãã¤ãã¤ããªãããç¡ãããªã¨çã£ã¦ã¿ã¾ããã¿ã¤ãã³ã°ã測ãã«ã¯ãä¸ã®ããã« delay ã使ãä»ãã¿ã¤ãã使ã£ãæ¹æ³ãããããã§ããArduino Interrupts http://www.uchobby.com/index.php/2007/11/24/arduino-interrupts/ ã«ããã¨ãã¿ã¤ãã¨ããã®ã¯ã¯ããã¯ã¨å ±ã«æ°åãå¢ãã¦ããã«ã¦ã³ã¿ã§ãæ°åãå¢ãããã¦æº¢ããã¨å²ãè¾¼ã¿ãèµ·ããã®ã§ããã®ç¬éé¢ç½ãäºãããã¨ããä¸å®æéç½®ãã«é¢ç½ãäºãåºæ¥ãä»çµã¿ã§ããã¯ããã¯ããã®ã¾ã¾ä½¿ãã¨éãã¦å¤§å¤ã§ãããããªã¹ã±ã¼ã«ã¨ããä»çµã¿ã使ãã¨ãã£ããæ°ãã¾ããä¾ãã°
- Arduino ã®ã¯ããã¯ã¯ 16MHz ãªã®ã§
- 256 ã®ããªã¹ã±ã¼ã«ãªãã16000000 / 256 = 62500 Hz
- ã¤ã¾ã 1ç§éã« 62500 åã«ã¦ã³ãããã
- 440Hz ã®ä¸æ³¢é·ã®éã«ã¯ 62500 / 440 = 142 åæ°ããã
- å®éã«ã¯ãã®éã« HIGH ã®æ㨠LOW ã®æãããã®ã§ã71 åæ¯ã«ä¿¡å·ãå ¥ãæ¿ãã㨠440Hz ã®é³ãé³´ãã
ã¨ããäºã§ã71 ãªã 8 ãããã®ç¯å²ã«åã¾ãã®ã§ 8 ãããã®ã¿ã¤ã2ã使ãã¾ãã
#include <avr/interrupt.h> #include <avr/io.h> int speakerPin = 9; int frequency = 440; unsigned char halfInterval = F_CPU / 256 / frequency / 2; unsigned char timerLoadValue = 256 - halfInterval; char signal = 0; void setup() { pinMode(speakerPin, OUTPUT); TCCR2A = 0; // Normal Timer TCCR2B = 1<<CS22 | 1<<CS21 | 0<<CS20; // clk/256 prescale TIMSK2 = 1<<TOIE2; // Timer/Counter2 Overflow Interrupt Enable TCNT2 = timerLoadValue; } ISR(TIMER2_OVF_vect) { // Timer/Counter2 Overflow TCNT2 = timerLoadValue; // Reset the timer digitalWrite(speakerPin, signal); // Output signal signal = !signal; } void loop() {}
ãã¼ãããã£ããããã·ã¨ããç¨åº¦ããããinclude æã¯ä¸è¦ã§ããããã£ãããã®ã§æ®ããã¾ã¾ã«ãã¦ãã¾ããããã§é£ããã®ã¯ setup ã®æã§ãã¿ã¤ã2ã«ãã¼ãã«è¨å®ã¨ãã¬ã¹ã±ã¼ã«ã«ã¤ãã¦ä¼ãã¦ãTOIE2 ã§æº¢ããæã«å²ãè¾¼ã¿ãçºçããããã«ãã¦ãã¾ãã TCCR2A ã TOIE2 ã¨ãã£ãè¬ãããå®æ°ã¯ãã¼ã¿ã·ã¼ãã«èª¬æãè¼ã£ã¦ãã¾ãã
æçµçã«é³ã®é«ã㯠timerLoadValue ã§æ±ºã¾ãã¾ãã440Hz ã®ä¾ã§ã¯ã71 åæ°ããã°è¯ãã£ãã®ã§æåã¿ã¤ãã« 256 - 71 ãè¨å®ãã¾ãããã㦠71 åæ°ã㦠256 ã«ãªãã¨æº¢ãã¦å²ãè¾¼ã¿ãçºçã ISR(TIMER2_OVF_vect) ãèµ·åããã¨ããä»çµã¿ã§ããã§ã¯ã§ã¯ã