5

I am trying to create a RS232 application that reads incoming data and stores it in a buffer. I found the following code in an RS232 example but I am 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 takes 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], ...};
}

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

5
  • The first function is an event handler: msdn.microsoft.com/en-us/library/…. It will be called automatically when you add the event to your port. Have port_DataReceived call ReadStoreArray instead of LogIncoming
    – 001
    Jan 24, 2014 at 16:10
  • You'll need to keep in mind that you may not receive your entire message in one event handler. You need to read until you get the number of bytes you require.
    – Jon B
    Jan 24, 2014 at 16:31
  • Thanks for your response. In most cases I want to leave the event handler as is. I only want to combine the response with another array for the specific method mentioned above "ReadStoreArray". How would I pull the bytes read into the "buffer" into my "ReadStoreArray" method?
    – Nevets
    Jan 24, 2014 at 16:35
  • For example I would want to store the response in a new array in order to manipulate it (i.e. read certain bytes, combine with another array). Is there a way to capture the response and store it in a new array in the "ReadStoreArray" method?
    – Nevets
    Jan 24, 2014 at 16:40
  • In port_DataReceived pass buffer to ReadStoreArray. I posted an example
    – 001
    Jan 24, 2014 at 16:51

4 Answers 4

8

When you create your 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], ...};
}
3
  • ReadStoreArray is no longer a good name for a function that does not read, also are those locals supposed to be arrays?
    – Ben Voigt
    Jan 24, 2014 at 16:52
  • In the hooking up of the DataReceived event, I get, "class, struct, or interface method must have a return type"; also "Identifier expected" at the end of that. Jun 10, 2014 at 22:04
  • I have posted a question related to it can you please see it ?
    – Moeez
    Jul 7, 2020 at 9:58
3

Don't bother with using the DataRecieve handler, it's horribly inaccurate, you're better off to start a thread which constantly reads the serial port and grabs every byte which comes across it.

2
  • I have posted a question related to it can you please see it ?
    – Moeez
    Jul 7, 2020 at 9:58
  • Agreed the DataReceived handler can be problematic but setting up a thread to constantly read the serial port is inefficient. It’s like saving on doorbell batteries then having to physically go to the door every minute to see if somebody is there! Oct 21, 2022 at 7:51
1

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

0

If you have a delimiter you can check for the delimiter and read the next amount of the data buffer required.

byte[] RawData;
        try
        {
            SerialPort serialPort = new SerialPort("COM11", 230400);
            serialPort.ReadTimeout = 1000;
            serialPort.WriteTimeout = 1000;
            if (serialPort.IsOpen) serialPort.Close();
            serialPort.Open();

            using (var binaryReader = new BinaryReader(serialPort.BaseStream))
            {
                //while (!FindForDelimiter(binaryReader))
                //{
                //    Thread.Sleep(1);
                //    //FindForDelimiter(binaryReader);
                //}

                while (serialPort.IsOpen)
                {
                    try
                    {
                        RawData = binaryReader.ReadBytes(5);
                        for (int offset = 0; offset < RawData.Length; offset += 5)
                        {
                            ulong lasttime = BitConverter.ToUInt32(RawData, 0);
                            Console.WriteLine(lasttime);
                        }
                    }
                    catch
                    {

                    }
                }

            }

In mine, i have requirement to find the delimiter its works my use case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.