gpt4 book ai didi

c# - 访问串行端口时信号量超时?

转载 作者:太空宇宙 更新时间:2023-11-03 11:11:15 24 4
gpt4 key购买 nike

我在 C# 中打开串行端口时遇到了这个问题(这应该很简单;或者我是这么认为的)。

当我尝试打开串口时,出现以下异常:

The semaphore time-out period has expired.‎

这是执行此操作的方法。

public static void Open_TheActivePortWeWillUse(String Drone_StringNameFromUser)
{
var TempSerialPort = new SerialPort (
Drone_StringNameFromUser,
(int) SerialPortParameter.TheSerialPortSpeed);

// Now we have a name that anybody can see and use
OurSpecificPorts.TheActivePortWeAreUsing = TempSerialPort;
// We'll do 8-N-1 since almost the whole planet does that
OurSpecificPorts.TheActivePortWeAreUsing.DataBits = 8;
// We'll do 8-N-1
OurSpecificPorts.TheActivePortWeAreUsing.Parity = Parity.None;
// We'll do 8-N-1
OurSpecificPorts.TheActivePortWeAreUsing.StopBits = StopBits.One;

OurSpecificPorts.TheActivePortWeAreUsing.DataReceived +=
OurBackGroundSerialPortReceiver;
// We can now open our active port, which is what this line does
OurSpecificPorts.TheActivePortWeAreUsing.Open();
}

对我来说最奇怪的是我不一致地得到这个错误。 一半时间它工作正常,而另一半时间,它不

有人看到我的代码有什么明显的错误吗?我错过了什么吗?

最佳答案

在方法内声明您的 SerialPort 对象将不允许在方法关闭后访问它。这是一种打开端口的方法:

  private void OpenSerialPort(String portName)
{
try
{
serialPort1.Close();
serialPort1.PortName = portName;
serialPort1.BaudRate = 115200;
serialPort1.DataBits = 8;
serialPort1.Handshake = Handshake.None;
serialPort1.Parity = Parity.None;
serialPort1.RtsEnable = false;
serialPort1.StopBits = StopBits.One;

serialPort1.Open();

}
catch (Exception ex)
{
MessageBox.Show("Could not open serial port " + portName, "Error");
}
}

类中声明了SerialPort对象:

namespace Arcadia
{
public partial class Form1 : Form
{
private SerialPort serialPort1;

并在构造函数中添加回调:

    public Form1()
{
InitializeComponent();

serialPort1.DataReceived += new SerialDataReceivedEventHandler(this.SerialPortReadCallback);

发送数据的处理方式不同:

    private void SerialPortWrite(String writeString)
{
if (serialPort1.IsOpen)
{
serialPort1.WriteLine(writeString);
}
}

这是接收到的数据回调:

    private void SerialPortReadCallback(object sender, SerialDataReceivedEventArgs args)
{
try
{

while (serialPort1.BytesToRead > 0)
{
// Do something with the data

}
}
catch (Exception ex)
{
}
}

关于c# - 访问串行端口时信号量超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13977175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com