c++ - 无法读取串行输入

标签 c++ serial-port arduino

我有一个 Arduino 通过 USB 连接到我的电脑。我尝试从中读取 COM 端口。

谁能看看这是否有什么明显的错误???

void main()
{   
    int exitStatus;
    unsigned int bytesToRead = 1;
    unsigned char *buffer = (unsigned char*) malloc(sizeof(unsigned char) + 1);
    Serial *connection = new Serial("COM3");

    if(connection->IsConnected()){
        exitStatus=connection->ReadData(buffer, bytesToRead);
        if( *buffer > 0)
            <statement I'm trying to hit>
    }

}    

现在它总是命中“我正在尝试命中的声明”,即使它不应该命中。调试它总是显示缓冲区的内容是很多垃圾。我知道来自串行输入的内容应该是正确的,因为从我在串行监视器中看到的内容来看,一切看起来都不错。

想法?

最佳答案

您没有评估 exitStatus 变量,这可能表明读取成功。

此外,如果您只想读取一个字节,则不需要 malloc 内存,只需将指针传递给本地 char 变量即可。

虽然我在这里,但 main 的类型是 int main()int main(int argc, char** argv)

int main()
{   
    int exitStatus;
    unsigned int bytesToRead = 1;
    unsigned char buffer;
    Serial *connection = new Serial("COM3");

    if(connection->IsConnected()){
        exitStatus=connection->ReadData(&buffer, 1);
        if((exitStatus == <Insert the value for a correct read status>) && (buffer != '0'))
            <statement I'm trying to hit>
    }
    return 0;
}

更新 将 != 0 检查更改为 != '0',因为我怀疑有一个 '0' 字符 (=0x30) 来自串行接口(interface)。

关于c++ - 无法读取串行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7777131/

相关文章:

windows - 如何使自定义 USB 设备在 Windows 中显示为 COM 端口?

arduino - 更改 LCD 引脚

c - Arduino 上的按位移位 unsigned long

c++ - 无参数构造函数

serial-port - 通过 AT 命令向 GSM 手机/调制解调器提交 "operator commands"(例如剩余的现金 SIM 卡积分)

c# - 如何从串口读取和写入

c++ - 返回值错误

c++ - 在 C++ 中使用 std::getline() 获取带空格的输入

c++ - 接受记录器的可变数量的参数

c++ - 使用 -1 将所有位设置为真是否安全?