전체상품목록 바로가기

본문 바로가기


현재 위치
  1. home
  2. community
  3. 튜토리얼

튜토리얼

튜토리얼 Tutorial

게시판 상세
subject 웨이브 쉴드 6개 버튼 연동 사운드 재생하기 예제 소개
writer 아트로봇 (ip:124.50.164.53)
  • date 2011-07-07 21:05:27
  • like 추천하기
  • view 2095
rating 0점

웨이브 쉴드 사용예제 소개

 

예제명: 6개 버튼 연동 사운드 재생하기

 

1. 버튼을 누르면 해당되는 wav 파일 재생하기

2. 재생중에 새로운 버튼이 눌려지면 기존 음악은 중지되고 곧바로 새로운 음악이 재생되는 예

3. SD 메모리에 호환되는 wav파일들을 저장한 뒤에 해당파일명으로 아래의 소스를 수정합니다.

 

가령,      playfile("0gtarfun.WAV");    를 

               playfile("MYSOUND.WAV");  로 수정해 주시면 끝!

주의,  파일명의 크기는 영문 8자이내로 수정해 주셔야합니다.

 

4. 본 예제는 이전 튜토리얼에서 소개해드렸던 WaveHC library 설치 및 웨이브 쉴드 기본 작동을 테스트 후 시도하시기 바랍니다.

 

5. 버튼은 Analog 입력 0번 부터 5번까지 6개의 핀을 이용하며,  해당 아날로그 핀이 GND에 접속되면 버튼이 눌려진것으로 인식됩니다.   즉,  아날로그핀 0번  케이블 <-> 0번버튼 <-> GND  와 같이 연결하신 후, 해당버튼을 누르시면 0번 버튼에 연동되는 해당 wav파일이 재생되게 됩니다.   (아래 예제의 경우 0gtarfun.WAV 파일이 재생됨)

단순 테스트시 점퍼케이블의 한쪽끝을 GND에 꽂아주시고 나머지 핀으로 Analog 0번~5번까지 핀 중에 하나를 접촉시켜주시면 해당 버튼을 눌러주는 효과를 대신하실 수 있습니다. (청부된 사진 참조)

 

6. 아날로그 입력핀 부분에 헤더소켓을 연결해주시면 점퍼케이블과 브레드보드를 이용하여 납땜없이 버튼 연결등을 임시로 하실 수 있으십니다.   첨부된 이미지를 참조하세요

 

아두이노 소스 코드

 

#include
#include
#include
#include "WaveUtil.h"
#include "WaveHC.h"


SdReader card;    // This object holds the information for the card
FatVolume vol;    // This holds the information for the partition on the card
FatReader root;   // This holds the information for the filesystem on the card
FatReader f;      // This holds the information for the file we're play

WaveHC wave;      // This is the only wave (audio) object, since we will only play one at a time

#define DEBOUNCE 5  // button debouncer

// here is where we define the buttons that we'll use. button "1" is the first, button "6" is the 6th, etc
byte buttons[] = {14, 15, 16, 17, 18, 19};
// This handy macro lets us determine how big the array up above is, by checking the size
#define NUMBUTTONS sizeof(buttons)
// we will track if a button is just pressed, just released, or 'pressed' (the current state
volatile byte pressed[NUMBUTTONS], justpressed[NUMBUTTONS], justreleased[NUMBUTTONS];

// this handy function will return the number of bytes currently free in RAM, great for debugging!  
int freeRam(void)
{
  extern int  __bss_end;
  extern int  *__brkval;
  int free_memory;
  if((int)__brkval == 0) {
    free_memory = ((int)&free_memory) - ((int)&__bss_end);
  }
  else {
    free_memory = ((int)&free_memory) - ((int)__brkval);
  }
  return free_memory;
}

void sdErrorCheck(void)
{
  if (!card.errorCode()) return;
  putstring("\n\rSD I/O error: ");
  Serial.print(card.errorCode(), HEX);
  putstring(", ");
  Serial.println(card.errorData(), HEX);
  while(1);
}

