Trying to load values from external application to Arduino via serial port

Hello,
I am trying to load values from my external application, in this case visual studio, to my arduino ATmega2560 using the serial port on the computer. When trying to load the values, I have problems recieving them corecctly and can not seem to find a reason as to why it would not work. This is my current code;

int byteIndex = 0;
int currentWriteMode = -1;
byte packet[4];

void setup() 
{
  ReadWriteMode(OUTPUT);
  Serial.begin(9600);
}

void loop() 
{
  if (Serial.available() > 0) 
  {
    
    int data = Serial.read();
    packet[byteIndex] = data;
    byteIndex++;

    
    SetControl(7);
    
    if(byteIndex == 4)
    {
      if(packet[0] == 0x01)   // Write Mode
      {
        ReadWriteMode(OUTPUT);
        SetControl(1+2+4);
        delay(10);
        
        SetAddress(packet[1], packet[2]);
        delay(10);

        SetControl(0+2+4);
        delay(10);

        SetControl(0+0+4);
        delay(10);

        SetData(packet[3]);
        delay(10);
        
        SetControl(0+2+4);
        delay(10);

        SetControl(0);
        delay(10);
        
        SetAddress(0,0);
        SetData(0);
        byteIndex = 0;
      }
    }
  }
}

// Set the addresses and data IO:s
void ReadWriteMode(int mode)
{
  if(mode != currentWriteMode)
  {    
    AddressPortsMode(mode);
    DataPortsMode(mode);
    ControlPortsMode(mode);
   
    currentWriteMode = mode;
  }
}

/*
  [ Sets the value of the buses ]
*/

// Set the IO:s for the address
void SetAddress(byte address0, byte address1)
{
  for(int bitIndex = 0; bitIndex < 8; bitIndex++)
  {
    if(bitRead(address0, bitIndex) == true)
      digitalWrite(10 + bitIndex, HIGH); 
    else
      digitalWrite(10 + bitIndex, LOW);
  }  
  
  for(int bitIndex = 0; bitIndex < 8; bitIndex++)
  {
    if(bitRead(address1, bitIndex) == true)
      digitalWrite(18 + bitIndex, HIGH); 
    else
      digitalWrite(18 + bitIndex, LOW);
  }    
}

// Set the IO:s for the data
void SetData(byte data)
{
  for(int bitIndex = 0; bitIndex < 8; bitIndex++)
  {
    if(bitRead(data, bitIndex) == true)
      digitalWrite(2 + bitIndex, HIGH); 
    else
      digitalWrite(2 + bitIndex, LOW);
  }  
}

// Set the IO:s for the controls
void SetControl(byte control)
{
  for(int bitIndex = 0; bitIndex < 8; bitIndex++)
  {
    if(bitRead(control, bitIndex) == true)
      digitalWrite(26 + bitIndex, HIGH); 
    else
      digitalWrite(26 + bitIndex, LOW);
  }  
}

/*
  [ Sets the IOs state to OUTPUT or INPUT ]
*/

// Sets the address ports to input or output
void AddressPortsMode(int mode)
{
  for(int index = 10; index <= 25; index++)
    pinMode(index, mode);
}

// Sets the data ports to input or output
void DataPortsMode(int mode)
{
  for(int index = 2; index <= 9; index++)
    pinMode(index, mode);
}

// Sets the control ports to input or output
void ControlPortsMode(int mode)
{
  for(int index = 26; index <= 28; index++)
    pinMode(index, mode);
}

