Thursday, 18 April 2013

Let's code a simple sampler

Using the groovuino library, we'll make a simple sampler, which will play a "poum-tchack" rythm.

You can hear the result here :
https://soundcloud.com/gaetino/poumtchack

First of all, you will have to wire a SD card to the SPI port, and making an audio out on the Arduino. Please refer to this post if you don't know how to connect the hardware :
http://groovuino.blogspot.com/2013/03/the-goal-is-to-build-groovebox-using.html

On the SD card, you will transfer 2 one-shot wave files (44 kHz), named "kick1.wav" and "snare1.wav".

Download groovuino library and SdFat lib :
https://github.com/Gaetino/Groovuino
https://code.google.com/p/sdfatlib/
Then put them in your favorite arduino library repository.

As usual, we'll begin the code by importing libraries :


#include <SdFat.h>
#include <sampler.h>
#include <timer.h> 

Now instanciate a Sd and a sampler object :


SdFat sd;
Sampler sampler;


To make the beat, we'll use a simple timer :

int to = 0;

Now the setup method to initialize our data :

void setup() 


// Start the audio engine
  startTimer(TC1, 1, TC4_IRQn, 44100);
  analogWrite(DAC1,0); 


    sd.begin(chipSelect, SPI_FULL_SPEED);
    sampler.init();
}

We'll use the loop() method to compute the beat, and to fill the wave buffer if necessary.
Of course, if you want to make a groovebox, you will need another timer to get the beat and trigger the samples.


void loop() 
{
   if(to>100000) 
   {
     to=0;
 // POUM
     sampler.load("kick1.wav");
     sampler.splay(100,1);
   }
   
   if(to==50000) 
   {
 // TCHACK
     sampler.load("snare1.wav");
     sampler.splay(100,1);
   }
   
   sampler.buffill();
   
   delayMicroseconds(10);
   
   to++;


And finally, as usual, the audio engine :


void TC4_Handler() 

   TC_GetStatus(TC1, 1); 

// 2048 is the 0 value of audio out.
   int16_t ulOutput=2048;

   sampler.next();
   
   ulOutput += sampler.output();

   if(ulOutput>4095) ulOutput=4095;
   dacc_write_conversion_data(DACC_INTERFACE, ulOutput); 
}


That's it. If all is good, you can hear a "poum-tchack".

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete