繁体   English   中英

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

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

我在C ++程序上设置串行COM端口时遇到问题。 下面是我的代码。

#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;
}

"\\\\\\\\.\\\\COM7"上有错误

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

当我将其更改为const char *port = "\\\\\\\\.\\\\COM7";

它在SerialPort arduino(port);上显示错误SerialPort arduino(port);

请帮我。 确实需要一些帮助。 谢谢。

在C ++中,文字字符串是字符的常量数组。 因此,您需要const char*来指向它们。

如果必须将非常量指针传递给函数,请使用arrays

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

可能更好的解决方案是修改SerialPort构造函数以接受const char*作为其参数。 甚至更好地开始将std::string用于字符串。

暂无
暂无

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

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