簡體   English   中英

如何將字節數組發送到串行設備(C#)

[英]How to send a byte array to a serial device (C#)

我有一個串行設備,向我發送一串ASCII十六進制代碼(例如42 33)。 然后,我閱讀這些內容並使用它們來旋轉校驗和。 一旦旋轉它們,我需要將它們發送回包括一些控制字節的串行設備。

我覺得我的代碼可能太復雜了,我正在努力創建一種干凈的方法來構建一系列字節以發送回設備。

// Calculate Checksum
private byte[] calcChecksum(string checksum)
{
    // Create a byte array from checksum string
    byte[] byteArray = Encoding.ASCII.GetBytes(checksum);

    // Create Hex Characters from ASCII codes of byte array positions 5, 6.
    string left = ((char)byteArray[5]).ToString();
    string right = ((char)byteArray[6]).ToString();

    // Convert Hex Characters to Integer values used for the shifting
    int numLeft = Convert.ToByte(left, 16);
    int numRight = Convert.ToByte(right, 16);

    // Dummy checksum values to shift
    string cs = ShiftLeft(0x5232, numLeft).ToString("x4");
    string kw = ShiftRight(0xab23, numRight).ToString("x4");

    string cskw = cs + kw;

    byte[] checksumBytes = Encoding.ASCII.GetBytes(cskw);

    return checksumBytes;
}

// Communicate with Serial device
private void bChecksum_Click(object sender, EventArgs e)
{
    // Read string from device. Need a better way to create this
    // instead of using a richtext box. Okay for now but suggestions
    // welcome.
    returnCode = tbOutput.Text;
    byte[] checksumBytes = calcChecksum(returnCode);

    // Bytes I need to send to the device. Here I need to insert all the
    // checksumBytes Array values between 0x1B and 0x03
    byte[] bytesToSend = { 0x04, 0x02, 0x31, 0x30, 0x1B, ...array bytes..., 0x03 };
    _serialPort.Write(bytesToSend, 0, bytestosend.Length);
}

為了澄清,我需要一種方法將checksumBytes數組插入0x1B和0x03位置之間的bytesToSend Array中。

此外,任何代碼改進都將受到歡迎。

如果我對您的理解正確,那么您可以使用Array.CopyTo方法將3 個數組合並在一起; byte [] controlStart = {0x01,0x02,0x03}; byte [] checksumBytes = {0x04,0x05,0x06}; byte [] controlEnd = {0x07,0x08,0x09};

        byte[] bytesToSend = new byte[controlStart.Length + checksumBytes.Length + controlEnd.Length];

        controlStart.CopyTo(bytesToSend, 0);
        checksumBytes.CopyTo(bytesToSend, controlStart.Length);
        controlEnd.CopyTo(bytesToSend, controlStart.Length + checksumBytes.Length);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM