c++ - 用Visual C++编程串口arduino

标签 c++ serial-port arduino

我想从 arduino 读取模拟传感器到我的电脑。

Arduino 程序有:

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600); 
}

void loop() {
char request[1];
if(Serial.available()){
request[0]=Serial.read();
Serial.print(analogRead(atoi(request)));
Serial.print("\n\r");
};
delay(2);                     
}

和我的Visual C++

#include <windows.h>
#include "stdafx.h"
#include "SerialClass.h"

char buffer[20];
char buf0[200];

int _tmain(int argc, _TCHAR* argv[])
{
   Serial oSerial("COM6:");

while(1){
sprintf_s(buffer,"0");    
    oSerial.WriteData(buffer,1); 
Sleep(1000);
oSerial.ReadData(buf0,4);
printf("Sensor 0: %s \n",buf0);
Sleep(1000); }
}

而且我的程序结果不稳定,我在 input0 上加了 5V,所以它必须是 1023:

sensor 0 :
sensor 0 : 10230
sensor 0:
100
sensor 0: 23
0
sensor 0: 10230

我在我的 arduino 中尝试使用串行监视器程序运行。所以可能是 C++ 程序中的问题

有人知道吗?

最佳答案

我认为问题是因为您的 PC 正在寻找 4 个字符而 Arduino 每次请求发送 3-6 个字符。

我建议您在接收到 Arduino 发送的回车符 (\r) 之前将字符接收到缓冲区中。然后就可以输出完整的字符串了。您将需要处理控制字符。

未经测试的例子:

替换

oSerial.ReadData(buf0,4);

int x=0;
int char_rev;

while(buf0[x]!='\r') {

    char_rev = oSerial.ReadData(buf0[x],1);
    if (char_rev==1) {
        x++;
    }
}
buf0[x]=0;

关于c++ - 用Visual C++编程串口arduino,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063588/

相关文章:

c++ - 对象的析构函数导致崩溃

c++ - 漫反射 Material 奇怪的光线追踪行为

c++ - 计算正弦信号的频率,c++

Arduino返回的PHP串口数据

c++ - 如何将 ‘std::chrono::duration<int, std::ratio<2629746l, 1l>>’类型转换为 ‘int’类型?

python - 在 Python 上运行后台循环

c - 在 Windows 内核中打开、读取和写入串行端口

python - 从电脑读取wav文件到arduino mega

c - Arduino (C) - "expected primary-expression before ' )'

linux - 如何在树莓派 3B+ 上选择一个特定的 USB 端口来使用 arduino-mk 对两个 arduino 板进行编程?