79 lines
1.4 KiB
C++
79 lines
1.4 KiB
C++
//waveform generator
|
|
|
|
// hacked from https://www.instructables.com/Arduino-Waveform-Generator-1/
|
|
|
|
#include <Adafruit_MCP4728.h>
|
|
#include <Wire.h>
|
|
|
|
Adafruit_MCP4728 mcp;
|
|
|
|
#define nsamp 32
|
|
#define dacmax 256
|
|
|
|
const byte nclk = 200; // a guess
|
|
long int freq; //frequency in Hz
|
|
long unsigned int phase;
|
|
long unsigned int phase_inc;
|
|
|
|
void setup() {
|
|
// TIMSK0 &= ~_BV(TOIE0); // disable timer0 overflow interrupt
|
|
|
|
Serial.begin(115200);
|
|
|
|
if (!mcp.begin(0x64)) {
|
|
while (1) {
|
|
delay(100);
|
|
}
|
|
}
|
|
|
|
// mcp.setSpeed(400000L);
|
|
// mcp.setSpeed(800000L);
|
|
mcp.setSpeed(800000L);
|
|
|
|
freq=440;
|
|
phase=0;
|
|
calc_phase_inc();
|
|
|
|
setwave();
|
|
}
|
|
|
|
const float pi=3.14159265;
|
|
byte waveform[nsamp];
|
|
byte phaseb = 0;
|
|
void setwave(){
|
|
for (int isamp=0; isamp<nsamp; ++isamp){
|
|
float phip=(isamp+0.5)/nsamp;
|
|
float phi=2*pi*phip;
|
|
int val=0;
|
|
|
|
//saw
|
|
//val = dacmax * isamp / nsamp;
|
|
//val = ( isamp < nsamp / 2 ) ? 0 : dacmax - 1;
|
|
//sine
|
|
val=(sin(phi)+1.0)*dacmax/2;
|
|
//val=((sin(phi)+0.333*sin(3*phi))/0.943+1)*dacmax/2;
|
|
|
|
val=max(val,0);
|
|
val=min(val,dacmax-1);
|
|
waveform[isamp]=val;
|
|
}
|
|
}
|
|
|
|
|
|
//calculate the phase increment.
|
|
void calc_phase_inc(){
|
|
// by measurement, 2^27 is about 138Hz (C below middle C)
|
|
// 2^27 / 138 = 972592.231884058
|
|
phase_inc = freq * 975592.231884058;
|
|
Serial.println(phase_inc);
|
|
}
|
|
|
|
|
|
|
|
void loop() {
|
|
phase += phase_inc;
|
|
int redphase = phase >> 27;
|
|
mcp.fastWrite(waveform[redphase] << 4, 0, 0, 0);
|
|
}
|
|
|