#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#include "Button.h"
#include "Midi.h"
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
const unsigned long second = 1000000;
const float minute = 60.0;
int bpmPotPin = A1;
int bpmPotVal = 0;
float bpm = 120.0;
float beatsPerSecond = minute / bpm;
float beatLength = beatsPerSecond * second;
float quarterNoteLength = beatLength;
float eightNoteLength = quarterNoteLength / 2;
float sixteenthNoteLength = eightNoteLength / 2;
float clockTickLength = quarterNoteLength / 24;
unsigned long now = 0;
unsigned long nextTick = clockTickLength;
const int buttonPin = 2;
const int ledPin = 13;
int ledState = LOW;
int playState = LOW;
Button recordButton(2);
Button stopButton(11);
Button playButton(6);
Midi midi;
void setup() {
recordButton.setup();
stopButton.setup();
playButton.setup();
midi.setup();
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
// Serial.begin(31250);
// Serial.begin(115200);
Serial.begin(9600);
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.display();
display.clearDisplay();
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(WHITE); // Draw white text
display.setCursor(0,0); // Start at top-left corner
display.println(F("Hello, world!"));
display.display();
}
void setBpm(float newBpm) {
bpm = newBpm;
beatsPerSecond = minute / bpm;
beatLength = beatsPerSecond * second;
quarterNoteLength = beatLength;
eightNoteLength = quarterNoteLength / 2;
sixteenthNoteLength = eightNoteLength / 2;
clockTickLength = quarterNoteLength / 24;
display.clearDisplay();
display.setCursor(0,0);
display.println(F("BPM:"));
display.println(bpm);
display.display();
}
void loop() {
now = micros();
if (now >= nextTick) {
// Serial.write(Midi::CLOCK);
nextTick = nextTick + clockTickLength;
}
bpmPotVal = analogRead(bpmPotPin);
if (bpmPotVal != bpm) {
setBpm(bpmPotVal);
}
recordButton.update(now);
stopButton.update(now);
playButton.update(now);
midi.update(now);
if (recordButton.is_pressed() == HIGH) {
midi.loadNotes();
midi.sendNotes();
}
if (playButton.is_pressed() == HIGH) {
if (playState == HIGH) {
Serial.write(Midi::STOP);
playState = LOW;
} else {
Serial.write(Midi::CONT);
playState = HIGH;
}
}
if (stopButton.is_pressed() == HIGH) {
if (playState == HIGH) {
Serial.write(Midi::STOP);
Serial.write(Midi::START);
}
}
digitalWrite(ledPin, playState);
}