user2881196 user2881196 - 10 months ago 132
C++ Question

Arduino and Visual C++ Serial Communication

So I found this tutorial for Arduino Visual Studio Communication:

After reading up on it I wrote a small program on the Arduino which reads a character's ASCII code and returns that incremented value. I already tested it with the serial monitor. However, when I wrote the program below I not only receive the answer, but I also receive "garbage" as well.

#include <iostream>
#include <string>
#include "Serial.h"

using namespace std;

int main(int argc, char* argv[])
Serial * Arduino = new Serial("COM8");
cout << "Communicating with COM7 enter data to be sent\n";
char data[256] = "";
int nchar = 256;
char incomingData[256] = "";
while (Arduino->IsConnected())
cin >> data;
Arduino->WriteData(data, nchar);
Arduino->ReadData(incomingData, nchar);
cout << incomingData << endl;
return 0;

The ouput looks as follows:

Communicating with COM7 enter data to be sent

Can anyone shed light into how I should go about changing this code so that I can send and recieve a specific number of characters or in this case one character. I have already tried changing nchar to 1 so that it would only send a single character; however, this causes the output to display out of sync. Any help is appreciated thanks.

Answer Source

First of all, you always send nchar bytes, no matter how much (or little) you read from the user. And also the data you read from the serial port, you don't terminate it like a string.

For the first it's simple, stop using an array for that, and use std::string (to avoid possible buffer overflows), and send size bytes.

Then when receiving, you need to find out how many bytes you received, and then terminate the array like a string (or use std::string there too, there's a constructor that lets you pass in a pointer and a size).