Thread: auto detect com ports using c

  1. #1
    Registered User
    Join Date
    Sep 2012
    Posts
    68

    auto detect com ports using c

    Hello everyone,
    Is there any way i can list the number of active com ports in my system using c,i have tried searching for it in msdn but there there is no code example for it in c

    If anyone has any idea pls share!!

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Yes, there are solutions, but what you're asking about is outside the scope of C. You need to read relevant documentation for your host (operating system, etc), since the solutions are system dependent.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Sep 2012
    Posts
    68
    Quote Originally Posted by grumpy View Post
    Yes, there are solutions, but what you're asking about is outside the scope of C. You need to read relevant documentation for your host (operating system, etc), since the solutions are system dependent.
    I am currently working on Windows 7 professional (32bit),compiler: gcc(codeblocks)
    Can you point me to the relevant document you mentioned.

  4. #4
    Registered User
    Join Date
    Sep 2012
    Posts
    68
    This is what i have got so far.I'm sure there must be a more efficient way of doing this

    Code:
    #include <stdio.h>
    #include <windows.h>
    #include <string.h>
    int main()
    {
        char port[] = "COM1";
        char port1[] = "\\\\\.\\";
        strcat(port1,port);
        int i = 0,j=49,k = 49;
        HANDLE hSerial;
        for(i = 0; i<=10; i++)
        {
            hSerial = CreateFile(port1, GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
            if(hSerial==INVALID_HANDLE_VALUE)
            {
                if(GetLastError()==ERROR_FILE_NOT_FOUND)
                {
                    //printf("\nError:Serial Port does not exist.");
                    //printf("Sub Error: ERROR_FILE_NOT_FOUND");
                    ;
                }
                //printf("\nSerial port communication error.\nSub Error: INVALID_HANDLE_VALUE");
                printf("Detecting port...");
                port1[strlen(port1)-1] = j;
                j++;
                if(j > 58)
                {
                    printf("\nAuto Detect feature is enabled only for COM1 to COM9\n");
                    break;
                }
                printf("%s\n",port1);
                ///End of Code for opening port
                //system("pause");
            }
            else
            {
                printf("Port opened.\n");
                break;
            }
        }
        return 0;
    }

  5. #5

  6. #6
    Registered User
    Join Date
    Sep 2012
    Posts
    68
    After some trying i was able to figure out a way of doing it.Quiet simply actually,nothing fancy.
    Any advice on improving it are welcome.
    Code:
    #if AUTO_COM
        printf("Detecting port...\n");
        Sleep(500);
        while(k < 258)  //0 to 256
        {
            hSerial = CreateFile(port, GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
            if(hSerial==INVALID_HANDLE_VALUE)
            {
                if(GetLastError()==ERROR_FILE_NOT_FOUND)
                {
                    com_check_flag = 1;
                }
                com_check_flag = 1;
            }
            else
            {
                com_check_flag = 0;
                printf("Detected port:  COM%d\n",k-1);
                Sleep(800);
            }
            if(com_check_flag == 1)
            {
                sprintf(port,"\\\\\.\\com%d",k);
                k++;
            }
            if(k > 257)
            {
                printf("Unable to detect port.\n");
                CloseHandle(hSerial);
                system("pause");
                exit(1);
            }
            if(com_check_flag == 0)
            {
                break;
            }
        }
    #endif
    hSerial is a HANDLE by the way.

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    You're suggesting that you can't simplify this?
    Code:
                if(GetLastError()==ERROR_FILE_NOT_FOUND)
                {
                    com_check_flag = 1;
                }
                com_check_flag = 1;
    I'd suggest giving your variables more descriptive names. A name 'k' is not exactly informative.

    Better not to use system() to implement a pause. There are plenty of ways to wait for user input without using a system call, that only involve one or two lines of code. Using a system call, in this case, has no justification apart from laziness and unwillingness to find practical alternatives.

    Windows usually only supports com ports COM1 through COM9.

    There is no need for the Sleep() calls.

    The loop logic, to say the least, is rather contorted. Try rewriting to avoid using the break keyword (or any other covert goto).
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    Registered User
    Join Date
    Sep 2012
    Posts
    68
    Quote Originally Posted by grumpy View Post
    You're suggesting that you can't simplify this?
    Code:
                if(GetLastError()==ERROR_FILE_NOT_FOUND)
                {
                    com_check_flag = 1;
                }
                com_check_flag = 1;
    I'd suggest giving your variables more descriptive names. A name 'k' is not exactly informative.

    Better not to use system() to implement a pause. There are plenty of ways to wait for user input without using a system call, that only involve one or two lines of code. Using a system call, in this case, has no justification apart from laziness and unwillingness to find practical alternatives.

    Windows usually only supports com ports COM1 through COM9.

    There is no need for the Sleep() calls.

    The loop logic, to say the least, is rather contorted. Try rewriting to avoid using the break keyword (or any other covert goto).
    Hello Mr. grupmy,
    *'k',in this case is a simple counter with a range of 0 to 257,changed its name y the way .
    *And i have been meaning to ask,when is it useful to use system() calls and when is it not?The reason why i used system("pause") here is because if my .exe file is out of my projects folder,and when the condition is met,the cmd window closes down before the user can view the error message.I can get the same function using getch() as well.
    *Com1 to com256 are supported in windows.To be able to access ports above com9,we need to add the "\\.\" before the comx port.(eg:\\.\com13).Found these details on msdn.
    * I used Sleep here as a kind of delay sequence.So that the user knows which port has been assigned/used.If there is a better way,please let me know.
    *The only way i can think of avoiding break is by checking the true condition in the while.
    Code:
    int com_check_flag  = 3; //something other than 0 or 1.
    while(k < 258 && com_check_flag != 0)  //0 to 256
    awaiting your reply..

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by ak47 View Post
    *And i have been meaning to ask,when is it useful to use system() calls and when is it not?
    Generally speaking, a system() call should be viewed as an absolute last resort. If it is possible to code something workable using available library facilities (in your case, the standard C library and win32 API) it is better to do that, rather than launching a separate process.

    Put it this way: in the last 20 years, I have only used a system() call three times. And that was to launch large, third-party, executables that were not available to me as source, where there was a legal agreement not to reverse-engineer, and [even if I had been at liberty to overlook that legal agreement] it would have taken several man years of effort to replicate. I certainly would not use a system call as an alternative to something that can be coded in less than a dozen lines.

    Quote Originally Posted by ak47 View Post
    * I used Sleep here as a kind of delay sequence.So that the user knows which port has been assigned/used.If there is a better way,please let me know.
    Unless the output written to stdout disappears too fast, slowing your program down achieves little. It would probably be better to display the information in some persistent manner, or wait for user input of some form before continuing.

    Quote Originally Posted by ak47 View Post
    *The only way i can think of avoiding break is by checking the true condition in the while.
    Other loop constructs (eg a for loop) and moving some code out of the loop, would help too. Given, for example, the fact that the handle is only closed if k exceeds 257 - which is also the last time the loop body is executed - there is no need for the handle closure to be inside the loop. Simply run the loop to completion, and then close the handle.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Ports
    By xniinja in forum C Programming
    Replies: 2
    Last Post: 06-23-2010, 12:41 PM
  2. auto detect variable value change - is it possible?
    By Yarin in forum C++ Programming
    Replies: 4
    Last Post: 07-17-2008, 12:41 PM
  3. ports
    By crvenkapa in forum Networking/Device Communication
    Replies: 2
    Last Post: 06-18-2007, 10:47 AM
  4. COM-ports
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 02-15-2002, 06:07 AM
  5. ports
    By ihsir in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 01-14-2002, 10:13 AM