c++ - 从 arduino 读取到 c++ 程序时保持接收 NULL

标签 c++ winapi arduino

我在我的 C++ 程序中使用 Windows API 通过串口连接 arduino。

arduino 每秒发送一个字节,c++ 程序应读取该字节并在屏幕上打印。

这是我的 arduino 代码。

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.write('a');
  delay(1000);  
}

Serial类中有成员

    //Serial comm handler
    HANDLE hSerial;
    //Connection status
    bool connected;
    //Get various information about the connection
    COMSTAT status;
    //Keep track of last error
    DWORD errors;
    //transform error message to be stored in a string variable

这是我的 C++ 程序中的读取函数

int Serial::ReadData(char buffer)
{
    //Number of bytes we'll have read
    DWORD bytesRead = 0;

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

    cout << this->status.cbInQue << " Bytes in the queue have not been read" << endl;
    //Check if there is something to read
    if(this->status.cbInQue>0)
    {
        //Try to read the require number of chars, and return the number of read bytes on success
        if(ReadFile(this->hSerial, (void *)&buffer, 1, &bytesRead, NULL) )
        {
            return bytesRead;
        }

    }
    //If nothing has been read, or that an error was detected return 0
    return 0;
}

如果需要,这是我的 Serial 构造函数

Serial::Serial(string portName, char use)
{
    //We're not yet connected
    this->connected = false;

    DWORD authority;
    if (use == 'w'){
        authority = GENERIC_WRITE;
    }
    else if (use == 'r'){
        cout << "read" << endl;
        authority = GENERIC_READ;
    }
    else if (use == 'b'){
        authority = GENERIC_READ | GENERIC_WRITE; 
    }
    else{
        cout << "the second parameter of the initialization of the Serial object is wrong" << endl;
        cout << "It can only be w or r" << endl;
    }

    //Try to connect to the given port through CreateFile
    this->hSerial = CreateFile(portName.c_str(),
            authority,
            0,
            NULL,
            OPEN_EXISTING,
            0,
            NULL);

    //Check if the connection was successful
    if(this->hSerial==INVALID_HANDLE_VALUE)
    {
        cout << GetLastErrorAsString() << endl;
    }
    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);
             }
        }
    }
}

这是我的主程序

int main(int argc, _TCHAR* argv[])
{     
    char use = 'r'; //r for read, w for write, b for both
    Serial* SP = new Serial("COM4", use);    // adjust as needed

    char input;
    int num_bytes_read;
    while(SP->IsConnected())
    {
        cout << "connect successes!" << endl;
        num_bytes_read = SP->ReadData(input);
        cout << num_bytes_read << " " << (int) input << endl;
        Sleep(1000);
    }
    return 0;
}

打印到屏幕时,我将 char 变量“input”转换为 int 以检查存储在 char 变量中的值的 ascii 代码。

最后就是我的c++程序的输出

connect successes!
1 Bytes in the queue have not been read
1 0

看起来确实收到了数据,但为什么打印的不是'a'而是NULL?

我使用 Arduino/Genuino Uno(这是我在 Arduino IDE 中选中“工具”按钮时看到的)和 Windows 10

感谢您考虑我的请求!

最佳答案

在 C++ 中,参数通过 vaule 传递...除非它们通过引用传递。所以改变这一行:

int Serial::ReadData(char buffer)

到:

int Serial::ReadData(char &buffer)

否则,当您读入 buffer 时您实际上正在读入 ReadData 的局部变量并且不要修改 input来自 main .

可以说,如果你把它改成这样会更好:

int Serial::ReadData(char *buffer, int len)

然后,在 main你称之为写作:

num_bytes_read = SP->ReadData(&input, 1);

这样以后,当你想读取更多的数据时,只需调用一次即可。

关于c++ - 从 arduino 读取到 c++ 程序时保持接收 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38263790/

相关文章:

c++ - 如何使用具有多态性的插入运算符

c++ - 如何用c++建立一个简单的ssh连接

c++ - WinSNMP 设置源/管理器端口

java - 三维数组以错误的顺序到达串行端口

c++ - 在 C++ 中使用指针时,对象属性未按预期更改

c++是否有STL算法来检查范围是否严格排序?

c++ - 转发引用错误时终端进程终止

c++ - 为什么 WriteFile 不会运行多次?

c++ - 尝试使用带有 C++ 的 MoveFile 移动文件时出现 ERROR_INVALID_NAME

c - 转换为C代码时如何导入.h文件?