// Simple DAC sine wave test on Teensy 3.1
// DAC is 12 bit using stable reference voltage
// deltaTime of 90 for N=6 @ 96 MHz -0 or -O3 gives precise frequency
// deltaTime of 50 for N=1 @ 96 MHz -O gives precise frequency
// smaller deltaTimes not necessarily precise
// maximum output integer on analogWrite function is 2733 without clipping
// maximum output voltage from Teensy 3.1 is 2.252 Volts
// when subsequent points are viewed on an oscillascope, on a generally downward
// trending portion of the graph, the line is jagged, meaning that the next point
// that you expect should be lower than the previous one will actually be higher
// Thus the output signal should be filtered.
int ledPin = 13;
int led = 0; // use to toggle led
int analogBits = 1350;
boolean output;
byte n, N = 6; // number of harmonics (1 to 6)
float A[6] = {0.008, 1.0,0.007, 0.006, 0.005, 0.004};
float phase[6] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
float amplitude;
float twopi = 3.1415926535 * 2;
elapsedMicros usec = 0;
elapsedMicros time = 0;
// I started with the eq'n 50 + (N-1)*40/5, but frequencies were wrong for intermediate N
uint deltaTime = 65 + (N-1)*25/5; // microseconds
float Fw = 100;
void setup() {
analogWriteResolution(12);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
delay(800);
// normalize sum of amplitudes to one
float sum = 0.0f;
for (n=0; n<N; n++)
sum += A[n];
for (n=0; n<N; n++)
A[n] = A[n]/sum;
}
void loop() {
time = 0;
amplitude = 0.0f;
for (n=0; n < N; n++)
amplitude += A[n] * sinf(phase[n]);
analogWrite(A14, analogBits + (int) (analogBits * amplitude));
for (n = 0; n < 2; n++) {
phase[n] += twopi * (n + 1) * Fw * deltaTime * 1e-6;
if (phase[n] >= twopi) {
phase[n] = phase[n] - twopi;
}
}
led = led + 1; // toggles the LSB
output = ((1 << 14) & led); // value of shifted bit
digitalWrite(ledPin, output);
while (usec < deltaTime); // wait
usec = usec - deltaTime;
//Serial.println(time);
//time = 0;
//Serial.println(output);
}