为什么我的程序可以打开COM1但不能打开COM11?

时间:2022-06-07 18:52:36

I have tried to read data from sensors. The sensors controller is using db9 header (com1), because I will use com1, I use db9 to usb converter and get com 11.

我试图从传感器读取数据。传感器控制器使用db9 header(com1),因为我将使用com1,我使用db9到usb转换器并获得com 11。

I have program to read and write to the serial port, it work when I use com1, but when I change to com 11, the program fail to open the com because it reach ERROR_FILE_NOT_FOUND

我有程序读取和写入串口,它在我使用com1时工作,但当我更改为com 11时,程序无法打开com,因为它达到了ERROR_FILE_NOT_FOUND

here is my program for the serial port programming:

这是我的串口编程程序:

Serial::Serial(char *portName)

{

this->connected = false;

wchar_t wcPort[64];
 size_t convertedChars = 0;
 mbstowcs_s(&convertedChars, wcPort, strlen(portName), portName, _TRUNCATE);

 this->hSerial = CreateFile(wcPort,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);

//Check if the connection was successfull
if(this->hSerial==INVALID_HANDLE_VALUE)
{
    //If not success full display an Error
    if(GetLastError()==ERROR_FILE_NOT_FOUND){

        //Print Error if neccessary
        printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);

    }
    else
    {
        printf("ERROR!!!");
    }
}
else
{

    DCB dcbSerialParams = {0};


    if (!GetCommState(this->hSerial, &dcbSerialParams))
    {

        printf("failed to get current serial parameters!");
    }
    else
    {


    dcbSerialParams.BaudRate=CBR_38400;
        dcbSerialParams.ByteSize=8;
        dcbSerialParams.StopBits=ONESTOPBIT;
        dcbSerialParams.Parity=NOPARITY;
        dcbSerialParams.fOutX=TRUE;
        dcbSerialParams.fInX=TRUE;



         if(!SetCommState(hSerial, &dcbSerialParams))
         {
            printf("ALERT: Could not set Serial Port parameters");
         }
         else
         {

             this->connected = true;


         }
    }
}

}

Is it because the software/program or the hardware problem?

是因为软件/程序还是硬件问题?

when I try with hyperterminal, it can read and write the com 11.

当我尝试使用超级终端时,它可以读写com 11。

1 个解决方案

#1


3  

To open COM ports numbered 10 and higher, you need to prefix the name with \\.\.

要打开编号为10或更高的COM端口,您需要在名称前加上\\。\。

Now, in C, you must escape all those backslashes. So the port you need to open is "\\\\.\\COM11".

现在,在C中,你必须逃避所有这些反斜杠。所以你需要打开的端口是“\\\\。\\ COM11”。

#1


3  

To open COM ports numbered 10 and higher, you need to prefix the name with \\.\.

要打开编号为10或更高的COM端口,您需要在名称前加上\\。\。

Now, in C, you must escape all those backslashes. So the port you need to open is "\\\\.\\COM11".

现在,在C中,你必须逃避所有这些反斜杠。所以你需要打开的端口是“\\\\。\\ COM11”。