Problem solved; TLDR version: the tone function is not good enough to create fast pitched sounds. Using the toneAC library which uses timer1 solves this problem -> Google Code Archive - Long-term storage for Google Code Project Hosting.
Hi!
I am building a sound generator using an Arduino Uno and the tone() function.
Here is the code
const int speakerPin = 11;
const int buttonOne = 6;
int buttonStateOne = 0;
const int potOne = 0;
int potOneVal = 2;
const int potTwo = 1;
int potTwoVal = 100;
void setup(void) {
Serial.begin(9600);
pinMode(buttonOne, INPUT);
pinMode(speakerPin, OUTPUT);
}
void loop(void) {
potOneVal = map(analogRead(potOne), 0, 1023, 200, 1000);
potTwoVal = map(analogRead(potTwo), 0, 1023, 100, 1000);
buttonStateOne = digitalRead(buttonOne);
if (buttonStateOne == HIGH ) {
sirenSlow();
delayMicroseconds(25);
}
}
void sirenSlow() {
int i = 0;
while(i < potOneVal) {
tone(speakerPin, potTwoVal+i);
i++;
}
noTone(speakerPin);
while(i != 0) {
tone(speakerPin, potTwoVal+i);
i--;
}
noTone(speakerPin);
}
What I am trying to achieve is a siren like sound which works almost perfectly now except that the generated sound clips, pops or distorts (see this small recording I uploaded to youtube)
You can hear that the sounds is clipping or popping. The reason could be is that the Arduino generates a pure SquareWave and I send it to the speaker, and because the signal is too loud or harsh it clips in my speaker. I tried to counter that with adding resistance but without success. I also created a very simple amplifier using a LM386 but also without success.
When I generate a pure tone() (without loops) I don't hear the clipping, even when I add a sequence of tones (with enough delay) I still don't hear the clipping so the problem is within the loop perhaps? Maybe the tone() gets fired to quick which generates the clipping/popping. I've tried to counter that with delays within the while but that generates weird / distorted noise.
Current flow: arduino uno via monojack to my analogue mixingdesk to my active Yamaha80SM speakers.
I'm kinda out of ideas at the moment, any ideas?
Thanks!
// edit
The clipping/popping is almost only noticeable when the tone generates a high frequency but I am sure the same problem occurs also on lower frequencies but not noticeable enough.
// more edits
when I send the signal with only a resistor to my mixing desk the incoming signal clips but the sound is good except for the popping/clipping, when I use a LM386 simple amplifier circuit to create a clean signal for a mixer the incoming signal on the mixing desk does not clip and is lower in volume (which is good!) the clipping/popping does not dissapear though and is still very noticeable