从串行端口读取数据时出现问题 [英] Problem with reading data from serial port

查看:279
本文介绍了从串行端口读取数据时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我正在使用Visual Studio 2010在Windows7中进行串行通信.我正在使用串行到USB转换器通过串行连接在两台计算机之间进行通信.最初,我通过串行端口发送数据,并且在另一台PC的超级终端上接收到该数据.接下来,我尝试从端口读取数据,但提示以下异常:

System.dll中发生了类型为"System.IO.IOException"的未处理的异常
附加信息:所请求的资源正在使用中.

这是代码.它是MSDN库帮助中的示例代码,应该可以使用.

Hello,
I am using visual studio 2010 for serial communication in windows7. I am using a serial to USB converter to communicate between two computers via serial connection. Initially I sent data through serial port and it was received on the hyperterminal on the other PC. Next I tried to read data from the port but it prompted following exception:

An unhandled exception of type ''System.IO.IOException'' occurred in System.dll
Additional information: The requested resource is in use.

Here is the code. Its a sample code from MSDN library help and it was supposed to work.

#using <system.dll>

using namespace System;
using namespace System::IO::Ports;
using namespace System::Threading;

public ref class PortChat
{
private:
    static bool _continue;
    static SerialPort^ _serialPort;

public:
    static void Main()
    {
        String^ name;
        String^ message;
        StringComparer^ stringComparer = StringComparer::OrdinalIgnoreCase;
        Thread^ readThread = gcnew Thread(gcnew ThreadStart(PortChat::Read));

        // Create a new SerialPort object with default settings.
        _serialPort = gcnew SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort->PortName = SetPortName(_serialPort->PortName);
        _serialPort->BaudRate = SetPortBaudRate(_serialPort->BaudRate);
        _serialPort->Parity = SetPortParity(_serialPort->Parity);
        _serialPort->DataBits = SetPortDataBits(_serialPort->DataBits);
        _serialPort->StopBits = SetPortStopBits(_serialPort->StopBits);
        _serialPort->Handshake = SetPortHandshake(_serialPort->Handshake);

        // Set the read/write timeouts
   //     _serialPort->ReadTimeout = 500;
   //     _serialPort->WriteTimeout = 500;

        _serialPort->Open();
        _continue = true;
        readThread->Start();

     //   Console::Write("Name: ");
     //   name = Console::ReadLine();

        Console::WriteLine("Type QUIT to exit else press Enter");

        while (_continue)
        {
            message = Console::ReadLine();

            if (stringComparer->Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
             

				// This is how u will send data from COM Port.
				// name = Console::ReadLine();
				// _serialPort->WriteLine(name);

				// This is how u will recieve data from your COM Port
				String^ message = _serialPort->ReadLine();
                Console::WriteLine(message);


			 }
			
        }

        readThread->Join();
        _serialPort->Close();
    }
	
    static void Read()
    {
        while (_continue)
        {
            try
            {
                String^ message = _serialPort->ReadLine();
                Console::WriteLine(message);
            }
            catch (TimeoutException ^) { }
        }
    }

    static String^ SetPortName(String^ defaultPortName)
    {
        String^ portName;

        Console::WriteLine("Available Ports:");
        for each (String^ s in SerialPort::GetPortNames())
        {
			Console::WriteLine("   {0}",s);
        }

		Console::Write("COM port({0}): ", defaultPortName);
        portName = Console::ReadLine();

        if (portName == "")
        {
            portName = defaultPortName;
        }
        return portName;
    }

    static Int32 SetPortBaudRate(Int32 defaultPortBaudRate)
    {
        String^ baudRate;

        Console::Write("Baud Rate({0}): ", defaultPortBaudRate);
        baudRate = Console::ReadLine();

        if (baudRate == "")
        {
            baudRate = defaultPortBaudRate.ToString();
        }

        return Int32::Parse(baudRate);
    }

    static Parity SetPortParity(Parity defaultPortParity)
    {
        String^ parity;

        Console::WriteLine("Available Parity options:");
        for each (String^ s in Enum::GetNames(Parity::typeid))
        {
            Console::WriteLine("   {0}", s);
        }

        Console::Write("Parity({0}):", defaultPortParity.ToString());
        parity = Console::ReadLine();

        if (parity == "")
        {
            parity = defaultPortParity.ToString();
        }

        return (Parity)Enum::Parse(Parity::typeid, parity);
    }

    static Int32 SetPortDataBits(Int32 defaultPortDataBits)
    {
        String^ dataBits;

        Console::Write("Data Bits({0}): ", defaultPortDataBits);
        dataBits = Console::ReadLine();

        if (dataBits == "")
        {
            dataBits = defaultPortDataBits.ToString();
        }

        return Int32::Parse(dataBits);
    }

    static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        String^ stopBits;

        Console::WriteLine("Available Stop Bits options:");
        for each (String^ s in Enum::GetNames(StopBits::typeid))
        {
            Console::WriteLine("   {0}", s);
        }

        Console::Write("Stop Bits({0}):", defaultPortStopBits.ToString());
        stopBits = Console::ReadLine();

        if (stopBits == "")
        {
            stopBits = defaultPortStopBits.ToString();
        }

        return (StopBits)Enum::Parse(StopBits::typeid, stopBits);
    }

    static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        String^ handshake;

        Console::WriteLine("Available Handshake options:");
        for each (String^ s in Enum::GetNames(Handshake::typeid))
        {
            Console::WriteLine("   {0}", s);
        }

        Console::Write("Handshake({0}):", defaultPortHandshake.ToString());
        handshake = Console::ReadLine();

        if (handshake == "")
        {
            handshake = defaultPortHandshake.ToString();
        }

        return (Handshake)Enum::Parse(Handshake::typeid, handshake);
    }
};

int main()
{
    PortChat::Main();
}
</system.dll>



此行中出现例外:



The exception appears in this line:

String^ message = _serialPort->ReadLine();



谁能帮忙.预先感谢.



Can anyone help. Thanks in advance.

推荐答案

提示在错误消息中:请求的资源正在使用中"
您需要找到正在使用所选USB端口的端口,如果转换器在该端口上,请使用其他端口,或者禁用正在使用的端口.这不太可能是代码问题:这是环境问题.
The clue is in the error message: "The requested resource is in use"
You need to find what is using the USB port you have selected, and either use a different one if your converter is on that, or disable whatever is using it. This is not likely to be a code problem: it is an environment problem.


SerialPort类不是线程安全的.您需要同步跨线程对任何类成员的访问.
The SerialPort class is not thread safe. You need to synchronise access to any class members across threads.


这篇关于从串行端口读取数据时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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