我需要通過USB在Microsoft Windows Visual C++ 2010和Arduino微控制器之間建立串行通信。運動跟蹤算法產生需要發送給Arduino的X和Y座標,Arduino依次控制兩個平移和傾斜舵機。Microsoft Visual C++ 2010和Arduino UNO之間的串行通信通過USB
我最後一年的機械工程專業學生,並有與Microsoft Visual影城和C++的經驗非常少,所以請多多包涵,並請原諒我,如果我的條件是不正確的......
我已經做了廣泛的研究在多個論壇上,但找不到針對我的問題的答案:
我在Visual Studio中創建普通/「空」項目時,遇到的所有解決方案都只支持通信。可以在這裏找到一個示例:Serial communication (for Arduino) using Visual Studio 2010 and C
當我在「Win32控制檯應用程序」項目中嘗試調試相同的代碼體(它在「空」項目中成功運行)時,出現以下錯誤:
錯誤C2065:LcommPort「:未聲明的標識符 錯誤C2228:左「.c_str」必須有類/結構/聯合
可惜我不能只是我的項目從一個‘Win32控制檯應用程序’的改變由於運動跟蹤算法需要使用控制檯應用程序類型的項目,所以正常的「空」項目。
我正在使用的代碼的主體如下所示(這是一個簡化的測試源文件,用於確認MS Visual和Arduino之間是否建立了通信,其中LED的開啓和關閉頻率通過改變串行連接):
#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;
}
相應的源代碼是錯誤的家中的代碼line9發現:
#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) {
}
任何幫助或建議,將大大得到真正的重視。
這是唯一的錯誤?你在哪裏包含'string'? – deviantfan
您的問題標題在所要求的實際問題上非常誤導。請提供一個[MCVE](http://stackoverflow.com/help/mcve)來改善您的問題,而不是發佈如此多的無關代碼。 –