C#串口接收数据
private void spRun_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
strReceive = spRun.ReadExisting();
showdata(strReceive);
}
public void showdata(string sdata)
{
if (txtReceive.InvokeRequired)
{
MyInvoke _myInvoke = new MyInvoke(showdata);
this.Invoke(_myInvoke, new object[] { sdata });
}
else
{
this.txtReceive.Text = sdata;
}
}
string serialReadString;
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
serialReadString = serialPort1.ReadExisting();
this.rTB_receive.Invoke
(
new MethodInvoker
(
delegate
{
this.rTB_receive.AppendText(serialReadString);
}
)
);
}
在我的测试软件中发现一个问题,就是当发送数据小于或等于8位时,一切正常,如果大于8为字节,则在datareceived事件中接收到的数据会分成两段,第一段为8位,第二段为剩下的字节,很奇怪,在msdn中讲到不能保证每次发送的数据都能正确接收到,需要参照BytesToRead属性来确定要读取的数据量,所以我想出来的解决办法为:
int DataLength=serialPort.BytesToRead;
int i=0;
StringBuilder sb=new StringBuilder();
while(i<DataLength)
{
byte[] ds=new byte[1024];
int len=serialPort.Read(ds,0,1024);
sb.Append(Encoding.Ascii.GetString(ds,0,len));
i+=len;
}
Console.Write(sb,ToString());
private string StringToHexString(string s,Encoding encode)
{
byte[] b = encode.GetBytes(s);//按照指定编码将string编程字节数组
string result = string.Empty;
for (int i = 0; i < b.Length; i++)//逐字节变为16进制字符,以%隔开
{
result += "%"+Convert.ToString(b[i], 16);
}
return result;
}
private string HexStringToString(string hs, Encoding encode)
{
//以%分割字符串,并去掉空字符
string[] chars = hs.Split(new char[]{'%'},StringSplitOptions.RemoveEmptyEntries);
byte[] b = new byte[chars.Length];
//逐个字符变为16进制字节数据
for (int i = 0; i < chars.Length; i++)
{
b[i] = Convert.ToByte(chars[i], 16);
}
//按照指定编码将字节数组变为字符串
return encode.GetString(b);
}
字符串转16进制字节数组
发送串口数据: using System; using System.Collections.Generic; using System.... 51串口接收蓝牙数据C程序... 3页 4下载券 实验八_串行口发送数据和... ...
// // C#异步数据接收串口操作类 dyj057@gmail.com using System; using System.Runtime.InteropServices; /// /// (C)2003-2005 C2217 Studio 保留所有...
串口通信中接收数据时延迟处理与缓存处理的解决方案(C#)_计算机软件及应用_IT/... 基于LabVIEW被动接收型串... 暂无评价 4页 3.00 μC/OS-Ⅱ中的周期...
("数据接收成功!", "系统提示"); //} public byte[] mysendb() { string... 串口发送接收程序 2页 1下载券 串口收发程序 暂无评价 1页 免费 c语言串口...
利用C#实现串口通讯(定时接收数据)_计算机软件及应用_IT/计算机_专业资料。自己编写的简单程序!using System; using System.Collections.Generic; using System....
CommBufferData为串口缓冲区内所有数据 //存取最后一次接收到的缓冲区的数据, /... 运用C语言对串行口进行操... 3页 免费 .net串口读写操作 2页 免费 在VB...
对象接收数据时, MSDN:从 SerialPort 对象接收数据时,将在辅助线程上引发 ... 1页 免费 C_串口操作之读取串口数... 2页 1下载券喜欢此文档的还喜欢...
2.2 串口设备数据的接收和处理_计算机软件及应用_IT/计算机_专业资料。串口设备数据的接收和处理工控程序设计 学习情景2.2 串口设备数据的接收和处理 学习情景2....
将串口接收到的数据保存到EXCEL文档_计算机软件及应用_IT/计算机_专业资料。《一...="C:\d1.xls" End Sub '收到 RThreshold 定义的字符数 1 字节 MSComm1....
串口设备数据的连续接收 2 委托的概念和使用方法 C#中的委托的作用相当于C/C++中的函数指针 中的委托的作用相当于C/C++中的函数指针, C#中的委托的作用相当于C...
热门文档