Cant get VU meter and sin generator to work together.

Hi, I'm trying to combine a sin wave generator and a VU meter. The problem is that the wave crested is distorted.

void loop() {
  long sumOfSquares = 0;
  
  for (int i=0; i<numberOfSamples; i++) { //take many readings and average them
   sample = analogRead(1);             //take a reading
    signal1 = (sample - middleValue);      //work out its offset from the center
    signal2 = signal1 * signal1;                     //square it to make all values positive
   sumOfSquares += signal2;               //add to the total
  }
  averageReading = sumOfSquares/numberOfSamples;     //calculate running average
  runningAverage=(((averagedOver-1)*runningAverage)+averageReading)/averagedOver;

 /* if (runningAverage>threshold){         //is average more than the threshold ?
    digitalWrite(ledPin, HIGH);          //if it is turn on the LED
  }else{
    digitalWrite(ledPin, LOW);           //if it isn't turn the LED off
  } */
  Serial.println(runningAverage);        //print the value so you can check it
  //delay (10);
  
  if (runningAverage > 0)
  {
    digitalWrite(led[1], HIGH);    
  }
  else { digitalWrite(led[1], LOW);}

Even when I disconnect all the LED's and the electret microphone I'm having this problem. There is something wrong with the code itself. Any help is greatly appreciated.

Phas_Freq_VU.ino (3.69 KB)

Waveforms.h (86.7 KB)

Bump

Can't see any distortion.

Do you mean that double pulse at the end?
That is caused by a small delay between the cycles, probbly caused by the timer interrupt service routine.

anyway to remove it?

shareefm:
anyway to remove it?

Well it is an artifact of your scope, there is no distortion just a time delay.

As you have not posted all of your code it is difficult to know if you are using the millis() timer. You could try disabling the interrupts.