Reading and saving bytes from the serial port

I am trying to create an RS232 application that reads incoming data and saves it in a buffer. I found the following code in the RS232 example, but I'm not sure how to use it.

* RS232 Example port_DataReceived *

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        if (!comport.IsOpen) return;

        if (CurrentDataMode == DataMode.Text)
        {
            string data = comport.ReadExisting();

            LogIncoming(LogMsgType.Incoming, data + "\n");
        }
        else
        {
            int bytes = comport.BytesToRead;

            byte[] buffer = new byte[bytes];

            comport.Read(buffer, 0, bytes);

            LogIncoming(LogMsgType.Incoming, ByteArrayToHexString(buffer) + "\n");

        }
    }

I am trying to write another method that accepts an incoming byte array and combines it with another array ... see below:

private void ReadStoreArray()
{
   //Read response and store in buffer
   int bytes = comport.BytesToRead;
   byte[] respBuffer = new byte[bytes];
   comport.Read(respBuffer, 0, bytes);   

   //I want to take what is in the buffer and combine it with another array
   byte AddOn = {0x01, 0x02}
   byte Combo = {AddOn[1], AddOn[2], respBuffer[0], ...};
}

Currently, I have both methods in my code, since I am confused how to read and store incoming bytes in the port. Can I use the "port_DataReceived" method in my "ReadStoreArray" method? Do I need to modify my "ReadStoreArray" method? Or do I just need to start?

+4
3

SerialPort:

SerialPort comport = new SerialPort("COM1");
comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // Shortened and error checking removed for brevity...
    if (!comport.IsOpen) return;
    int bytes = comport.BytesToRead;
    byte[] buffer = new byte[bytes];
    comport.Read(buffer, 0, bytes);
    HandleSerialData(buffer);
}

//private void ReadStoreArray(byte[] respBuffer)
private void HandleSerialData(byte[] respBuffer)
{
   //I want to take what is in the buffer and combine it with another array
   byte [] AddOn = {0x01, 0x02}
   byte [] Combo = {AddOn[1], AddOn[2], respBuffer[0], ...};
}
+5

DataRecieve, , , , .

+2

You cannot read the same data from a port twice. You will need to read it once into the buffer, then either share the buffer (pass as a parameter to the function) or clone it to give each function its own copy.

0
source

Source: https://habr.com/ru/post/1523557/


All Articles