简体   繁体   中英

Serial Comms between Microsoft Visual C++ 2010 and Arduino UNO via USB

I need to establish a serial comm between Microsoft Windows Visual C++ 2010 and an Arduino microcontroller via USB. A motion tracking algorithm produces an X and Y coordinate which needs to be sent to the Arduino which in turn controls two pan and tilt servos.

I am a final year mechanical engineering student and have very little experience with Microsoft Visual Studios and C++, so please bear with me and please forgive me if my terms are incorrect...

I have done extensive research on multiple forums, but cannot find an answer specific to my problem:

All the solutions that I have come across only support comms when a normal/"empty" project is created in Visual Studios. An example can be found here: Serial communication (for Arduino) using Visual Studio 2010 and C

When I try and debug the same body of code (which successfully runs in an "empty" project) in a "Win32 Console Application" project, I am presented with the following errors:

error C2065: 'LcommPort' : undeclared identifier error C2228: left of '.c_str' must have class/struct/union

Unfortunately I cannot simply change my project from a "Win32 Console Application" to a normal "Empty" project due to the fact that the motion tracking algorithm necessitates the use of the console application type of project.

The main body of code that I am using is as follows (this is a simplified test source file to confirm whether comms are established between MS Visual and the Arduino where the frequency at which an LED turns on and off is altered through the serial connection):

    #include <Windows.h>
    #include "ArduinoSerial.h"
    #include "StdAfx.h"

    int main() {
        try {
            ArduinoSerial arduino( "COM3" );

            Sleep( 2000 ); // Initial wait to allow Arduino to boot after reset

            char buffer[] = { 25, 100 };
            arduino.Write( buffer, 2 ); // Send on/off delays to Arduino (if return value is 0, something went wrong)
        }
        catch ( const ArduinoSerialException &e ) {
            MessageBoxA( NULL, e.what(), "ERROR", MB_ICONERROR | MB_OK );
        }

        return 0;
    }

The corresponding source code which is the home of the error is found in line9 of the code:

#include <algorithm>
#include <sstream>
#include <Windows.h>
#include "stdafx.h"

#include "ArduinoSerial.h"

ArduinoSerial::ArduinoSerial( const std::string commPort ) {
    comm = CreateFile( TEXT( commPort.c_str() ),
                       GENERIC_READ | GENERIC_WRITE,
                       0,
                       NULL,
                       OPEN_EXISTING,
                       0,
                       NULL );

    if ( comm == INVALID_HANDLE_VALUE ) {
        std::ostringstream error;
        error << "Unable to acquire handle for " << commPort << ": ";

        DWORD lastError = GetLastError();

        if ( lastError == ERROR_FILE_NOT_FOUND ) {
            error << "Invalid port name";
        }
        else {
            error << "Error: " << lastError;
        }

        throw ArduinoSerialException( error.str() );
    }

    DCB dcb;
    SecureZeroMemory( &dcb, sizeof DCB );
    dcb.DCBlength = sizeof DCB;
    dcb.BaudRate = CBR_9600;
    dcb.ByteSize = 8;
    dcb.StopBits = ONESTOPBIT;
    dcb.Parity = NOPARITY;
    dcb.fDtrControl = DTR_CONTROL_ENABLE;

    if ( !SetCommState( comm, &dcb ) ) {
        CloseHandle( comm );

        std::ostringstream error;
        error << "Unable to set comm state: Error " << GetLastError();

        throw ArduinoSerialException( error.str() );
    }

    PurgeComm( comm, PURGE_RXCLEAR | PURGE_TXCLEAR );
}

std::size_t ArduinoSerial::Read( char buffer[], const std::size_t size ) {
    DWORD numBytesRead = 0;
    BOOL success = ReadFile( comm, buffer, size, &numBytesRead, NULL );

    if ( success ) {
        return numBytesRead;
    }
    else {
        return 0;
    }
}

std::size_t ArduinoSerial::Write( char buffer[], const std::size_t size ) {
    DWORD numBytesWritten = 0;
    BOOL success = WriteFile( comm, buffer, size, &numBytesWritten, NULL );

    if ( success ) {
        return numBytesWritten;
    }
    else {
        return 0;
    }
}

ArduinoSerial::~ArduinoSerial() {
    CloseHandle( comm );
}

ArduinoSerialException::ArduinoSerialException( const std::string message )  :
    std::runtime_error( message ) {
}

Any help or advice will be really greatly appreciated.

I am presented with the following errors:

 error C2065: 'LcommPort' : undeclared identifier error C2228: left of '.c_str' must have class/struct/union 

This little piece of code

 TEXT( commPort.c_str())

becomes actually

 LcommPort.c_str()

That's why you get this compiler error.

You should notice that TEXT() is a preprocessor macro meant for character literals, to prefix them with L depending in which mode (Unicode/ASCII) your project is compiled. It doesn't work with any variables obviously.

Use either commPort.c_str() directly, or const std::wstring commPort .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM