Dan Fayal

Dan Fayal

  • NA
  • 2
  • 2.7k

Sending one byte at a time to serial port.

Jun 26 2021 3:15 PM

Hi!

Before I go any further, dear ones, I would like to make it clear that I have not tried to do the byte-sending code of the C# application yet, nor the Arduino part. What I have tried in C# is a complete failure. But I will post my attempt C# code.

I really need some help. I am trying to make a software in C# that communicates with my Arduino. The goal is to make my own writer for my PS One memory cards. 

The first step of my software, opens a binary file and composes a byte array such as {0xA3, 0xD5, 0x4F} in a textbox. This I have already done.

See:

OpenFileDialog dialog = new OpenFileDialog();
var fileContent = string.Empty;
var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
    openFileDialog.InitialDirectory = "c:\\";
    openFileDialog.RestoreDirectory = true;
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        filePath = openFileDialog.FileName;
        var fileStream = openFileDialog.OpenFile();
        string Filename = filePath;
        var binData = File.ReadAllBytes(Filename);
        var sb = new StringBuilder();
        foreach (var b in binData)
            sb.Append("0x" + b.ToString("X2") + ",");
        var strData = sb.ToString();
        strData = strData.Remove(strData.Length - 1);
        txtboxHexStrings.Text = strData;

       My next step, is to send one byte at a time to the Arduino. The arduino will read this byte, write it to the respective address on the memory card, after write this byte,  discard it and wait for the next byte to be written until the whole  C# byte array is read. 

I know this sounds like a stupid question, and I sincerely apologize to the community for this. But I really can't think of a for loop algorithm that does this.  As I said before, the Arduino part I will still do. 

This is my failed attempt to send one byte at a time from the Array to the Arduino's serial port.                       

byte[] arrByte = Encoding.ASCII.GetBytes(txtboxHexStrings.Text);
for (int i = 0; i < arrByte.Length; i++)
{
    while (i < arrByte.Length)
    {
        // try to study a good delay time
        serialPort1.Write(new byte[] { arrByte[i] }, 0, 1);
        i++;
    }
}

Maybe I am wrong, but, the essential management is in the C# program, the Arduino will just receive the data to be written and do its part.  

Any help or information will be greatly appreciated. 

Best Wishes