Looptober24/05Wavetable/05Wavetable.ino

129 lines
2.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;
int note = 0;
int gate;
int decay = 128;
float pattern[16];
long unsigned int pattern_inc[4];
void setup() {
TIMSK0 &= ~_BV(TOIE0); // disable timer0 overflow interrupt
cli();
//set timer1 interrupt at 1Hz
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1 = 0;//initialize counter value to 0
// set compare match register for 1hz increments
OCR1A = 3905;// = (16*10^6) / (1*1024) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei();
Serial.begin(115200);
if (!mcp.begin(0x64)) {
while (1) {
delay(100);
}
}
// mcp.setSpeed(400000L);
// mcp.setSpeed(800000L);
mcp.setSpeed(800000L);
freq=440;
phase=0;
//pattern[0] = 220.0;
// pattern[1] = 261.6255653005987;
// pattern[2] = 369.9944227116345;
// pattern[3] = 391.9954359817495;
for( int i = 0; i < 4; i++ ) {
pattern[i] = 0;
}
for( int i = 4; i < 6; i++ ) {
pattern[i] = 659.2551138257401;
}
for( int i = 6; i < 8; i++ ) {
pattern[i] = 493.8833012561241;
}
for( int i = 8; i < 16; i++ ) {
pattern[i] = 0;
}
for( int i = 0; i < 16; i++ ) {
pattern_inc[i] = pattern[i] * 975592.231884058;
}
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;
}
}
ISR(TIMER1_COMPA_vect){
note += 1;
if( note > 15 ) {
note = 0;
}
phase_inc = pattern_inc[note];
gate = 4095;
}
void loop() {
phase += phase_inc;
int redphase = phase >> 27;
mcp.fastWrite(waveform[redphase] << 4, gate, 0, 0);
if( gate > 0 ) {
gate -= decay;
}
}