I am generating a simple musical instrument using a ST board. basically I have a sensor which detects motion or spatial angle and generates sounds of differnt pitch and volume depending on the angle. I already have the driver for the audio codec so all I need to do is to generate sound samples and feed the samples to it. Now I am able to get the angle readings from the sensor but the challenging part is how to generate sound. From google search so far, I think I need to generate a sin function with frequency and amplitude(volume) set according to the reading from the sensor. But my codec assumes a sampling rate 0f 48KHz so how would I go about generating sinusoids with different frequencies for a fixed sampling rate?
So far I have done this:
samplingRate = 48000;
n = 0; // reset once there is a change in frequency
// this function is called 48000 times a second
int generateSineWave(float frequency, float volume)
{
int temp = volume*(sin(2*pi*frequency*n);
n = n + 1;
if (n == samplingRate) {
n = 0;
}
if (abs(temp) > MAXVAL) {
return ERROR_CODE;
}
return temp;
}
This seems to be working (I am hearing something),but I am not sure if it's generating the right frequency sinusoid. also the sound I am hearing is not very pleasant, how would I go about generating complex tones(like the ones in piano for example)? I guess also my control variables(spatial angles) needs to be low pass filtered. But apart from that any idea on how I could generate more audibly pleasant waves?