0

I am working on a program that receives data from a serial port and displays this on a GUI. I am very new to C# and this is a part of a project I am working on. I have tried to look for code for the past few weeks and watched every tutorial on this matter, all to fail. I am still very new to programming and OOP.

The issue I am having is that the received data is not being pasted in the display box. I have verified that the serial port works using Putty so that cannot be the issue.

Edit: Quick update, upon learning how to use the meter I am working with and closer inspection of the user manual, I discovered that I was able to connect to the meter using serialportname.open(). The issue was that I was not requesting data. For example, by writing "READ?" into the meter, a reading would be returned.

David
  • 1
  • 2
  • You seem to have posted more code than what would be reasonable for your issue. Please read [ask] and how to make a [mre]; providing a MRE helps users answer your question and future users relate to your issue. – gunr2171 Jun 20 '22 at 16:29
  • The following may be helpful: https://stackoverflow.com/a/65971845/10024425 , https://stackoverflow.com/a/70614758/10024425 , and https://stackoverflow.com/a/67410160/10024425 – Tu deschizi eu inchid Jun 20 '22 at 19:02

3 Answers3

1

I see that you're not using the DataReceived event. It could be an approach to what you're trying to achieve; it will trigger each time your serial port receives data, so you could use it to insert into the textbox1

private void serialPort1_DataReceived(object sender,SerialDataReceivedEventArgs e)
{
  string Data= serialPort1.ReadLine();
  displayToTxt(Data);
}

private void displayToTxt(string Data)
{
  BeginInvoke(new EventHandler(delegate
  {
    textBox1.AppendText(Data);
  }));
}

I used delegate to avoid thread errors.

Rubio Jesús
  • 105
  • 1
  • 9
0

first you need to add EventHandler

 SerialPort1.DataReceived += new SerialDataReceivedEventHandler(ReceiveData);

then get data and update UI

 public void ReceiveData(object sender, SerialDataReceivedEventArgs e)
        {
            
            System.Threading.Thread.Sleep(30);
            SerialPort _SerialPort = (SerialPort)sender;
             int _bytesToRead = _SerialPort.BytesToRead;
             byte[] recvData = new byte[_bytesToRead];
             _SerialPort.Read(recvData, 0, _bytesToRead);
             this.BeginInvoke(new SetTextDeleg(UpdateUI), new object[] { recvData });
        }
private void UpdateUI(byte[] data)
        {
            string str = BitConverter.ToString(data);
            textBox1.Text += str;
        }

Nick J
  • 3
  • 1
0

I know this is old. But since it is still showing up in searches, I thought I would add my answer.

As mentioned in another answer, you need to assign a handler to the serial port.

    public void  OpenPorts()
    {
        foreach (string nm in SerialPort.GetPortNames())
        {
            SerialPort sp = new()
            {
                PortName = nm,
                ReadBufferSize = 2048,
                DiscardNull = true,
                RtsEnable = true,
                DtrEnable = true,
                ReceivedBytesThreshold = 1
            };

            try
            {
                //This should throw an exception if the port is already open.
                sp.Open();
                sp.DataReceived += DataReceived;
                //Make sure the buffer is empty
                if (sp.BytesToRead != 0)
                {
                    sp.DiscardInBuffer();
                }

            }
            catch (Exception ex)
            {
                //Handle the exception here
            }
        }

    public void DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            while ((sender as SerialPort).BytesToRead > 0)
            {
                SerialBuffer += (sender as SerialPort).ReadExisting();
            }
            (sender as SerialPort).DiscardInBuffer();
        }
        catch (InvalidOperationException ex)
        {
            _ = MessageBox.Show("exception thrown at DataReceived.", "Crashed", MessageBoxButton.OK, MessageBoxImage.Information);
        }
    }
ScottinTexas
  • 171
  • 1
  • 19