So, here's some code I made today... basically, it generates a semi-sine wave (positive only, no negative as of yet, I have a question about that) at a specified frequency, and can do things with separate waves (eg addition, subtraction) easily. I was intending to use it for sound, but unfortunately without changing timer 0B (and also messing up the essential millis() and micros()), there is an obvious whine at all frequencies. Later I might try messing with 0B to push it to 62500khz out of the human range and figure out how millis(), micros(), etc respond. Here is my code.
int wav1[3];//0 frequency, 1 unscaled amplitude, 2 is final amplitude
int wav2[3];
int average;
float time;
float percentage;
float templitude;
const int resolution=100;//this determines the update speed. A lower number means a higher refresh rate.
const float pi=3.14159;
void setup(){
wav1[0]=5;//the first wave is set to 5hz
wav1[1]=255;//100% amplitude
wav2[0]=500;//500 hertz
wav2[1]=255;//100% amplitude
TCCR1B = TCCR1B & 0b11111000 | 1;//set timer 1B (pin 9) to 31250khz
pinMode(9, OUTPUT);
//Serial.begin(115200);//this is for debugging
}
void loop(){
time=micros() % 1000000;
percentage=time/1000000;
templitude=abs(sin(((percentage)*wav1[0])*2*pi)); //this creates a single positive half-wave rather
//than one positive and one negative one in a true sine wave. This might be fixed later.
//Serial.println(templitude);//also for debugging
wav1[2]=templitude*wav1[1];//scale amplitude
templitude=abs(sin(((percentage)*wav2[0])*2*pi));//generate current "voltage" for wave 2
wav2[2]=templitude*wav2[1];//scale amplitude
average=(wav1[2]+wav2[2])/2;//find average of two waves. Other methods like subtraction or whatever
//are doable, but I would need support for a negative wave and the max amplitude would be 50%.
analogWrite(9, average);//set output "voltage"
delayMicroseconds(resolution);//this is to give the micro time to set the "voltage"
}
Now, two questions.
1.) Every second, there is a noticeable rise in pitch or volume (I can't tell which). I don't know if it's at the beginning or end of the second, but it's probably a problem with my code. Any ideas?
2.) If I use two PWM pins, and I digitalWrite one of them to zero, can that pin act as ground? That way, I can swap the hot and neutral pins to generate a true bi-polar sine wave.
Thanks!