'Receive RS485 Commands via C#
I have been googling and haven't found any code to help me with this, maybe I missed something? I want to receive RS485 commands. At the moment I am just receiving rubbish. Here is my current code although I don't think it would help:
//C# CODE
byte[] arr = new byte[serialPort1.BytesToRead];
serialPort1.Read(arr, 0, serialPort1.BytesToRead);
String s = "";
foreach (byte b in arr)
{
s += b.ToString() + " ";
}
/*String s = serialPort1.ReadByte().ToString();
while (serialPort1.BytesToRead > 0)
{
s += " " + serialPort1.ReadByte().ToString();
Thread.Sleep(10);
}*/
//String s = serialPort1.ReadLine().ToString();
richTextBox1.Invoke((MethodInvoker)delegate { richTextBox1.AppendText(s + "\n"); });
This was just a test to see if I could receive the data. Does anyone know how I can receive data through serial port and show them in a text box?
Solution 1:[1]
I am not sure about your final goal but if you are looking only to receive data and show them in a text box, there should be no difference with a standard RS232 serial communication, this should do it. The name of the text box in this example is txtOutput.
To start:
public Form1()
{
InitializeComponent();
serialPort1.PortName=("COM1");
serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
serialPort1.Open();
}
serial port
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
SetText(serialPort1.ReadLine());
}
catch (Exception ex)
{
SetText(ex.ToString());
}
}
Delegate:
delegate void SetTextCallback(string text);
Append to text box:
private void SetText(string text)
{
if (this.txtOutput.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.BeginInvoke(d, new object[] { text });
}
else
{
txtOutput.AppendText(text + "\r\n");
}}
Remember to set the serial port1 with bauds and make sure you have added the serial port to your form. I have tested the code with a standard serial connection and it is working.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |