#include "DueTimer.h"
/*
- Sawtooth waveform generation using timer
- Wave frequency = wf (Hz)
- Samples per pulse = wn (num)
- So tatal samples passed per second to O/P = wf * wn
- i.e. timer frequncy to write out, tf = wf * wn
*/
uint32_t wf = 52000; // Frequency of 1Hz. for 51.2 kHz use 51200 and so on.
uint32_t wn = 20; // Length of sine in this program
uint32_t tf = wf * wn;
uint32_t wi; // Sample selector index
int currentSample = 0; // Start from null
int interruptHappened = 0; // Interrupt trigger flag
int sine[] = {
500,655,794,905,976,1000,976,905,794,655,
500,345,206,95,24,0,24,95,206,345
};
/*
int sine[] = {
0x7ff, 0x8d5, 0x9a9, 0xa78, 0xb40,
0xbff, 0xcb2, 0xd59, 0xdf1, 0xe77,
0xeec, 0xf4d, 0xf9a, 0xfd2, 0xff3,
0xfff, 0xff3, 0xfd2, 0xf9a, 0xf4d,
0xeec, 0xe77, 0xdf1, 0xd59, 0xcb2,
0xbff, 0xb40, 0xa78, 0x9a9, 0x8d5,
0x7ff, 0x729, 0x655, 0x586, 0x4be,
0x3ff, 0x34c, 0x2a5, 0x20d, 0x187,
0x112, 0xb1, 0x64, 0x2c, 0xb,
0x0, 0xb, 0x2c, 0x64, 0xb1,
0x112, 0x187, 0x20d, 0x2a5, 0x34c,
0x3ff, 0x4be, 0x586, 0x655, 0x729
};*/
void tHandler() {
interruptHappened = 1; // Set interrupt flag
// Obtain curren sample from the waveform's array
currentSample = sine[wi];
// Write the sawtooth wave sample to DAC1
analogWrite(DAC1, currentSample);
// Increment index to next sample or reset it if at the last sample
wi = wi + 1;
if (wi == wn) {
wi = 0;
}
}
void setup() {
// Can be changed to control phase of the O/P
wi = 0;
// Set BAUD rate for Serial stuffs
Serial.begin(250000);
// Set DAC1 for output
pinMode(DAC1, OUTPUT);
// Set resolution of DAC at 12 bits
analogWriteResolution(12);
// Reset analog pin to 0 before starting waveform
analogWrite(DAC1, 0);
// Bind TC3 with ISR, set frequency and start it
Timer3.attachInterrupt(tHandler).setFrequency((double)tf).start();
}
void loop() {
if(interruptHappened != 0) {
// Print saw wave in serial plotter
Serial.println(currentSample);
Serial.print(" ");
interruptHappened = 0; // Reset interrupt flag
}
}