C#串口通信实现方法
本文实例讲述了c#串口通信实现方法。分享给大家供大家参考。具体方法如下:
通过com1发送数据,com2接收数据。当com2接收完本次发送的数据后,向com1发送信息通知com1本次数据已发完,com1接到通知后,再发下一段数据。这样可以确保每次发送的数据都可以被正确接收。
代码如下:
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.io.ports;
using system.threading;
using utils;
namespace 串口通信
{
public partial class form1 : form
{
#region 变量
/// <summary>
/// 启动还是停止,true起动,false停止
/// </summary>
public static bool start = true;
/// <summary>
/// 串口资源
/// </summary>
private static serialport serialport1 = null;
/// <summary>
/// 串口资源
/// </summary>
private static serialport serialport2 = null;
/// <summary>
/// 成功次数
/// </summary>
private static int successcount = 0;
/// <summary>
/// 失败次数
/// </summary>
private static int errorcount = 0;
/// <summary>
/// 上次计算的总次数
/// </summary>
private static int lastcount = 0;
/// <summary>
/// 定时器
/// </summary>
private system.windows.forms.timer timer = new system.windows.forms.timer();
#endregion
#region form1
public form1()
{
initializecomponent();
}
#endregion
#region form1_load
private void form1_load(object sender, eventargs e)
{
serialport1 = new serialport("com1");
serialport1.datareceived += new serialdatareceivedeventhandler(serialport_datareceived1);
serialport1.open();
serialport2 = new serialport("com2");
serialport2.datareceived += new serialdatareceivedeventhandler(serialport_datareceived2);
serialport2.open();
}
#endregion
#region form1_formclosed
private void form1_formclosed(object sender, formclosedeventargs e)
{
serialport1.close();
serialport1.dispose();
serialport2.close();
serialport2.dispose();
}
#endregion
#region btnstart_click
private void btnstart_click(object sender, eventargs e)
{
start = true;
senddata();
timer.interval = 500;
timer.tick += new eventhandler(delegate(object obj, eventargs eventargs)
{
if (lastcount == 0)
{
lastcount = successcount + errorcount;
}
else
{
int cnt = successcount + errorcount - lastcount;
cnt = data.length * cnt / 1024 * (1000 / timer.interval);
double total = (successcount + errorcount) * data.length / 1024.0;
invokedelegate invokedelegate = delegate()
{
label3.text = cnt.tostring() + "kb/s " + total.tostring("#.0") + "kb";
};
invokeutil.invoke(this, invokedelegate);
lastcount = successcount + errorcount;
}
});
timer.start();
}
#endregion
#region btnstop_click
private void btnstop_click(object sender, eventargs e)
{
start = false;
timer.stop();
timer.dispose();
timer = new system.windows.forms.timer();
}
#endregion
#region 接收串口数据事件
/// <summary>
/// 接收串口数据事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void serialport_datareceived1(object sender, serialdatareceivedeventargs e)
{
if (serialport1.readline() != null)
{
successcount++;
senddata();
}
}
/// <summary>
/// 接收串口数据事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void serialport_datareceived2(object sender, serialdatareceivedeventargs e)
{
list<byte> blist = new list<byte>();
int i = 0;
while (serialport2.bytestoread > 0)
{
byte[] barr = new byte[serialport2.bytestoread];
i += serialport2.read(barr, 0, barr.length);
blist.addrange(barr);
}
serialport2.writeline("success");
string s = asciiencoding.utf8.getstring(blist.toarray());
invokedelegate invokedelegate = delegate()
{
textbox2.text = s;
};
invokeutil.invoke(this, invokedelegate);
if (s != str)
{
errorcount++;
invokedelegate = delegate()
{
label2.text = errorcount + "次不相等(失败)";
};
invokeutil.invoke(this, invokedelegate);
}
else
{
invokedelegate = delegate()
{
label1.text = successcount + "次相等(成功)";
};
invokeutil.invoke(this, invokedelegate);
}
}
#endregion
#region 发送数据
private void senddata()
{
if (start)
{
thread thread = new thread(new parameterizedthreadstart(delegate(object obj)
{
invokedelegate invokedelegate = delegate()
{
textbox1.text = str;
};
invokeutil.invoke(this, invokedelegate);
serialport1.write(data, 0, data.length);
}));
thread.start();
}
}
#endregion
#region 数据
private static byte[] data = null;
/// <summary>
/// 数据
/// </summary>
private static byte[] data
{
get
{
if (data == null)
{
data = asciiencoding.utf8.getbytes(str);
}
return data;
}
}
#endregion
#region 获取字符串
private static string str = null;
/// <summary>
/// 字符串
/// </summary>
private static string str
{
get
{
if (str == null)
{
stringbuilder sb = new stringbuilder();
for (int i = 0; i < 270; i++)
{
sb.append("计算机程序");
}
str = sb.tostring();
}
return str;
}
}
#endregion
}
}
辅助代码如下:
using system.collections.generic;
using system.text;
using system.windows.forms;
namespace utils
{
/// <summary>
/// 跨线程访问控件的委托
/// </summary>
public delegate void invokedelegate();
/// <summary>
/// 跨线程访问控件类
/// </summary>
public class invokeutil
{
/// <summary>
/// 跨线程访问控件
/// </summary>
/// <param name="ctrl">form对象</param>
/// <param name="de">委托</param>
public static void invoke(control ctrl, delegate de)
{
if (ctrl.ishandlecreated)
{
ctrl.begininvoke(de);
}
}
}
}
using system.collections.generic;
using system.linq;
using system.text;
using microsoft.win32;
using system.security.permissions;
using system.io.ports;
using system.security;
namespace utils
{
/// <summary>
/// 串口资源工具类
/// </summary>
public class serialportutil
{
#region 获取本机串口列表,包括虚拟串口
/// <summary>
/// 获取本机串口列表,包括虚拟串口
/// </summary>
public static string[] getcomlist()
{
list<string> list = new list<string>();
foreach (string portname in serialport.getportnames())
{
list.add(portname);
}
return list.toarray();
}
#endregion
#region 从注册表获取本机串口列表
/// <summary>
/// 从注册表获取本机串口列表
/// </summary>
public static string[] getportnames()
{
registrykey localmachine = null;
registrykey key2 = null;
string[] textarray = null;
//这里有个断言,判断该注册表项是否存在
new registrypermission(registrypermissionaccess.read, @"hkey_local_machine\hardware\devicemap\serialcomm").assert();
try
{
localmachine = registry.localmachine;
key2 = localmachine.opensubkey(@"hardware\devicemap\serialcomm", false);
if (key2 != null)
{
string[] valuenames = key2.getvaluenames();
textarray = new string[valuenames.length];
for (int i = 0; i < valuenames.length; i++)
{
textarray[i] = (string)key2.getvalue(valuenames[i]);
}
}
}
finally
{
if (localmachine != null)
{
localmachine.close();
}
if (key2 != null)
{
key2.close();
}
codeaccesspermission.revertassert();
}
if (textarray == null)
{
textarray = new string[0];
}
return textarray;
}
#endregion
}
}
希望本文所述对大家的c#程序设计有所帮助。