arduino-modular/waveforms/waveforms.ino

79 lines
1.4 KiB
Arduino
Raw Normal View History

2024-01-02 23:58:06 +00:00
//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
2024-01-02 23:58:06 +00:00
#define dacmax 256
2024-01-03 00:50:22 +00:00
const byte nclk = 200; // a guess
long int freq; //frequency in Hz
2024-01-02 23:58:06 +00:00
long unsigned int phase;
long unsigned int phase_inc;
void setup() {
// TIMSK0 &= ~_BV(TOIE0); // disable timer0 overflow interrupt
2024-01-03 00:50:22 +00:00
2024-01-02 23:58:06 +00:00
Serial.begin(115200);
2024-01-03 00:50:22 +00:00
2024-01-02 23:58:06 +00:00
if (!mcp.begin(0x64)) {
while (1) {
delay(100);
2024-01-02 23:58:06 +00:00
}
}
// mcp.setSpeed(400000L);
// mcp.setSpeed(800000L);
mcp.setSpeed(800000L);
2024-01-02 23:58:06 +00:00
freq=440;
2024-01-02 23:58:06 +00:00
phase=0;
calc_phase_inc();
setwave();
}
const float pi=3.14159265;
byte waveform[nsamp];
byte phaseb = 0;
2024-01-02 23:58:06 +00:00
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;
2024-01-02 23:58:06 +00:00
//val = ( isamp < nsamp / 2 ) ? 0 : dacmax - 1;
//sine
2024-01-03 00:50:22 +00:00
val=(sin(phi)+1.0)*dacmax/2;
2024-01-02 23:58:06 +00:00
//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;
}
}
2024-01-03 00:50:22 +00:00
//calculate the phase increment.
2024-01-02 23:58:06 +00:00
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);
2024-01-02 23:58:06 +00:00
}
2024-01-03 00:50:22 +00:00
2024-01-02 23:58:06 +00:00
void loop() {
phase += phase_inc;
int redphase = phase >> 27;
2024-01-03 00:50:22 +00:00
mcp.fastWrite(waveform[redphase] << 4, 0, 0, 0);
2024-01-02 23:58:06 +00:00
}