-
Notifications
You must be signed in to change notification settings - Fork 0
/
arduino.ts
78 lines (67 loc) · 1.8 KB
/
arduino.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Midi } from "@tonejs/midi";
import { Note } from "@tonejs/midi/src/Note";
import { Frequency } from "tone";
const saveFile = (filename: string, data: string) => {
const blob = new Blob([data], { type: "text/plain" });
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
} else {
const elem = window.document.createElement("a");
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
};
const convertMelody = (notes: Note[]) => {
let code = `#define speed 1
const int notes[][3] = {`;
notes.forEach((note) => {
const freq = note.midi;
const vel = Math.round(note.velocity * 126);
const delay = Math.round(note.duration * 1000);
code += `
\{${freq}, ${vel}, ${delay}\},`;
});
code += "};\n";
code += `
const int length = sizeof notes / sizeof(int[3]);
void noteOn(int cmd, int pitch, int velocity) {
Serial.write(cmd);
Serial.write(pitch);
Serial.write(velocity);
}
bool state = 0;
void playMIDI(){
for (int i = 0; i < length; i++) {
noteOn(0x90, notes[i][0], notes[i][1]);
delay(round(notes[i][2]*speed));
noteOn(0x90, notes[i][0], 0);
if (digitalRead(2) == 0) {
state = !state;
while (digitalRead(2) == 0);
delay(200);
}
if (state == 1) {
digitalWrite(LED_BUILTIN, LOW);
} else {
digitalWrite(LED_BUILTIN, HIGH);
}
}
}
void setup() {
// put your setup code here, to run once:
// call the song function with digital pin
Serial.begin(31250);
pinMode(2, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
playMIDI();
}
`;
return code;
};
export { convertMelody, saveFile };