#include <Wire.h>
#include <Adafruit_MCP4725.h>
#include "TimerOne.h"
#define potPin 0
#define jack1 1
#define jack2 2
#define waveButton 2
#define lfoLed 3
#define switch1 12
#define switch2 13
#define cPi 3.14159
#define cRate 44100
#define cDACRange 4095
float lfoRate = 0.01;
float lfoOffset = 1;
unsigned long intPhase;
int waveShape;
int waveform = 0;
int amp;
Adafruit_MCP4725 dac; // constructor
//----------------------------------------------------
void setup() {
Serial.begin(44100);
//Serial.begin(9600);
dac.begin(0x60);
pinMode(waveButton,INPUT_PULLUP);
pinMode(lfoLed, OUTPUT);
pinMode(switch1,INPUT_PULLUP);
pinMode(switch2,INPUT_PULLUP);
}
//----------------------------------------------------
void lfo(){
static int pot;
static float fq;
static float phase;
pot = analogRead(potPin);
fq = pot * lfoRate + lfoOffset;
phase += (2*cPi*fq/cRate) * cDACRange;
intPhase = (int) phase;
}
//----------------------------------------------------
void checkRate(){
static int switchL;
static int switchR;
switchL = digitalRead(switch1);
switchR = digitalRead(switch2);
//low
if(switchL == 0){
lfoRate = 0.01;
lfoOffset = 1;
}
//mid
if(switchR == 1 && switchL == 1){
lfoRate = 0.1;
lfoOffset = 5;
}
//high
if(switchR == 0){
lfoRate = 1;
lfoOffset = 10;
}
}
//----------------------------------------------------
void checkWave(){
int value = digitalRead(waveButton);
static int oldValue = value;
if(value != oldValue){
oldValue = value;
if(value == 0){
waveform++;
if (waveform > 4){
waveform = 0;
}
}
}
}
//----------------------------------------------------
void wave(){
static int waveInverse;
static int rand;
//saw;
if(waveform == 0){
waveShape = intPhase % cDACRange;
}
//Square
if(waveform == 1){
waveShape = intPhase % cDACRange;
if(waveShape > cDACRange/2){
waveShape = cDACRange;
}else {
waveShape = 0;
}
}
//triangle
if(waveform == 2){
waveShape = (intPhase % cDACRange) * 2 - cDACRange;
waveInverse = waveShape * -1;
if(waveShape <= 0){
waveShape = 0;
}
if(waveInverse <= 0){
waveInverse = 0;
}
waveShape = waveShape + waveInverse;
}
//random
if(waveform == 3){
waveShape = intPhase % cDACRange;
if(waveShape >= cDACRange-250){
rand = random(0, cDACRange);
}
waveShape = rand;
}
//noise
if(waveform == 4){
rand = random(0, cDACRange);
waveShape = rand;
}
}
//----------------------------------------------------
void in1(){
static int in1;
in1 = analogRead(jack1);
if(in1 > 512){
waveShape = 0;
}
}
//----------------------------------------------------
void in2(){
static int in2;
in2 = analogRead(jack2);
if(in2 > 512){
waveShape = 0;
}
Serial.println(in2);
}
//----------------------------------------------------
void loop() {
static int lfoMap;
uint32_t dac_value;
lfo();
checkRate();
checkWave();
wave();
in1();
in2();
lfoMap = map(waveShape, 0, cDACRange,0, 255);
analogWrite(lfoLed, lfoMap);
amp = waveShape;
dac_value = amp;
dac.setVoltage(dac_value, false);
}