The serial data that I am trying to load to my port is from a visual studio project, here is the code for that aswell (written in C#);

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Z80_Programmer
{
    public partial class FormMain : Form
    {
        public static SerialPort _serialPort;

        public FormMain()
        {
            InitializeComponent();

            textBoxText.Text = global::Z80_Programmer.Properties.Settings.Default.SettingCommand;
        }

        private void Upload_Click(object sender, EventArgs e)
        {
            global::Z80_Programmer.Properties.Settings.Default.SettingCommand = textBoxText.Text;
            global::Z80_Programmer.Properties.Settings.Default.Save();

            using (SerialPort port = new SerialPort("COM16", 9600, Parity.None, 8, StopBits.One))
            {
                string textData = textBoxText.Text;

                int currentLength = -1;
                while (textData.Length != currentLength)
                {
                    currentLength = textData.Length;
                    textData = textData.Replace("\r\n\r\n", "\r\n");
                }

                textData = textData.Replace("\r", "").Trim(new char[] { '\r', '\n' });
                string[] rows = textData.Split('\n');

                byte[] dataArray = new byte[rows.Length];

                if(dataArray.Length % 4 != 0)
                {
                    MessageBox.Show("Compiler error, missing complete command!");
                    return;
                }

                for (int rowIndex = 0; rowIndex < rows.Length; rowIndex++)
                {
                    int value = Convert.ToInt32(rows[rowIndex]);
                    if (value > 255)
                    {
                        MessageBox.Show("Compiler error, row " + (rowIndex + 1).ToString());
                        return;
                    }
                    dataArray[rowIndex] = (byte)value;
                }

                port.ReadTimeout = 2000;
                port.Open();
                port.Write(dataArray, 0, dataArray.Length);
                port.Close();
            }
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            global::Z80_Programmer.Properties.Settings.Default.SettingCommand = textBoxText.Text;
            global::Z80_Programmer.Properties.Settings.Default.Save();
        }
    }
}

And the textbox code is;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Z80_Programmer
{
    public partial class FormMain : Form
    {
        public static SerialPort _serialPort;

        public FormMain()
        {
            InitializeComponent();

            textBoxText.Text = global::Z80_Programmer.Properties.Settings.Default.SettingCommand;
        }

        private void Upload_Click(object sender, EventArgs e)
        {
            global::Z80_Programmer.Properties.Settings.Default.SettingCommand = textBoxText.Text;
            global::Z80_Programmer.Properties.Settings.Default.Save();

            using (SerialPort port = new SerialPort("COM16", 9600, Parity.None, 8, StopBits.One))
            {
                string textData = textBoxText.Text;

                int currentLength = -1;
                while (textData.Length != currentLength)
                {
                    currentLength = textData.Length;
                    textData = textData.Replace("\r\n\r\n", "\r\n");
                }

                textData = textData.Replace("\r", "").Trim(new char[] { '\r', '\n' });
                string[] rows = textData.Split('\n');

                byte[] dataArray = new byte[rows.Length];

                if(dataArray.Length % 4 != 0)
                {
                    MessageBox.Show("Compiler error, missing complete command!");
                    return;
                }

                for (int rowIndex = 0; rowIndex < rows.Length; rowIndex++)
                {
                    int value = Convert.ToInt32(rows[rowIndex]);
                    if (value > 255)
                    {
                        MessageBox.Show("Compiler error, row " + (rowIndex + 1).ToString());
                        return;
                    }
                    dataArray[rowIndex] = (byte)value;
                }

                port.ReadTimeout = 2000;
                port.Open();
                port.Write(dataArray, 0, dataArray.Length);
                port.Close();
            }
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            global::Z80_Programmer.Properties.Settings.Default.SettingCommand = textBoxText.Text;
            global::Z80_Programmer.Properties.Settings.Default.Save();
        }
    }
}

Is there some limitation in the serial port that I am unaware of, and how might I go about fixing this issue? Any help or recommendation is appreciated!

Have a look at the examples in Serial Input Basics - simple reliable non-blocking ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

The technique in the 3rd example will be the most reliable. It is what I use for Arduino to Arduino and Arduino to PC communication.

You can send data in a compatible format with code like this (or the equivalent in any other programming language)

Serial.print('<'); // start marker
Serial.print(value1);
Serial.print(','); // comma separator
Serial.print(value2);
Serial.println('>'); // end marker

It makes debugging much easier if you send data as human readable text. I would only send binary data if it was the only way to achieve the required performance.

When your PC program opens the serial port it must allow time for the Arduino to reset. I usually get my Arduino program to send a message from setup() - for example Serial.println(“Arduino is Ready”); - and my PC program waits until it receives that before trying to send data to the Arduino. Then the PC program should keep the Serial Port open until it is completely finished with the Arduino.

…R