【问题标题】:How do I open the COM port specified by user?如何打开用户指定的 COM 端口?
【发布时间】:2019-11-17 19:51:35
【问题描述】:

我正在尝试打开用户输入提供的 COM 端口。我尝试了以下代码并打印了错误消息“打开串行端口时出错”。

int main()
{
    BOOL Status;
    HANDLE ComPort;
    char* ptr;
    char str[] = {'\\','\\','\\','\\','.','\\','\\','C','O','M','\0','\0','\0','\0'};
    printf("Enter COM Port: ");
    ptr = str + 10;
    fgets(ptr,4,stdin);
    size_t len = strlen(str);
if (len > 0 && str[len-1] == '\n') {
  str[--len] = '\0';
}
    ComPort = CreateFile((const char*)str,                //port name
                      GENERIC_READ | GENERIC_WRITE, //Read/Write
                      0,                            // No Sharing
                      NULL,                         // No Security
                      OPEN_EXISTING,// Open existing port only
                      0,            // Non Overlapped I/O
                      NULL);        // Null for Comm Devices

  if (ComPort == INVALID_HANDLE_VALUE){
      printf("Error in opening serial port");
      exit(EXIT_FAILURE);}
  else{
      printf("opening serial port successful");
  }
 .....
 ...

那么我做错了什么?

【问题讨论】:

  • 首先尝试以管理员身份运行。否则您可能无权打开端口。
  • @MikeWodarczyk 我在代码块上运行它
  • 您可能需要通过右键单击并以管理员身份运行来运行代码块。
  • @chux-ReinstateMonica 代码执行命令 printf("Error in opening serial port");而不是 printf("打开串口成功");
  • 我使用的输入是 5。

标签: c windows serial-port


【解决方案1】:

前缀'\\','\\','\\','\\','.','\\','\\' 错误。见"\\.\COM10"

原始代码无法处理读取'\n'

读取一行,然后形成 com 端口名称。

//char* ptr;
//char str[] = {'\\','\\','\\','\\','.','\\','\\','C','O','M','\0','\0','\0','\0'};
//ptr = str + 10;
//fgets(ptr,4,stdin);
//ComPort = CreateFile((const char*)str,  

char buffer[80]; // be generous
fgets(buffer, sizeof buffer, stdin);
buffer[strcspn(buffer, "\n")] = '\0'; // lop off potential \n

char str[sizeof buffer + 7] =  "\\\\.\\COM";  // Use correct prefix
strcpy(str, buffer);
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 2011-08-20
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2012-07-27
    相关资源
    最近更新 更多