gpt4 book ai didi

c++ - 写入串口时Qt崩溃

转载 作者:行者123 更新时间:2023-11-28 05:53:26 25 4
gpt4 key购买 nike

您好,我在 QT 中有一个程序,每当我写入串行端口时似乎都会崩溃。我正在使用 Mac OSx 15 英寸视网膜。相关代码如下:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
//set central widget for the Main Window
centralWidget = new QWidget(this);
this->setCentralWidget(centralWidget);

//creation and attribution of slider
slider = new QSlider();
slider->resize(255, 20);
slider->setOrientation(Qt::Horizontal);
slider->setRange(0, 255); //0-255 is range we can read

//layout with slider and lcd
main_layout = new QVBoxLayout();
main_layout->addWidget(slider);

//set layout to the widget inside MainWindow
centralWidget->setLayout(main_layout);

/*Connection Events*/
//connection between the slider event and the transmission function
QObject::connect(slider, SIGNAL(valueChanged(int)), this, SLOT(transmitCmd(int)));
}

void MainWindow::init_port()
{
port = new QSerialPort("COM3"); //create port

port->open(QIODevice::ReadWrite | QIODevice::Unbuffered); //open port
if(!port->isOpen())
{
QMessageBox::warning(this, "port error", "Can't open port!");
}

//set port properties
port->setBaudRate(QSerialPort::Baud9600); //9600 FOR ARDUINO
port->setFlowControl(QSerialPort::NoFlowControl);
port->setParity(QSerialPort::NoParity);
port->setDataBits(QSerialPort::Data8);
port->setStopBits(QSerialPort::OneStop);
}

void MainWindow::transmitCmd(int value)
{
//if value wasn't between 0-255, no transmission
if(value < 0 || value > 255)
return;
char *buffer = (char*) new int(value);

//send buffer to serial port
port->write(buffer);
}

它在 port->write(buffer) 行崩溃。我正在使用 QT 5.5 并使用 QTSerialPort。

最佳答案

尝试

port->write (buffer, sizeof (int));

您使用了 QIODevice::write(const char* data) 重载,它需要一个以 null 结尾的字符串(您的缓冲区不是)。所以很自然地,io 设备不知道什么时候停止...

无论如何,这应该可以解决您的崩溃问题。顺便说一句,同样可以说:

port->write (reinterpret_cast<const char*> (&value), sizeof (int))

但是,请注意上面的两个命令都会通过您的端口发送 4 个字节 (sizeof int) 的数据(按照您系统的字节顺序,可能是小端字节序)。也许(从函数开头的 0-255 检查判断),这实际上不是您想要的。如果您只想发送一个字节:

unsigned char valueCh = static_cast<unsigned char> (value);
port->write (reinterpret_cast<const char*> (&valueCh), 1)

附录:

如您所写,您只是忘记了初始化调用。好收获@perencia!但仍然值得理解为什么您的 transmitCmd() 确实有效——因为乍一看,它不应该。

我仍然坚持认为您使用了错误的 write() 调用——但事实上,它仍然有效。发生的事情是:

假设我们有 value == 17。然后,在小端架构上,您的缓冲区看起来像这样:

// "17" little-endian
11 00 00 00
^
|
buffer

并且您对 write(buffer) 的调用将看到您要发送的正确数据字节,后跟一个导致它停止的空字节。

关于c++ - 写入串口时Qt崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34708627/

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