ShivamJoker / MIDI-to-Arduino

Convert MIDI files into arduino code
https://arduinomidi.netlify.app
16 stars 4 forks source link

Hope to add support for DFRobot_Tone and non-blocking mode #3

Open onenok opened 3 weeks ago

onenok commented 3 weeks ago

Hope to add support for DFRobot_Tone and non-blocking mode

ShivamJoker commented 3 weeks ago

Sure

onenok commented 3 weeks ago

I think the current method is not flexible enough. If we put the "wait/play time" and "tone" in arrays, respectively, it will be very convenient to use and easier to make it non-blocking. (p.s. using Google Translate)

onenok commented 3 weeks ago

But I don't have enough ability to see which part should be changed, so I can only express my thoughts here. (p.s. also using Google Translate)

onenok commented 3 weeks ago

I implement non-blocking delay by determining whether the "system uptime(ms)" has exceeded the specified time since the last execution.


if ((millis() - the_last_execution_time) >= time_need_to_wait) {
        the_last_execution_time = millis();
                //code to run
        };
onenok commented 3 weeks ago

MIDI-to-Arduino/arduino.ts:

const convertMelody = (notes: Note[]) => {
  let code = `
void song(int buzzerPin){
  `;
  notes.forEach((note) => {
    const freq = Math.round(Frequency(note.name).toFrequency());
    code += `
  tone(buzzerPin, ${freq});
  delay(${Math.round(note.duration * 1000)});
  noTone(buzzerPin);
`;
  });
  code += "}\n";

  code += `
void setup() {
  // put your setup code here, to run once:
  // call the song function with digital pin
  song(11);
}

void loop() {
  // put your main code here, to run repeatedly:
}
`;

  return code;
};

I think can change to:

const convertMelody = (notes: Note[]) => {
  let code = `
#define C3  131
#define Cb3 139
#define D3  147
#define Db3 156
#define E3  165
#define F3  175
#define Fb3 185
#define G3  196
#define Gb3 208
#define A3  220
#define Ab3 233
#define B3  247
#define C4  262
#define Cb4 277
#define D4  294
#define Db4 311
#define E4  330
#define F4  349
#define Fb4 370
#define G4  392
#define Gb4 415
#define A4  440
#define Ab4 466
#define B4  494
#define C5  523
#define Cb5 554
#define D5  587
#define Db5 622
#define E5  659
#define F5  698
#define Fb5 740
#define G5  784
#define Gb5 831
#define A5  880
#define Ab5 932
#define B5  988
void song(int buzzerPin){
  `;
  notes.forEach((note) => {
    code += `
  tone(buzzerPin, ${note.name});
  delay(${Math.round(note.duration * 1000)});
  noTone(buzzerPin);
`;
  });
  code += "}\n";

  code += `
void setup() {
  // put your setup code here, to run once:
  // call the song function with digital pin
  song(11);
}

void loop() {
  // put your main code here, to run repeatedly:
}
`;

  return code;
};

So that it can be read and edited easily. (This version is for tone() and this is blocking)