[英]Qt crashing when writing to serial port
嗨,我有一个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)
重载,该重载期望以空值结尾的字符串(缓冲区不是)。 因此,自然而然,io设备不知道何时停止...
无论如何,这应该可以解决您的崩溃问题。 顺便说一句,同样有可能只说:
port->write (reinterpret_cast<const char*> (&value), sizeof (int))
但是,请注意,以上两个命令都会在您的端口上发送4个字节(sizeof int)的数据(按照系统的字节顺序,可能是little-endian)。 也许(从函数开始时的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)
的调用将看到您要发送的正确数据字节,然后是一个nul字节,这将使其停止。
您没有在调用init_port
。 至少在您提交的代码中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.