C# 如何使用串行端口将信息从kinect发送到arduino?

C# 如何使用串行端口将信息从kinect发送到arduino?,c#,serialization,arduino,kinect,kinect-sdk,C#,Serialization,Arduino,Kinect,Kinect Sdk,我已经摆弄了Kinect SDK和arduino,并且我在网络上寻找了一种将信息从Kinect传递到arduino的方法。我只是想传递一些非常简单的信息(例如,如果kinect识别出手势,arduino就会这样做),我发现有人在谈论使用串行端口来实现这一点。我看了文档和人们的代码,但我对C#非常陌生,不太了解串行端口是如何工作的。我有适用于Windows v1的Kinect,正在尝试将信息传递给botboarduino。如果有人能解释如何设置串行端口,将不胜感激 另外,我一直在为Kinect在V

我已经摆弄了Kinect SDK和arduino,并且我在网络上寻找了一种将信息从Kinect传递到arduino的方法。我只是想传递一些非常简单的信息(例如,如果kinect识别出手势,arduino就会这样做),我发现有人在谈论使用串行端口来实现这一点。我看了文档和人们的代码,但我对C#非常陌生,不太了解串行端口是如何工作的。我有适用于Windows v1的Kinect,正在尝试将信息传递给botboarduino。如果有人能解释如何设置串行端口,将不胜感激


另外,我一直在为Kinect在Visual Studio 2015社区工作,为Arduino在Arduino IDE中工作。

我知道,有点明显,但是首先使用
System.IO.Ports
命名空间中的
SerialPort
组件。

本节的示例部分:
https://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110)。aspx
MSDN页面提供了启动串行端口和解析数据所需的所有功能。当然,您需要打开串行端口,在Arduino端将其设置为正确的奇偶校验,以接收您想要发送和处理的所需数据,但这方面的示例已经足够多了。

Mike提供的示例应给出总体布局,但是,对于在程序中设置串行端口,您最有可能遵守

这是一个9600串口的初始串口设置示例(这些是C++使用Boost库的,但是它应该清楚地说明你需要设置什么):


当我在过去设置时,我唯一需要确保的是Arduino上的波特率与上述设置相匹配,否则其余的似乎是默认设置。不过,我不能保证在您的情况下做到这一点。

您需要写入Arduino所连接的串行端口。Windows将序列视为文件,因此要写入序列,请使用此类(我使用VS2013,但它也适用于VS2015):

标题(命名为SerialClass.h):

\ifndef SERIALCLASS\u包括在内
#定义包含的串行类
#定义ARDUINO_等待时间2000
#包括
#包括
#包括
类序列号
{
私人:
//串行通信处理程序
处理串行;
//连接状态
布尔连接;
//获取有关连接的各种信息
COMSTAT状态;
//跟踪最后一个错误
德沃德误差;
公众:
//初始化与给定COM端口的串行通信
串行(字符*端口名);
//关闭连接
~Serial();
//如果nbChar大于
//最大可用字节数,它将仅返回
//字节可用。当无法执行任何操作时,函数返回-1
//要读取,实际读取的字节数。
int ReadData(字符*缓冲区,无符号int-nbChar);
//通过串行连接从缓冲区写入数据
//成功后返回真实。
bool WriteData(字符*缓冲区,无符号整数nbChar);
//检查我们是否真的有联系
布尔断开连接();
};
#endif//SERIALCLASS\u包括在内
CPP文件(名为SerialClass.CPP):

