C# SerialPort.DataReceived isn';t为Windows应用程序启动,在控制台应用程序net2.0中运行良好
将C# SerialPort.DataReceived isn';t为Windows应用程序启动,在控制台应用程序net2.0中运行良好,c#,.net-2.0,C#,.net 2.0,将mySerialPort变量放在ReadSP函数之外,否则该函数完成时将被销毁。在另一个函数中关闭端口。您已经注释掉了写入串行端口的行,因此在我看来,您没有向串行端口发送任何数据,因此可能这就是没有收到请求的原因 对于测试,我建议使用“环回”,它基本上连接串行端口上的rx和tx线路。你可以用一个金属回形针来做这件事——只要把每一端都插进针脚2和针脚3 设置label1两次和ASCII.GetString()x3有点乱,但这里没有明显的问题。你能把“不工作”说得再好一点吗?症状、调试结果?此代码
mySerialPort
变量放在ReadSP
函数之外,否则该函数完成时将被销毁。在另一个函数中关闭端口。您已经注释掉了写入串行端口的行,因此在我看来,您没有向串行端口发送任何数据,因此可能这就是没有收到请求的原因
对于测试,我建议使用“环回”,它基本上连接串行端口上的rx和tx线路。你可以用一个金属回形针来做这件事——只要把每一端都插进针脚2和针脚3 设置
label1
两次和ASCII.GetString()
x3有点乱,但这里没有明显的问题。你能把“不工作”说得再好一点吗?症状、调试结果?此代码在控制台模式应用程序中不起作用。当然,在调用Open()之后立即调用Close()是行不通的。是的,就是这样。更具体地说,是该方法末尾的Close()语句。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace ReadWieght
{
public partial class Form1 : Form
{
public delegate void UpdateTextCallback(string text);
private void Form1_Load(object sender, EventArgs e)
{
ReadSP();
}
void ReadSP()
{
SerialPort mySerialPort = null;
mySerialPort = new SerialPort("COM1");
mySerialPort.BaudRate = 2400;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.RequestToSend;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
try
{
mySerialPort.Open();
// mySerialPort.Write(str.Trim());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
mySerialPort.Close();
}
// Updates the textbox text.
private void UpdateText(string text)
{
// Set the textbox text.
label1.Text = text;
}
//static string text = null;
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Invoke(new UpdateTextCallback(this.UpdateText), new object[] { "DATA RECIEVED" });
try
{
SerialPort sp = (SerialPort)sender;
byte[] comBuffer = new byte[sp.BytesToRead];
sp.Read(comBuffer, 0, sp.BytesToRead);
Console.WriteLine(Encoding.ASCII.GetString(comBuffer));
// char[] chr = Encoding.ASCII.GetString(comBuffer);
string str = Encoding.ASCII.GetString(comBuffer);
if (str.Length > 7)
{
str = str.Substring(2, 6);
this.Invoke((MethodInvoker)delegate
{
label1.Text = str; // runs on UI thread
});
}
Encoding.ASCII.GetString(comBuffer);
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
this.Invoke((MethodInvoker)delegate
{
label1.Text = ex.Message; // runs on UI thread
});
}
}
public Form1()
{
InitializeComponent();
}
}
}