[英]How to Send & Receive data in Serial-port in win-forms C#
I have been working on a card-reader application in Win-Forms C#.我一直在使用 Win-Forms C# 开发读卡器应用程序。 Below is my sample code.下面是我的示例代码。 It only reads once and shows the messagebox, after that it doesn't show again.它只读取一次并显示消息框,之后不再显示。 DataReceived event is not triggering a 2nd time. DataReceived 事件不会第二次触发。 I tested it in hyper-terminal and it works properly.我在超级终端中对其进行了测试,它运行正常。
C# sample Code:- C# 示例代码:-
SerialPort port = new SerialPort("COM3", 115200, Parity.Even, 8, StopBits.One);
try
{
if (port.IsOpen == true)
port.Close();
if (!port.IsOpen)
{
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
port.WriteLine("RI \n");
port.WriteLine("R100002 \n");
port.WriteTimeout = 300;
}
port.Close();
}
catch (Exception ex)
{
port.Close();
MessageBox.Show(ex.Message);
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
MessageBox.Show(sp.ReadExisting());
}
Does anybody having working sample code?有人有工作示例代码吗? Pls share any ideas to correct the issue.请分享任何纠正问题的想法。
You are closing the port immediately after writing.您在写入后立即关闭端口。 A closed port won't receive incoming data.关闭的端口不会接收传入的数据。
Don't close the port until you are done with it.在完成之前不要关闭端口。
here is my successful Tested code for card reader:-这是我成功的读卡器测试代码:-
I find out this combination from hyper-terminal, just try :)-我从超级终端中找到了这个组合,试试吧:)-
port.PortName = txt_Token_port_Name.Text;
port.BaudRate = Convert.ToInt32(txt_Token_Bud_rate.Text);
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = StopBits.One;
if (port.IsOpen == true)
port.Close();
if (port.IsOpen == false)
{
port.Open();
port.ReadTimeout = 3000;
port.Write("t\r");
port.Write("R1");
port.Write("00002");
txt_Token_TokenNo.Text = port.ReadLine();
port.Close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.