Skip to content
Snippets Groups Projects
noteblock.ino 1.6 KiB
Newer Older
fxk8y's avatar
fxk8y committed

#include "MIDIUSB.h"
#include <math.h>


// First parameter is the event type (0x0B = control change).
// Second parameter is the event type, combined with the channel.
// Third parameter is the control number number (0-119).
// Fourth parameter is the control value (0-127).

uint16_t period = 0;
uint64_t cycle = 0;
uint8_t state = 0;

void note(uint16_t frq);

void setup() {
  Serial.begin(115200);
  pinMode(10, OUTPUT);
}

uint16_t midi2frq(uint8_t number) {
//  Serial.print(number);
//  Serial.print(" | ");
  double _n = (double)((double)number-(double)69);
//  Serial.print(_n);
//  Serial.print(" | ");
  double d = pow((double)2, _n/(double)12) * (double)440;
//  Serial.println(d);
  return (uint16_t)d;
}

uint8_t lastNote = 0;

void loop() {
  midiEventPacket_t rx;
  rx = MidiUSB.read();
  if (rx.header != 0) {
      char buffer[256];
      sprintf(buffer, "header: 0x%X  b1: %d  b2: %d  b3: %d", rx.header, rx.byte1, rx.byte2, rx.byte3);
      Serial.println(buffer);
    if ((rx.header & 0x09) == 0x09) {
        lastNote = rx.byte2;
        note(midi2frq(rx.byte2));
        Serial.println("ONNNNNNN");
    } else if ((rx.header & 0x08) == 0x08 && lastNote == rx.byte2) {
        period = 0;
        Serial.println("OFFFFFFFF");
    } /* else {
      char buffer[256];
      sprintf(buffer, "header: 0x%X  b1: %d  b2: %d  b3: %d", rx.byte1, rx.byte2, rx.byte3);
      Serial.println(buffer);
    } */
  }

  if (period) {
    state ^= 1;
    digitalWrite(10, state);
  } else {
    digitalWrite(10, LOW);
  }

  cycle += 1;
  delayMicroseconds(period);
}

void note(uint16_t frq) {
  period = 1000000 / frq / 2;
}