gpt4 book ai didi

关于设置串口 com 端口的 C++ 问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:39:28 26 4
gpt4 key购买 nike

我在 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" 有错误

显示错误消息“const char *”类型的值不能用于初始化“char *”类型的实体

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

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

请帮帮我。真的需要一些帮助。谢谢。

最佳答案

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

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

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

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

关于关于设置串口 com 端口的 C++ 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54455554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com