在c#中从uart收到数据 [英] Received data from uart in c#

查看:155
本文介绍了在c#中从uart收到数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我在这段代码中遇到问题,proplem怎么知道端口是buzy

因为现在使用延迟等待读取数据来自发送方并在此之后从端口读取此数据,没有这个延迟无法读取正确的数据





Hi I have problem in this code, the proplem how can know the port is buzy
because now using delay for wait reading data from sender and after that reading this data from port, without this delay can't reading correct data


private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
       {

           string result=null;
           //Thread.Sleep(10000);
           result = Port.ReadExisting();
           textBox1.Text = result;
           if (result == "RING") label1.Text = "Call";
           else label1.Text = "message";
       }





我尝试过:



i尝试使用这种方法,但同样的问题





What I have tried:

i try using this method, but the same problem

int kk=Port.BytesToRead;
                
if(kk>=1)
{
     w = new byte[kk];
     Port.Read(w,0,kk);
     result = System.Text.Encoding.UTF8.GetString(w);
     textBox1.Text = result;
     if (result =="RING") label1.Text = "Call";
     else label1.Text = "message";

}

推荐答案

您必须检查已使用函数的返回值SerialPort.Read方法(Byte [],Int32,Int32)(System.IO.Ports) [ ^ ]或 SerialPort.ReadExisting Method (System.IO.Ports) [ ^ ]知道到目前为止是否收到了任何数据或接收了多少数据(接收数据是异步事件,因此您不知道预先)。如果没有数据,则必须等待。如果有数据,你必须检查是否会有更多数据(数据未完成),如果是这样,再次附加数据。



我建议阅读CodeProject文章 C#中的串口通信初学者 [ ^ ]。
You must check the return values of the used functions SerialPort.Read Method (Byte[], Int32, Int32) (System.IO.Ports)[^] or SerialPort.ReadExisting Method (System.IO.Ports)[^] to know if any or how many data has been received so far (receiving data is an asynchronous event so that you don't know that in advance). If there are no data, you have to wait. If there are data, you have to check if there will be more (data not complete) and if so read again appending the data.

I suggest to read the CodeProject article Serial Comms in C# for Beginners[^].


这篇关于在c#中从uart收到数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