I have been trying to make a dynamic generated sine wave (sine wave is computed in a buffer) for a while now, however I keep ending up with a bit of jitter in my signal with no logical source. I am running the setup trough a 20khz low pass filter. I have checked the generated buffers and they display exactly what they need to. So could someone please help me out, included is a capture of the jitter on an oscilloscope.
So here is my code:
#include <avr/interrupt.h> //add interrupts
#include <avr/io.h> //no idea
float pi= 3.141592;
volatile int counter;
int buffersize = 200;
byte mainArray[201]; //should be one larger then buffersize
byte bufferArray[201];
volatile boolean switchbuffer; //buffer used to check if the buffer needs to be switched
boolean buffercheck; //check if buffering is done, as to unload the CPU for buffering
int sinePhase; //integer that is there to make sure the sine wave his phase is transferred correctly between buffers
void setup(){
Serial.begin(115200);
noInterrupts();
//preload a sine wave into the buffer and calc array
for (int i = 0; i <= buffersize; i++){
byte val = 127 + byte(127*sin(float(i)*(pi/50.0)));
mainArray[i] = val;
bufferArray[i] = val;
}
//setting up counters and checks
counter=0;
buffercheck=true;
switchbuffer=false;
sinePhase=0;
pinMode(3, OUTPUT);
pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS20); //setting the prescaler (currently no prescaler)
//TCCR2B = _BV(CS21);
TIMSK2 = 0x01; //Timer2 INT Reg: Timer2 Overflow Interrupt Enable
OCR2A = 180; //set overflow compare register to a random value;
OCR2B = 50;
interrupts();
Serial.println("i am");
}
ISR(TIMER2_OVF_vect){
if(counter > buffersize){
counter = 0;
OCR2A = bufferArray[0];
switchbuffer = true;
}else{
OCR2A = mainArray[counter];
counter++;
}
}
void loop(){
//Serial.println(counter);
if(switchbuffer){
for(int i = 0; i<=buffersize; i++){
mainArray[i]=bufferArray[i];
}
switchbuffer = false;
buffercheck = true;
}
if(buffercheck){
//generate shit
generateSine(575);
}
}
void printing(){ Serial.println(counter);}
void generateSine (int freq){
float scale = 2*pi/float(62500/freq);
int period = 62500/freq;
int sinewaveTime = sinePhase;
for(int i = 0; i<= buffersize; i++){
if(sinewaveTime >= period){
sinewaveTime=0;
}else{
sinewaveTime++;
}
byte val = 127 + byte(127*sin((float(i)+sinePhase)*scale));
bufferArray[i] = val;
//Serial.print(val);
// Serial.print("\t");
}
// Serial.println();
sinePhase=sinewaveTime;
buffercheck=false;
//Serial.print(mainArray[200]);
//Serial.print("\t");
// Serial.print(bufferArray[0]);
//Serial.print("\t");
// Serial.println(sinePhase);
}