简体   繁体   中英

Arduino and Visual C++ Serial Communication

So I found this tutorial for Arduino Visual Studio Communication: http://playground.arduino.cc/Interfacing/CPPWindows

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:

F:\Serial\Debug>Serial.exe
Communicating with COM7 enter data to be sent
1
2☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺
a
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺b☺☺☺☺☺☺
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺
☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺╠╠╠╠╠╠╠╠
^C
F:\Serial\Debug>

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.

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).

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