Waveforms

main
Mike Lynch 2024-01-03 10:58:06 +11:00
parent 5e2e6c7e66
commit cdeb974109
1 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1,83 @@
//waveform generator
// hacked from https://www.instructables.com/Arduino-Waveform-Generator-1/
#include <Adafruit_MCP4728.h>
#include <Wire.h>
Adafruit_MCP4728 mcp;
#define nsamp 256
#define dacmax 256
const byte nclk=42; //number of clock cycles of the loop
long int freq; //frequency in mHz
long unsigned int phase;
long unsigned int phase_inc;
void setup() {
//TIMSK0 &= ~_BV(TOIE0); // disable timer0 overflow interrupt
//Wire.setClock(1400000L); // wooooo
Serial.begin(115200);
while (!Serial)
delay(10); // will pause Zero, Leonardo, etc until serial console opens
// Try to initialize!
if (!mcp.begin(0x64)) {
Serial.println("Failed to find MCP4728 chip");
while (1) {
delay(10);
}
} else {
Serial.println("Adafruit MCP4728 initialised");
}
freq=660;
phase=0;
calc_phase_inc();
//phase_inc = 1;
setwave();
}
const float pi=3.14159265;
byte waveform[nsamp];
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. 2^32/16E6=268.435456
void calc_phase_inc(){
phase_inc=0.268435456*nclk*freq;
Serial.println("phase inc");
Serial.println(phase_inc);
}
//regular running: generate waves
void loop() {
//phase+=900;
//int redphase = phase >> 24;
phase += analogRead(A0);
int redphase = phase % nsamp;
mcp.fastWrite(waveform[redphase] << 4, 0, 0, 0);
}