Hello,
I am trying to get my Arduino Due to produce sound waves at very accurate frequencies. In order to do this I measured how long on analogWrite iteration takes and calculated how many iterations are required for a specific frequency etc.
The problem can not figure out is why the time it takes to perform one analogWrite changes when I change seemingly unrelated code. This code that I change is only executed after all of the time measurements are finished.
int loopCount = 10000;
void loop() {
long time1 = micros();
for(int p=0; p<loopCount; p+=1){
for (int i = 0; i < sampleSize; i+=1) {
analogWrite(DAC1, sineValues[i]);
}
}
long time2 = micros();
int deltaTime = (time2 - time1)/loopCount;
Serial.println(deltaTime);
double frequency = 1000000/deltaTime;
Serial.print("Frequency: ");
Serial.print(frequency);
Serial.println(" Hz");
Serial.println((float)deltaTime/sampleSize);
}
When executing the above code the value of deltaTime is 5046 us indicating one analogWrite takes 5046 us.
int loopCount = 10000;
void loop() {
long time1 = micros();
for(int p=0; p<loopCount; p+=1){
for (int i = 0; i < sampleSize; i+=1) {
analogWrite(DAC1, sineValues[i]);
}
}
long time2 = micros();
int deltaTime = (time2 - time1)/loopCount;
Serial.println(deltaTime);
/*double frequency = 1000000/deltaTime;
Serial.print("Frequency: ");
Serial.print(frequency);
Serial.println(" Hz");
Serial.println((float)deltaTime/sampleSize);*/
}
When I comment out some of the code in the main loop the value of deltaTime is different, namely 5281 us.
Note that these values are very constant, when I uncomment the code deltaTime becomes exactly 5046 us again.
I hope anyone has an idea of what causes this.
Thanks