#包括“SerialClass.h”
#包括
串行::串行(字符*端口名)
{
//我们还没联系上
此->已连接=错误;
//尝试通过CreateFile连接到给定端口
此->hSerial=CreateFile(端口名,
一般的读,一般的写,
0,
无效的
开放式,
文件\u属性\u正常,
无效);
//检查连接是否成功
if(this->hSerial==无效的\u句柄\u值)
{
//如果未成功,则完全显示错误
如果(GetLastError()==找不到错误文件){
//必要时打印错误
printf(“错误:未附加句柄。原因:%s不可用。\n”,端口名);
}
else if(GetLastError()==错误\u访问被拒绝)
{
printf(“就是这个!!!!”);
}
其他的
{
printf(“错误!!!”);
DWORD error=GetLastError();
std::cout hSerial和DCB SerialParams)
{
//如果不可能,则显示错误
printf(“获取当前串行参数失败!”);
}
其他的
{
//定义arduino板的串行连接参数
dcbSerialParams.BaudRate=CBR_9600;
dcbSerialParams.ByteSize=8;
dcbSerialParams.StopBits=一个停止位;
dcbSerialParams.奇偶性=无奇偶性;
//将DTR设置为Control_Enable可确保Arduino正常运行
//建立连接后重置
dcbSerialParams.fDtrControl=DTR\u CONTROL\u ENABLE;
//设置参数并检查其是否正确应用
if(!SetCommState(hSerial和dcbSerialParams))
{
printf(“警报:无法设置串行端口参数”);
}
其他的
{
//如果一切顺利,我们就接通了
此->已连接=真;
//刷新缓冲区中的所有剩余字符
PurgeComm(此->串行、清除|清除|清除);
//我们等待2秒,因为arduino板将重置
睡眠(等待时间);
}
}
}
}
序列号::~Serial()
{
//在尝试断开连接之前,请检查我们是否已连接
如果(此->已连接)
{
//我们不再有联系了
此->已连接=错误;
//关闭串行处理程序
关闭手柄(此->hs串行);
}
}
int-Serial::ReadData(字符*缓冲区,无符号int-nbChar)
{
//我们将读取的字节数
德沃德·拜特斯雷德;
//我们真正需要读取的字节数
无符号整数搜索;
//使用ClearCommError函数获取sta
port.set_option(asio::serial_port_base::baud_rate(9600));
port.set_option(asio::serial_port_base::character_size(8));
port.set_option(asio::serial_port_base::flow_control(asio::serial_port_base::flow_control::none));
port.set_option(asio::serial_port_base::parity(asio::serial_port_base::parity::none));
port.set_option(asio::serial_port_base::stop_bits(asio::serial_port_base::stop_bits::one));
#ifndef SERIALCLASS_H_INCLUDED
#define SERIALCLASS_H_INCLUDED

#define ARDUINO_WAIT_TIME 2000

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

class Serial
{
private:
    //Serial comm handler
    HANDLE hSerial;
    //Connection status
    bool connected;
    //Get various information about the connection
    COMSTAT status;
    //Keep track of last error
    DWORD errors;

public:
    //Initialize Serial communication with the given COM port
    Serial(char *portName);
    //Close the connection
    ~Serial();
    //Read data in a buffer, if nbChar is greater than the
    //maximum number of bytes available, it will return only the
    //bytes available. The function return -1 when nothing could
    //be read, the number of bytes actually read.
    int ReadData(char *buffer, unsigned int nbChar);
    //Writes data from a buffer through the Serial connection
    //return true on success.
    bool WriteData(char *buffer, unsigned int nbChar);
    //Check if we are actually connected
    bool IsConnected();


};

#endif // SERIALCLASS_H_INCLUDED
#include "SerialClass.h"
#include<iostream>
Serial::Serial(char *portName)
{
    //We're not yet connected
    this->connected = false;

    //Try to connect to the given port throuh CreateFile
    this->hSerial = CreateFile(portName,
        GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    //Check if the connection was successfull
    if (this->hSerial == INVALID_HANDLE_VALUE)
    {
        //If not success full display an Error
        if (GetLastError() == ERROR_FILE_NOT_FOUND){

            //Print Error if neccessary
            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);

        }
        else if (GetLastError() == ERROR_ACCESS_DENIED)
        {
            printf("It is this!!!!");

        }
        else
        {
            printf("ERROR!!!");
            DWORD error = GetLastError();
            std::cout << error;
        }
    }
    else
    {
        //If connected we try to set the comm parameters
        DCB dcbSerialParams = { 0 };

        //Try to get the current
        if (!GetCommState(this->hSerial, &dcbSerialParams))
        {
            //If impossible, show an error
            printf("failed to get current serial parameters!");
        }
        else
        {
            //Define serial connection parameters for the arduino board
            dcbSerialParams.BaudRate = CBR_9600;
            dcbSerialParams.ByteSize = 8;
            dcbSerialParams.StopBits = ONESTOPBIT;
            dcbSerialParams.Parity = NOPARITY;
            //Setting the DTR to Control_Enable ensures that the Arduino is properly
            //reset upon establishing a connection
            dcbSerialParams.fDtrControl = DTR_CONTROL_ENABLE;

            //Set the parameters and check for their proper application
            if (!SetCommState(hSerial, &dcbSerialParams))
            {
                printf("ALERT: Could not set Serial Port parameters");
            }
            else
            {
                //If everything went fine we're connected
                this->connected = true;
                //Flush any remaining characters in the buffers 
                PurgeComm(this->hSerial, PURGE_RXCLEAR | PURGE_TXCLEAR);
                //We wait 2s as the arduino board will be reseting
                Sleep(ARDUINO_WAIT_TIME);
            }
        }
    }

}

Serial::~Serial()
{
    //Check if we are connected before trying to disconnect
    if (this->connected)
    {
        //We're no longer connected
        this->connected = false;
        //Close the serial handler
        CloseHandle(this->hSerial);
    }
}

int Serial::ReadData(char *buffer, unsigned int nbChar)
{
    //Number of bytes we'll have read
    DWORD bytesRead;
    //Number of bytes we'll really ask to read
    unsigned int toRead;

    //Use the ClearCommError function to get status info on the Serial port
    ClearCommError(this->hSerial, &this->errors, &this->status);

    //Check if there is something to read
    if (this->status.cbInQue>0)
    {
        //If there is we check if there is enough data to read the required number
        //of characters, if not we'll read only the available characters to prevent
        //locking of the application.
        if (this->status.cbInQue>nbChar)
        {
            toRead = nbChar;
        }
        else
        {
            toRead = this->status.cbInQue;
        }

        //Try to read the require number of chars, and return the number of read bytes on success
        if (ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
        {
            return bytesRead;
        }

    }

    //If nothing has been read, or that an error was detected return -1
    return -1;

}


bool Serial::WriteData(char *buffer, unsigned int nbChar)
{
    DWORD bytesSend;

    //Try to write the buffer on the Serial port
    if (!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
    {
        //In case it don't work get comm error and return false
        ClearCommError(this->hSerial, &this->errors, &this->status);

        return false;
    }
    else
        return true;
}

bool Serial::IsConnected()
{
    //Simply return the connection status
    return this->connected;
}
Serial Arduino = Serial("COM3"); //My Arduino is at COM3 - change it for yours!
if (Arduino.IsConnected() == false)  //Checks if it connected
{
    std::cout << "Your Arduino isn't connected!" << std::endl;
    std::cin.ignore();
    return 1;
}
Arduino.WriteData("This is sent data"); //Sends "This is sent data" to the Serial which Arduino is connected to!