简体   繁体   English

通过C#接收RS485命令

[英]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. 我想接收RS485命令。 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? 有谁知道我如何通过串行端口接收数据并将其显示在文本框中?

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. 我不确定您的最终目标,但是如果您只是想接收数据并在文本框中显示它们,则与标准RS232串行通信应该没有什么不同,应该这样做。 The name of the text box in this example is txtOutput. 在此示例中,文本框的名称为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. 请记住使用波特设置串行端口1,并确保已将串行端口添加到表单中。 I have tested the code with a standard serial connection and it is working. 我已经使用标准的串行连接测试了代码,并且可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM