Go Down

Topic: Auto detect com port (Read 1 time) previous topic - next topic

Juniorjrjr

Hello!
I need to know how to detect the port which arduino is plug in. It needs to be in C language for windows.
Thanks!

Klaus_K

The Arduino IDE sometimes has difficulties with this, so I would not keep my hopes up. Depending on the board this changes every time the board is reset or flashed. Because COM ports are not used much anymore nowadays, I would just ask Windows to give me all available and if there is more than one, ask the user to select the right one.

Regarding the Windows code, looks like when you Google "C# com port" you get some nice examples from Microsoft in the first hit. :)

Juniorjrjr

#2
Nov 17, 2019, 03:51 am Last Edit: Nov 17, 2019, 04:00 am by Juniorjrjr
Thanks for reply!

I didn't understand what you wrote.

In my C program what I'm using is char[] that has value something like "COM2"; what I need to know is if is there a way to get the this com name which the arduino is connected?

Something like:   FILE *fp = popen("readlink -f /dev/serial/by-id/*Arduino*", "r"); this works on linux, but I need it for windows, will this work on windows too?

Thanks!

Klaus_K

When you say C program, you mean you are writing a program which will be running on the Windows PC and not on the Arduino. Yes?

You want your Arduino to send some data to the PC and instead of showing it in the Serial Monitor of the Arduino PC you want to do something with the data in your program. Right?

What software do you use to write and compile the PC software?

Juniorjrjr

Hi! Thanks for the reply!

Yes. I have an aplication in c language(when I end this app, I'll generate .exe), and the arduino is sending data to the C program. But it only works the COM PORT 2, for example, because I pass a char array to HANDLE, and what I want now is that C program detects where the arduino comm port is.

I'm using Visual Studio to write the c code.

Klaus_K

When you connect your Arduino to the PC the PC will detect a USB device. The USB device will tell the operating system what the capabilities are. A few of the capabilities have been standardized like keyboard, mouse, mass storage and serial port. If it is not standard the user has to install a special driver. But this is not the case for serial. Windows will just use a standard driver and assign a COM port. Windows can change this number every time you disconnect the device. When you reprogram the Arduino or reset it, it will disconnect USB and connect again.

So your program will need to be able to choose a COM port dynamically.

Because Windows assigns the COM port, you will need to use Windows methods to figure out which COM ports are available.

Microsoft has many examples and good documentation on their website. You can Google search

e.g. "Visual Studio get all available COM ports"

https://docs.microsoft.com/de-de/dotnet/api/system.io.ports.serialport.getportnames?view=netframework-4.8

So when you get the list of COM ports and it is only one item, you can assume it is your Arduino and you try to connect to it. When there are multiple COM ports in the list, you ask the user of your program which COM port should be used.

sterretje

#6
Nov 17, 2019, 04:36 pm Last Edit: Nov 17, 2019, 04:41 pm by sterretje
I've asked a moderator to move this to a more suitable section.

Once I have time and access to a PC, I will try to find a solution.

A number of arduinos can identify themselves, others can't; in that case you have to open every port till you know that you have the right port, and the arduino has to identify itself with e.g. "hi, arduino here".
If you understand an example, use it.
If you don't understand an example, don't use it.

Electronics engineer by trade, software engineer by profession. Trying to get back into electronics after 15 years absence.

GolamMostafa

In my Laptop, there is no traditional 9-pin asysnc COM (UART) Ports. I engage my Arduino UNO with a USB Port. In the IDE and before uploading a sketch, I choose/select so called COMX Port even sometimes as COM53. Someone may please explain what is this COM Port; certainly it is not physical COM Port; virtual COM Port? How is it formed?   

CrossRoads

I use FTDI chips almost exclusively for USB. You can use Windows setting tools and make the port assignment what you want, and it sticks with the hardware. Other interface chips might be more dynamic.
Designing & building electrical circuits for over 25 years.  Screw Shield for Mega/Due/Uno,  Bobuino with ATMega1284P, & other '328P & '1284P creations & offerings at  my website.

Klaus_K

#9
Nov 17, 2019, 07:16 pm Last Edit: Nov 17, 2019, 07:21 pm by Klaus_K
GolamMostafa, it is a virtual COM port.

Engineers used COM ports for such a long time that they could not give them up. :) They are just too easy to use. Once they are configured you push one byte in and one byte comes out at the other side.

So, within the USB specification a class was defined (Communications and CDC Control) that mimics this behavior. Because the speed on the USB are higher, you can even do other stuff while you are transferring the data for the serial port "emulation". These other things are separated by having different endpoints (USB term for channel).

So, when you connect a USB device to your PC. The operating system finds out there is a CDC endpoint and starts the driver for a COM port.

On your Arduino board the problem is solved in two different ways.

- Some boards have a special chip that will take the serial data the microcontroller sends out and provide it to the PC over USB.

- Some newer boards have a direct USB connection. Here the USB peripherals of the microcontroller is used by a library that is automatically compiled/linked into your code. The USB code runs in between your code without you noticing.

If you want to know more you can
- read the USB description on Wikipedia
- Google USB endpoints, descriptors, CDC class
- download the USB specification from usb.org (not recommended unless you have insomnia)

Juniorjrjr

Thanks for all the replies!

I'm searching for a solution on google, but what I've found next of a good solution is following:

Code: [Select]
#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;
}


But it just goes by COM1 to COM9. And it don't find where the arduino is connected. I found another solution:

https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcommports

but it needs to pass an array and how can I know how many com ports in a PC? and then if I have to find how many it is. how can I know if the arduino is connected in that com port?

Another solutions is accept!

Thanks!


Klaus_K

You cannot find out whether there is an Arduino connected to the COM port or something else. If your Arduino is sending data trough the COM port you can read it. You can send a magic series of bytes between your program and the Arduino to tell the program if found the right COM port.

Right now you find out why we do not use COM ports anymore. They where easy for engineers but they sucked for the end users. End user did not know what baudrate, parity and all the other stuff means. :)

Now users have any easy live and engineers need to learn about USB, which sucks for old school electronic engineers, because the specification is very abstract and uses more of a software terminology and constructs.

Juniorjrjr

Thanks for the reply!

How can I search for this new way of communication(USB) on the internet?

I'm searching but what I've found is just about COM PORTS.

And in C language, it is possible to do with this new way of communication?

Thanks!

Klaus_K

This is way more complicated than you think. Unless you want to create a commercial product or you have a lot of time and are keen to crack this problem, I think you should just ask the user to select the COM port manually. And do not forget, if you create your own USB device and sell it to other people, you will need to pay some money to the USB organization.

To get you started go to Youtube and search for "USB protocol".

From what I have seen, there are Arduino examples that make the Arduino behave like a keyboard or mouse. This can be your starting point to write the software for the Arduino to behave as a USB device.

If your USB device is something already standardized in the USB specification, you can write your software to make use of standard USB drivers. If it is something unique. You will need to create your own Windows USB driver. Google "visual studio usb driver development". Microsoft has you covered. :)

Then you need to write your program to attach to the driver and do whatever your program and hardware is supposed to do.


What is your application? Maybe there is an easier way to do things.

Juniorjrjr

My app is for make a joystick module controls the character's moviment in a game.

It is almost done, but I have just this problem to solve.

Go Up