Visual Studio 2010 Arduino串口通信

时间:2012-11-25 01:52:57

标签: winapi visual-c++ opencv serial-port arduino

我在Visual Studio 2010中使用OpenCV来跟踪对象,我正在尝试向Arduino发送一个值以旋转连接到摄像机的伺服器。我正在使用Arduino Uno。我已完成跟踪对象的C++代码并确定相机需要旋转的方向,但我无法将此数据发送到Arduino。我目前正在尝试使用RS-232电缆。我使用Type-B USB线编程我的Arduino和RS-232尝试将数据从Visual Studio发送到Arduino。这是我的Visual Studio串行通信代码:

     int portspeed(int centerpix, int xmid)
{HANDLE hDevice = CreateFile(L"COM5",GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,0);
    DCB lpTest;
    GetCommState(hDevice,&lpTest);
    lpTest.BaudRate = CBR_9600;
    lpTest.ByteSize = 8;
    lpTest.Parity = NOPARITY;
    lpTest.StopBits = ONESTOPBIT;
    SetCommState(hDevice,&lpTest);
    DWORD btsIO;

    if (centerpix<xmid)
    {
        char test[] = "2";
        WriteFile(hDevice,test,strlen(test),&btsIO,NULL);
        cout << "Turn right " << test << endl;
    }
    else
    {
        char test[] = "3";
        WriteFile(hDevice,test,strlen(test),&btsIO,NULL);
        cout << "Turn left " << test << endl;
    }

    return 0;
}

在Arduino代码方面,我有这个,我用来尝试点亮两个不同的LED,看看程序是否能够正确地传达它需要旋转的方向:

int incomingByte = 0;   // For incoming serial data
void setup()
{
    Serial.begin(9600);     // Opens serial port, sets data rate to 9600 bit/s
}

void loop()
{
    // Send data only when you receive data:
    if (Serial.available() > 0)
    {
        incomingByte = Serial.read();
        if (incomingByte==50)   //if =2
            analogWrite(9,100);
        else
            analogWrite(9,0);
        if (incomingByte==51)   //if =3
            analogWrite(10,50);
        else analogWrite(10,0);
            delay(3000);
    }
    else
        analogWrite(9,255);
}

我的解释是我需要启动C ++程序(通过串行通信连续发送数据),然后将TX引脚从RS-232连接到Arduino上的RX引脚(数字0)。当我尝试将程序上传到Arduino时,我收到了错误,

  

avrdude:stk500_getsync():不同步:resp = 0x00

这只发生在我有一根导线进入RX引脚时,即使这根导线没有连接到任何东西。我相信这个错误的发生是因为RX正在寻找波特率为9600的输入,但是当C ++程序运行并以9600的速率发送数据时,它仍然会给我这个错误。

如何通过串行通信从Visual Studio项目中将实时图像处理的值发送到Arduino?

1 个答案:

答案 0 :(得分:0)

作为一个有Win32经验的人(更多的是.NET人),我认为你的问题可能在于写缓冲。

默认情况下,对文件或端口的写入缓冲在内存中。也许写入永远不会被发送到端口,因为您永远不会关闭文件句柄,也不会调用[FlushFileBuffers][3]

尝试在return 0;之前添加此内容:

//After a time, sensitive write
FlushFileBuffers(hDevice);

//or, more properly for the end of the program.
CloseHandle(hDevice);