简体   繁体   English

使用Visual C ++编程串口arduino

[英]Programming serial port arduino with Visual C++

I want to read analog sensor from arduino to my pc. 我想从arduino读取模拟传感器到我的电脑。

Arduino program are: 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);                     
}

and my visual C++ 和我的视觉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); }
}

and result of my program is not stable, I put 5V in input0, so it must be 1023: 并且我的程序结果不稳定,我在input0中输入了5V,因此必须为1023:

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

I try in my arduino with serial monitor the program is working. 我尝试使用串行监视器在arduino中运行程序。 so may be the problem is in the c++ program 所以可能是问题出在c ++程序中

any one have idea? 有人有主意吗?

I believe the problem is caused because your PC is looking for 4 chars and the Arduino is sending 3-6 chars per request. 我相信问题是由于您的PC正在寻找4个字符而Arduino正在按请求发送3-6个字符而引起的。

I would recommend you receive chars into your buffer until you receive the carriage return (\\r) sent by the Arduino. 我建议您将字符接收到缓冲区中,直到收到Arduino发送的回车符(\\ r)。 Then you can output the complete string. 然后,您可以输出完整的字符串。 You will need to handle the control characters. 您将需要处理控制字符。

Untested example: 未经测试的示例:

Replace 更换

oSerial.ReadData(buf0,4);

With

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM