Control Arduino Using C++ program

Hi guys. My question is that is it possible to control the Arduino using a C++ program. For example, I want to set an analog output pin between 0V and 3.3V during the execution of my C++ program. I did some research and find that serial control may be an option. However, could anyone give me an example on how to integrate serial control codes for Arduino into a C++ code?

a162060505:
Hi guys. My question is that is it possible to control the Arduino using a C++ program.

This is sort of confusing, since the Arduino language is C++.
I guess you mean you want to communicate with an Arduino C++ program using a PC C++ program.

For example, I want to set an analog output pin between 0V and 3.3V during the execution of my C++ program. I did some research and find that serial control may be an option. However, could anyone give me an example on how to integrate serial control codes for Arduino into a C++ code?

Just send normal serial data from your PC program using ‘CreateFile()’ then ‘WriteFile()’, or whatever method you like to use, then have the Arduino decode the serial data and turn the LED on. A good method is to send ‘<‘your data’>’.
Then in your Arduino code, you can wait for ‘<’, extract the data until you get to ‘>’, and act upon it. You could either send ASCII or raw data - that’s up to you. Just create your own ‘control codes’, as you call them.
(Or did you want someone to write the PC code for you?)

The examples in Serial Input Basics are simple reliable ways to receive data in the Arduino. The 3rd example is pretty much as @OldSteve recommends. Design your PC program to be compatible.

If you are not obliged to use C++ on your PC you may be interested in this Python - Arduino demo. The same concept is applicable in any PC language.

...R

Here’s the PC C++ code I wrote a couple of years ago for my alarm clock auto-update. You might be able to use it as a bit of a guide. It might (or might not) be useful. (I didn’t use <>, but a 4-character qualifier instead in that case.) I won’t post the micro code, because it was in Basic, (PICBasic Pro), for a PIC16F84A, so won’t be relevant.

bool OpenCOMPort()
{
    COMMTIMEOUTS cto;
    COMMCONFIG cc;
    hCOMPort = CreateFile(
        szFullCOMPortName,
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        0,
        NULL);
    if (hCOMPort == INVALID_HANDLE_VALUE)
    {
        hCOMPort = NULL;
        return false;
    }
    // Configure the port:-
    GetCommState(hCOMPort, &cc.dcb);
    cc.dcb.BaudRate = BAUD_RATE;
    cc.dcb.ByteSize = 8;
    cc.dcb.StopBits = ONESTOPBIT;
    cc.dcb.Parity = NOPARITY;
    cc.dcb.fDtrControl = DTR_CONTROL_DISABLE;
    cc.dcb.fRtsControl = RTS_CONTROL_DISABLE;
    if (!SetCommState(hCOMPort, &cc.dcb))
    {
        CloseHandle(hCOMPort);
        hCOMPort = NULL;
        return false;
    }
    GetCommTimeouts(hCOMPort, &cto);
    cto.ReadIntervalTimeout = 20;
    cto.ReadTotalTimeoutMultiplier = 50;
    cto.ReadTotalTimeoutConstant = 500;
    cto.WriteTotalTimeoutMultiplier = 10;
    cto.WriteTotalTimeoutConstant = 100;
    if (!SetCommTimeouts(hCOMPort, &cto))
    {
        CloseHandle(hCOMPort);
        hCOMPort = NULL;
        return false;
    }
    return true;
}

bool SetRTCTimeDate(RTCTIMEDATE rtctd)
{
    DWORD dwBytesWritten = 0;
    DWORD dwBytesRead;
    bool fRetVal;
    // Open the COM port:-
    if (!OpenCOMPort())
        return false;

    // Send the 19-byte data packet to the RTC module:-
    byte bDummy = 255;
    for (int x = 0; x < 20; x++)
        WriteFile(hCOMPort, (LPCVOID)&bDummy, 1, &dwBytesWritten, NULL);
    Sleep(1);
    fRetVal = WriteFile(hCOMPort, (LPCVOID)&rtctd, 17, &dwBytesWritten, NULL);
    if (!fRetVal)
    {
        CloseHandle(hCOMPort);
        return false;
    }
    WriteFile(hCOMPort, (LPCVOID)&rtctd.wCheckSum, 2, &dwBytesWritten, NULL);

    // Now get the response, ('ACK'):-
    byte bInPacket[16];
    // First get the (4-byte) host ID:-
    fRetVal = ReadFile(hCOMPort, &bInPacket, 4, &dwBytesRead, NULL);
    if ((!fRetVal) || (dwBytesRead != 4)) // ReadFile() failed.
    {
        CloseHandle(hCOMPort);
        return false;
    }
    bInPacket[4] = '\0'; // Add a temporary terminating zero.
    if (strcmp((char*)bInPacket, "HOST") != 0)                                  // Failed to get the correct Host ID.
    {
        CloseHandle(hCOMPort);
        return false;
    }
    else
    {
        // Got a valid Host ID, so now get the remaining 12 bytes:-
        fRetVal = ReadFile(hCOMPort, &bInPacket[4], 12, &dwBytesRead, NULL);    // No 'overlapped' structure
        // Get the original checksum from the received data packet:-
        WORD wOrigCheckSum = bInPacket[14] | (bInPacket[15] * 256);
        // Calculate the new checksum for the received data:-
        WORD wCheckSum = 0;                                                     // This MUST be zeroed before proceeding.
        for (int i = 0; i < 14; i++)
            wCheckSum += bInPacket[i];
        // Do the comparison:-
        if (wCheckSum != wOrigCheckSum)                                         // Bad checksum.
        {
            CloseHandle(hCOMPort);
            return false;
        }
        // Now get and check the opcode:-
        WORD* pwOpcode = (WORD*)&bInPacket[4];
        if (*pwOpcode != OC_ACK)
        {
            CloseHandle(hCOMPort);
            return false;
        }
    }
    CloseHandle(hCOMPort);
    return true;
}

@OldSteve, I am not a C++ expert but it seems as if the function in your code opens and closes the serial port.

That is generally a bad idea with an Arduino because the Arduino resets every time the port is opened. I would recommend opening the port at the start of the PC program and keeping it open until the PC program is completely finished with the Arduino.

...R

Robin2:
@OldSteve, I am not a C++ expert but it seems as if the function in your code opens and closes the serial port.

That is generally a bad idea with an Arduino because the Arduino resets every time the port is opened. I would recommend opening the port at the start of the PC program and keeping it open until the PC program is completely finished with the Arduino.
...R

I didn't modify it for an Arduino. It was just intended as a guide on 'how' to open and close the port, not 'when'.
There's nothing to stop the OP from opening and closing the port whenever he wants.

OldSteve:
I didn't modify it for an Arduino.

Thanks for the clarification.

...R

Robin2:
Thanks for the clarification.
...R

No problem. I probably didn't make that clear enough originally. That was the code I used to communicate with a PIC chip, just copied 'as-is', for a guide to the methods. The communication was via a USB to TTL converter and an APC220 433MHz RF transceiver, too, not a direct connection. The methods of opening and closing the PC COM port are the same though.