如何与串口连接 [英] how to connect with serial port

查看:140
本文介绍了如何与串口连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨..
我是Windows应用程序的新手..im使用vs 2005和c#asp.net.
现在,我想通过代码和示例来了解串行端口通信(例如:台式机阅读器).请帮助我

Hi..
Im new for windows applications.. im using vs 2005 and c# asp.net.
Now i want to know abt serial port communication(Ex:desktop reader) with code and example..Pls help me

推荐答案

您好,要使用serialPort,您需要有关字节,十六进制等的一些知识.
首先,您需要将工具箱中的串行端口添加到表单中,然后设置其COM端口号,缓冲区等.
要与串行端口通信,首先需要始终"打开串行端口,例如:
serialPort1.Open();
(如果端口已全部打开,然后尝试再次打开,则会出现异常错误.为防止这种情况,您应该键入以下代码:

if(!serialPort.isopen)
serialPort.Open();

要发送数据,您还需要创建一个字节数组变量,例如:
字节[]数据=新字节[20];

然后发送,只需调用此函数

serialPort1.write(data,0,15);
此函数会将您的数据数组从其第一个单元格发送到第15个单元格.

要接收数据,您必须选择:
1.选择serialport1.DataReceived事件
2.或设置一个计时器来检查缓冲区中是否有大量数据
(还要检查缓冲区中数据的可用性,您需要检查
serialPort1.ReadBufferSize.此数字显示缓冲区中的数据量.


请注意,缓冲区中红色的数据将被删除.
Hi, to use serialPort you need to have some knowledge about byte, hex ect.
First, you need to add serialport from your toolbox to your form and then set it''s com port number, buffer ect.
To communicate with serial port, you need "always" at first to open serialport like:
serialPort1.Open();
(if the port is allready opened and you try to open again, there will be an exception error. to prevent this you shoul type this code :

if(!serialPort.isopen)
serialPort.Open();

to send data you need too create a byte array variable like :
byte[] data = new byte[20];

then for sending you need just call this function

serialPort1.write(data,0,15);
this function will send your data array from it''s first cell to the 15th.

to receive data you have to choise :
1.choiseing serialport1.DataReceived event
2. or set a timer to check if there are somme data in your buffer or not
( too check the availability of data in your buffer you need to check
serialPort1.ReadBufferSize. This number show the amount of data in your buffer.


Be careful, the data red from your buffer will be erased.


这篇关于如何与串口连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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