研究テーマ->音楽とロボット->オリジナル制作のロボット->Arduinoで楽器音を再生する

   
  ここでは、Arduinoを使用して効果音を再生する方法について紹介します。toneの機能を使用する他、PWMのピンを使用して、サンプリング音で効果音を再生することもできます。  
 
Toneで楽器音を再生する
  Toneで楽器の音を出すことができます。  
  Arduinoスケッチ  
  #define NUM_BUTTON 7
#define NUM_LED  6
const int buttonPin[NUM_BUTTON] = {A0,A1,A2,A3,A4,A5,8}; // the number of the pushbutton pin
const int ledPin[NUM_LED] = {2,3,4,5,6,7};  // the number of the LED pin
int SoundPin = 13;   // ブザーを接続したピン番号
//int Note[NUM_BUTTON]={262,294,330,349,392,440,494};
int Note[NUM_BUTTON]={262/2,294/2,330/2,349/2,392/2,440/2,262*2/2};

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

void setup() {

 // 起動後、この中の内容が上から順に1回実行される
 Serial.begin(9600);       // シリアル通信の準備をする
 while (!Serial);         // 準備が終わるのを待つ
 Serial.println("start");  // シリアル通信でメッセージをPCに送信

 // initialize the LED pin as an output:
 int i;
 for(i=0;i<NUM_LED;i++)
 {
  pinMode(ledPin[i], OUTPUT);
 }
 // initialize the pushbutton pin as an input:
 //pinMode(buttonPin, INPUT);
 for(i=0;i<NUM_BUTTON;i++)
 {
  pinMode(buttonPin[i], INPUT_PULLUP);
 }
}

void loop() {
 int i;
 bool flg=false;

 for(i=0;i<NUM_BUTTON;i++)
 {

  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin[i]);

  int j=0;
  switch(i)
  {
    case 0:
     j=5;
     break;
    case 1:
     j=4;
     break; 
    case 2:
     j=3;
     break;
    case 3:
     j=2;
     break; 
    case 4:
     j=1;
     break;
    case 5:
     j=0;
     break;     
    case 6:
     j=6;
     break;     
    default:
      j=6;
     break;     
  }

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  int oct_div=2;
  if(j==6)
  {
   if (buttonState == false) {
    tone(SoundPin,Note[j]/oct_div);

    flg=true;
   }
  }
  else
  {
   if (buttonState == false) {
    // turn LED on:
    digitalWrite(ledPin[j], HIGH);
    tone(SoundPin,Note[j]/oct_div);

    flg=true;
   } else {
    // turn LED off:
    digitalWrite(ledPin[j], LOW);
   }
  }
 }
 if(flg==false){
  noTone(SoundPin);
 }
}
 
 
 

http://www.mu-tech.co.jp/Soft/ButtonSample.zip