简体   繁体   English

C ++设置串行com端口时出现问题

[英]C++ Problem on setting the serial com port

I having a problem on the setting the serial COM port on my C++ program. 我在C ++程序上设置串行COM端口时遇到问题。 There is my code in below. 下面是我的代码。

#include<iostream>
using namespace std;
#include<string>
#include<stdlib.h>
#include"SerialPort.h"

char output[MAX_DATA_LENGTH];
char incomingData[MAX_DATA_LENGTH];

char *port = "\\\\.\\COM7";

int main(){
SerialPort arduino(port);
if(arduino.isConnected()){
    cout<<"Connection made"<<endl<<endl;
}
else{
    cout<<"Error in port name"<<endl<<endl;
}
while(arduino.isConnected()){
    cout<<"Enter your command: "<<endl;
    string data;
    cin>>data;

    char *charArray = new char[data.size() + 1];
    copy(data.begin(), data.end(), charArray);
    charArray[data.size()] = '\n';

    arduino.writeSerialPort(charArray, MAX_DATA_LENGTH);
    arduino.readSerialPort(output, MAX_DATA_LENGTH);

    cout<<">> "<<output<<endl;

    delete [] charArray;
    }
return 0;
}

There are an error on "\\\\\\\\.\\\\COM7" "\\\\\\\\.\\\\COM7"上有错误

showing an error message a value of type "const char *" cannot be used to initialize an entity of type "char *" 显示错误消息a value of type "const char *" cannot be used to initialize an entity of type "char *"

When I change it to const char *port = "\\\\\\\\.\\\\COM7"; 当我将其更改为const char *port = "\\\\\\\\.\\\\COM7";

It showing error on SerialPort arduino(port); 它在SerialPort arduino(port);上显示错误SerialPort arduino(port);

Please help me. 请帮我。 Really need some help on this. 确实需要一些帮助。 Thank you. 谢谢。

In C++ literal strings are constant arrays of characters. 在C ++中,文字字符串是字符的常量数组。 Therefore you need const char* for pointers to them. 因此,您需要const char*来指向它们。

If you must pass a non-constant pointer to a function, use arrays : 如果必须将非常量指针传递给函数,请使用arrays

char port[] = "\\\\.\\COM7";

A possibly better solution would be to modify the SerialPort constructor to accept const char* as its argument. 可能更好的解决方案是修改SerialPort构造函数以接受const char*作为其参数。 Or even better to start using std::string for strings. 甚至更好地开始将std::string用于字符串。

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

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