2021年10月
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            

最近のトラックバック

« 2014年8月 | トップページ | 2015年8月 »

2014年9月

2014年9月 9日 (火)

bitDuinoでメロディを奏でてみた

Tonecycle_test

※bitDuino10書込み環境に圧電スピーカーを接続した様子

 現在ATtiny10とATtiny13AをサポートするArduino互換機環境のbitDuinoですが、tone関数でメロディを奏でてみたいとがんばってみました。ATtiny13Aを使用するbitDuino13では元のtone関数の無くても何とかなるし使いにくい第3引数duration(発音の長さ)を廃止して空きメモリを増やしています。またATtiny10を使用するbitDuino10では、どうしてもフラッシュに入るサイズに出来なかったので、周波数を引数にするtone関数の代わりに、直接的にクロックサイクル数を引数にするtoneCycle関数を実装しました。最新のサポートファイルをダウンロードしてお使いください。

 またそれぞれにサンプルスケッチを用意しました。ライブラリのサンプルではないので、普通にスケッチフォルダに保存して試してみて下さい。実際に音を出すには圧電スピーカーが必要です。サンプル中、bitDuino10はD2(4番ピン)とGND(2番ピン)、bitDuino13ではD4(3番ピン)とGND(4番ピン)に圧電スピーカーを繋げています。tone関数、toneCycle関数のいずれでも使用するピンは自由ですので、スケッチを自作する場合には接続ピンを変更する事も可能です。それからオリジナルのtone関数のサンプルスケッチではメロディデータを普通の変数で配列に持っていますが、bitDuinoでは変数や配列に使えるSRAMも小さいので、PROGMEM constキーワードとpgm_read_word_near関数を駆使しています。toneCycle関数用のサンプルスケッチではpitches.hの中身もそれに合わせて値を変更しています。

 下はtoneCycle関数用サンプルスケッチのtoneCycleMelody.inoです。LEDは繋がなくても音は出ます。

 #include <avr/pgmspace.h> 
 #include "pitches.h"
// notes in the melody:
PROGMEM const unsigned int melody[] = {
  NOTE_C5, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_G4,0, NOTE_B4, NOTE_C5};
// note durations: milli seconds 
PROGMEM const unsigned int noteDurations[] = {
  250, 125, 125, 250, 250, 250, 250, 500 };
#define led 1
#define spk 2
 
void setup() {
  pinMode(led,OUTPUT);
  // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < (sizeof(noteDurations)>>1); thisNote++) { 
    unsigned int noteDuration = pgm_read_word_near(noteDurations+thisNote); 
    toneCycle(spk, pgm_read_word_near(melody+thisNote));
    digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level) 
    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    delay(noteDuration); 
    // stop the tone playing:
    noTone(spk);
   digitalWrite(led, LOW);   // turn the LED on (HIGH is the voltage level)
   delay(noteDuration>>2);
  }
} 
void loop() {
  // no need to repeat the melody.
}
 

 バッハのメヌエットを奏でてみた動画はこちら。 

« 2014年8月 | トップページ | 2015年8月 »

ウェブページ

無料ブログはココログ