从串行数据读取时C#出现问题
我在C#中的串行端口读取器有问题 如果我通过串行端口发送5555,程序将打印出555。 这是节目单从串行数据读取时C#出现问题,c#,C#,我在C#中的串行端口读取器有问题 如果我通过串行端口发送5555,程序将打印出555。 这是节目单 public static void Main() { byte[] buffer = new byte[256]; string buff; using (SerialPort sp = new SerialPort("COM2", 6200)) { sp.Open(); //read directly sp.Rea
public static void Main()
{
byte[] buffer = new byte[256];
string buff;
using (SerialPort sp = new SerialPort("COM2", 6200))
{
sp.Open();
//read directly
sp.Read(buffer, 0, (int)buffer.Length);
//read using a Stream
sp.BaseStream.Read(buffer, 0, (int)buffer.Length);
string sir = System.Text.Encoding.Default.GetString(buffer);
Console.WriteLine(sir);
您需要使用从“Read”方法返回的int。返回的值将告诉您实际读取了多少字节。在读取所需的字节数之前,可能需要多次循环并调用“Read”
更新:有一些示例代码,显示如何多次读取,直到您有足够的数据进行处理。您的计算机和其他设备都可能有一个硬件缓冲区,该缓冲区可以传递与为连接启用的实际硬件控制相关的数据。因此,您必须注意:
- 硬件控制流程设置李>
- 数据读取/写入的定时李>
更新:用谷歌搜索“SerialPort tutorial C#”,并研究其中的一些,比如。你能给我举个例子吗?是不是以“5555”null结尾?我真的不知道。。。如何检查?@Scott Chamberlain空终止字符串是C/C++等模糊语言的问题,而不是硬件设备的问题;-)