简体   繁体   中英

Programming serial port arduino with Visual C++

I want to read analog sensor from arduino to my pc.

Arduino program are:

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++

#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:

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. so may be the problem is in the c++ program

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.

I would recommend you receive chars into your buffer until you receive the carriage return (\\r) sent by the Arduino. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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