Arduino Mega 2560 MIDI In

Hi everyone i’m trying to do a simple connection Keyboard-Arduino in order to receive MIDI signals sent from the Keyboard but I am not succeeding.

The image shows, according to what I found, how I connected the components.(The diode is 1N4007 and the Optocoupler is a PC817 made by Sharp).

How should I connect Arduino and the MIDI wire to the Optocoupler?

I attach also the simple sketch to check if i’m receiving something or not:

#include <MIDI.h>
MIDI_CREATE_INSTANCE(SoftwareSerial, Serial3, MIDI);

byte commandByte;
byte noteByte;
byte velocityByte;

void setup(){
  Serial1.begin(31250);
  Serial.begin(9600);
}


void loop(){
do{
    if (Serial3.available()){
      commandByte = Serial3.read();//read first byte
      noteByte = Serial3.read();//read next byte
      velocityByte = Serial3.read();//read final byte
      Serial.println(commandByte);
    }
  }
  while (Serial3.available() > 2);//when at least three bytes available

}

  Serial1.begin(31250);
...

    if (Serial3.available()){

See any problem? Also the PC817 output pins are the wrong way round. 3 to GND, 4 to the Arduino.

Steve

Also:-

MIDI_CREATE_INSTANCE(SoftwareSerial, Serial3, MIDI);

You do not need to be using software serial that processor has four real hardware serial ports.

Thank you guys.
The problem was in the code as Steve made me notice. A bit distracted.

It is working now but I did not change the pc817 so I think the right way to connect the components is like I did.

Ps: Mike you are right don't know why I left the code like that.

donowitz:
Hi everyone i'm trying to do a simple connection Keyboard-Arduino in order to receive MIDI signals sent from the Keyboard but I am not succeeding.

The image shows, according to what I found, how I connected the components.(The diode is 1N4007 and the Optocoupler is a PC817 made by Sharp).

You have pins 3 and 4 of the opto coupler the wrong way round. 3 is the emitter and 4 is the collector,
fix this even if it is apparently working