问题
I'm facing a slight issue at the moment. I am currently doing some video (image) detection and tracking using Microsoft Visual Studio 2010 Professional and OpenCV, and the result (of the vision system) is to control additional hardware via the Arduino platform.
My code for the vision system works 100% and code on Arduino also works 100%, but I'm having an issue communicating via C / C++ from the PC to the Arduino board. (Can not use Visual Basic, etc.)
Specifications at the moment: Windows 7 platform, Visual Studio 2010, OpenCV 2.2.0, Arduino 0022, Arduino Mega board, 2 x USB to serial converters for simulations.
My code does not seem to even be functioning. I am, however, following the example below by #opc0de. But to illustrate my point the code below doesn't seem to work (never states COM open (yes, I change to the write ports)). (Connect two serial cables to each other plugged into two different COM ports hyperterminal, realterm, etc. work 100%. My code and the code below don't seem to work at all). (My code is +- 800 lines long and I don't feel like posting as the COMs section is very similar to below). I just want serial commynication to be working.
All I want from the COMs is the ability to send a text string, "x=### y=###" so even a simple piece of code will do (like below) (I want to read at a later stage, but I am not worried it at the moment)
Link to code: Stack Overflow - opc0de
#include <Windows.h>
#include <stdio.h>
#include <conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
char test[] = "Hello";
HANDLE hDevice = CreateFile(L"COM2",GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,0);
if (hDevice !=INVALID_HANDLE_VALUE)
{
printf("Port opened! \n");
DCB lpTest;
GetCommState(hDevice,&lpTest);
lpTest.BaudRate = CBR_9600;
lpTest.ByteSize = 8;
lpTest.Parity = NOPARITY;
lpTest.StopBits = ONESTOPBIT;
SetCommState(hDevice,&lpTest);
DWORD btsIO;
WriteFile(hDevice,test,strlen(test),&btsIO,NULL);
CloseHandle(hDevice);
}
_getch();
return 0;
}
回答1:
Check your code to make sure it works separately:
First, use a COM logger. The old and good Terminal from MS is the worst, but I cannot remember another one right now. See if your C++ code sends something there. If no, make it work :) If yes, debug commnication problems with an Arduino. Make a simple logger on Arduino to see what you receive on the other part and how you handle it.
来源:https://stackoverflow.com/questions/8181685/serial-communication-for-arduino-using-visual-studio-2010-and-c