void setup() {
  byte i;
 
  // set up serial port
  Serial.begin(9600);
  putstring_nl("WaveHC with ");
  Serial.print(NUMBUTTONS, DEC);
  putstring_nl("buttons");
 
  putstring("Free RAM: ");       // This can help with debugging, running out of RAM is bad
  Serial.println(freeRam());      // if this is under 150 bytes it may spell trouble!
 
  // Set the output pins for the DAC control. This pins are defined in the library
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
 
  // pin13 LED
  pinMode(13, OUTPUT);
 
  // Make input & enable pull-up resistors on switch pins
  for (i=0; i< NUMBUTTONS; i++) {
    pinMode(buttons[i], INPUT);
    digitalWrite(buttons[i], HIGH);
  }
 
  //  if (!card.init(true)) { //play with 4 MHz spi if 8MHz isn't working for you
  if (!card.init()) {         //play with 8 MHz spi (default faster!) 
    putstring_nl("Card init. failed!");  // Something went wrong, lets print out why
    sdErrorCheck();
    while(1);                            // then 'halt' - do nothing!
  }
 
  // enable optimize read - some cards may timeout. Disable if you're having problems
  card.partialBlockRead(true);
 
// Now we will look for a FAT partition!
  uint8_t part;
  for (part = 0; part < 5; part++) {     // we have up to 5 slots to look in
    if (vol.init(card, part))
      break;                             // we found one, lets bail
  }
  if (part == 5) {                       // if we ended up not finding one  :(
    putstring_nl("No valid FAT partition!");
    sdErrorCheck();      // Something went wrong, lets print out why
    while(1);                            // then 'halt' - do nothing!
  }
 
  // Lets tell the user about what we found
  putstring("Using partition ");
  Serial.print(part, DEC);
  putstring(", type is FAT");
  Serial.println(vol.fatType(),DEC);     // FAT16 or FAT32?
 
  // Try to open the root directory
  if (!root.openRoot(vol)) {
    putstring_nl("Can't open root dir!"); // Something went wrong,
    while(1);                             // then 'halt' - do nothing!
  }
 
  // Whew! We got past the tough parts.
  putstring_nl("Ready!");
 
  TCCR2A = 0;
  TCCR2B = 1<

  //Timer2 Overflow Interrupt Enable
  TIMSK2 |= 1<


}

SIGNAL(TIMER2_OVF_vect) {
  check_switches();
}

void check_switches()
{
  static byte previousstate[NUMBUTTONS];
  static byte currentstate[NUMBUTTONS];
  byte index;

  for (index = 0; index < NUMBUTTONS; index++) {
    currentstate[index] = digitalRead(buttons[index]);   // read the button
   
    /*    
    Serial.print(index, DEC);
    Serial.print(": cstate=");
    Serial.print(currentstate[index], DEC);
    Serial.print(", pstate=");
    Serial.print(previousstate[index], DEC);
    Serial.print(", press=");
    */
   
    if (currentstate[index] == previousstate[index]) {
      if ((pressed[index] == LOW) && (currentstate[index] == LOW)) {
          // just pressed
          justpressed[index] = 1;
      }
      else if ((pressed[index] == HIGH) && (currentstate[index] == HIGH)) {
          // just released
          justreleased[index] = 1;
      }
      pressed[index] = !currentstate[index];  // remember, digital HIGH means NOT pressed
    }
    //Serial.println(pressed[index], DEC);
    previousstate[index] = currentstate[index];   // keep a running tally of the buttons
  }
}


void loop() {
  byte i;
 
  if (justpressed[0]) {
    justpressed[0] = 0;
    playfile("0gtarfun.WAV");
  }
  else if (justpressed[1]) {
      justpressed[1] = 0;
      playfile("0horse.WAV");
  }
  else if (justpressed[2]) {
      justpressed[2] = 0;
      playfile("0lamb.WAV");
  }
  else if (justpressed[3]) {
      justpressed[3] = 0;
      playfile("0rainttn.WAV");
  }
  else if (justpressed[4]) {
      justpressed[4] = 0;
      playfile("0chimes.WAV");
  }
  else if (justpressed[5]) {
      justpressed[5] = 0;
      playfile("doorbell.WAV");
  }
}

 

// Plays a full file from beginning to end with no pause.
void playcomplete(char *name) {
  // call our helper to find and play this name
  playfile(name);
  while (wave.isplaying) {
  // do nothing while its playing
  }
  // now its done playing
}

void playfile(char *name) {
  // see if the wave object is currently doing something
  if (wave.isplaying) {// already playing something, so stop it!
    wave.stop(); // stop it
  }
  // look in the root directory and open the file
  if (!f.open(root, name)) {
    putstring("Couldn't open file "); Serial.print(name); return;
  }
  // OK read the file and turn it into a wave object
  if (!wave.create(f)) {
    putstring_nl("Not a valid WAV"); return;
  }
 
  // ok time to play! start playback
  wave.play();
}

 

 

 

file artrobot-IMG_4815.JPG
password 수정 및 삭제하려면 비밀번호를 입력하세요.
  • 조영환 2012-08-30 19:26:28 0점
    수정 삭제 댓글
    안녕하세요. 얼마전 이 제품 구입했는데 혹시 아날로그 입력 말고, 숫자나 문자등으로 디지털 제어가 가능한지요.. 고민 끝에 문의드립니다.
  • 손태호 2013-11-26 16:30:21 0점
    수정 삭제 댓글
    이거 안되는데요.
  • 손태호 2013-11-26 16:30:41 0점
    수정 삭제 댓글
    코딩좀 다시 정리해서 올려주시면 안될까요.
  • 박지웅 2014-09-03 14:41:29 0점
    수정 삭제 댓글
    웨이브 쉴드 사용법을 잘모르겠는데
    nice920209@naver.com 로 보내주실수있나요???
  • 유혁준 2015-07-13 08:35:44 0점
    수정 삭제 댓글
    타이머 2 토큰 어떻게 정해주나요?
댓글 수정

password :

/ byte

password : 확인 취소

댓글 입력

commentsname : password : 관리자 답변 보기

/ byte

왼쪽의 문자를 공백없이 입력하세요.(대소문자구분)

회원에게만 댓글 작성 권한이 있습니다.