Перейти к содержимому

Как читать serial port qt

  • автор:

Qt Serial Port

Qt Serial Port provides basic functionality for configuration, I/O operations, and getting and setting the control signals of the RS-232 pinouts.

The following items are not supported by this module:

  • Terminal features, such as echo, control CR/LF, and so on.
  • Text mode.
  • Configuring timeouts and delays while reading or writing.
  • Pinout signal change notification.

Using the Module

Using a Qt module’s C++ API requires linking against the module library, either directly or through other dependencies. Several build tools have dedicated support for this, including CMake and qmake.

Building with CMake

Use the find_package() command to locate the needed module component in the Qt6 package:

find_package(Qt6 REQUIRED COMPONENTS SerialPort) target_link_libraries(mytarget PRIVATE Qt6::SerialPort)

For more details, see the Build with CMake overview.

Building with qmake

To configure the module for building with qmake, add the module as a value of the QT variable in the project’s .pro file:

QT += serialport

Module Evolution

Changes to Qt SerialPort lists important changes in the module API and functionality that were done for the Qt 6 series of Qt.

Related Information

© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Как читать serial port qt

Просмотр профиля

20.11.2015, 16:04

Группа: Участник
Сообщений: 152
Регистрация: 1.1.2011
Пользователь №: 2314

Репутация: 0

День добрый, господа.

Вопрос такой. Есть порт с перемычкой между TxD и RxD. Пишу в порт данные и читаю их же. Использую QtSerialPort в полной аналогии с примером (terminal example). Проблема заключается в чтении данных. Есть слот, приконнекченный к сигналу readyRead() объекта. Когда в порте появляются данные, этот слот вызывается всякий раз, когда размер этих данных равен 8 Байтам. Например, если размер считываемых данных составляет 14 Байт, слот вызывается 2 раза, если 27 Байт — 4 раза, 248 Байт — 31 раз. Т.е. порт ведет себя так, как будто бы размер буфера равен 8. Суть проблемы в том, что из-за вышеперечисленного невозможно отследить момент, когда все доступные данные считаны из порта:

Раскрывающийся текст

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
.
serial = new QSerialPort(this);
serial->setReadBufferSize(0);
connect(serial, SIGNAL(readyRead()), SLOT(readData()));
.
>
void MainWindow::readData()
<
port_data.append(serial->readAll());
if(serial->bytesAvailable()==0) // здесь должна быть обработка всех полученных данных
>
>

При каждом вызове слота readData() условие if(serial->bytesAvailable()==0) по непонятной для меня причине оказывается верно. Так же, как и верно условие if(serial->atEnd()). Как победить это? В идеале хотелось бы, чтоб все данные считывались сразу, за один заход в слот readData(). Ну, на крайний случай, пускай заходит в него сколько угодно раз, но чтоб можно было б как-то отследить момент, когда все данные считаны.

UPD
Если добавить небольшой лок перед чтением, т.е.

Раскрывающийся текст

void MainWindow::readData()
<
QThread::msleep(400);
port_data.append(serial->readAll());
.
>

то чтение происходит за 2 захода в метод readData() — в первый раз считывается 8 Байт, затем все остальное.

Я ничего не понимаю.

Сообщение отредактировал borune — 20.11.2015, 16:42

опции профиля:

Qt C++ Serial Port в примерах, как переделать его для чтения данных Arduino?

К Arduino подключен считыватель карточек, в Arduino залит скетч, который позволяет узнать номер карты, как теперь с помощью C++ показать этот номер в отдельном окне?

  • Вопрос задан более трёх лет назад
  • 13270 просмотров

Комментировать
Решения вопроса 1

a_volkov1987

Александр Волков @a_volkov1987
Инженер-схемотехник

doc.qt.io/qt-5/qtserialport-terminal-example.html — подробно описано, как создать порт для асинхронного приема данных.
Согласуйте настройки порта на ПК с настройками UART в скетче на ардуино (скорость, количество стоповых бит и контроль четности).
На ардуино сформируйте посылку из номера карты. Номер передавайте как строку, после номера передавайте символ перевода каретки.
В QT по приходу байта записывайте его в буфер, пока принятый байт не будет равен символу перевода каретки. Как только найдёте такой символ — данные из буфера передавайте в новое окно и очищайте буфер.

Ответ написан более трёх лет назад
Нравится 3 1 комментарий
Bugmen @Bugmen Автор вопроса

Пробовал создавать другие примеры не связанные с терминалом, но почему-то при загрузке скетча программа на QT выдает ошибку, а если первой запустить программу QT, а потом попытаться загрузить скетч, ардуино выдает ошибку

Ответы на вопрос 0
Ваш ответ на вопрос

Войдите, чтобы написать ответ

электроника

  • Электроника
  • +2 ещё

Как построить ВАХ светодиода на arduino?

  • 1 подписчик
  • 4 часа назад
  • 34 просмотра

QSerialPort Class

Note: All functions in this class are reentrant.

Public Types

enum BaudRate
enum DataBits
enum Direction
flags Directions
enum FlowControl
enum Parity
enum PinoutSignal
flags PinoutSignals
enum SerialPortError
enum StopBits

Properties

Public Functions

QSerialPort(QObject *parent = nullptr)
QSerialPort(const QString &name, QObject *parent = nullptr)
QSerialPort(const QSerialPortInfo &serialPortInfo, QObject *parent = nullptr)
virtual ~QSerialPort()
qint32 baudRate(QSerialPort::Directions directions = AllDirections) const
QBindable

bindableDataBits()
QBindable

bindableError() const
QBindable

bindableFlowControl()
QBindable

bindableIsBreakEnabled()
QBindable

bindableParity()
QBindable

bindableStopBits()
bool clear(QSerialPort::Directions directions = AllDirections)
void clearError()
QSerialPort::DataBits dataBits() const
QSerialPort::SerialPortError error() const
QSerialPort::FlowControl flowControl() const
bool flush()
QSerialPort::Handle handle() const
bool isBreakEnabled() const
bool isDataTerminalReady()
bool isRequestToSend()
QSerialPort::Parity parity() const
QSerialPort::PinoutSignals pinoutSignals()
QString portName() const
qint64 readBufferSize() const
bool setBaudRate(qint32 baudRate, QSerialPort::Directions directions = AllDirections)
bool setBreakEnabled(bool set = true)
bool setDataBits(QSerialPort::DataBits dataBits)
bool setDataTerminalReady(bool set)
bool setFlowControl(QSerialPort::FlowControl flowControl)
bool setParity(QSerialPort::Parity parity)
void setPort(const QSerialPortInfo &serialPortInfo)
void setPortName(const QString &name)
void setReadBufferSize(qint64 size)
bool setRequestToSend(bool set)
bool setStopBits(QSerialPort::StopBits stopBits)
QSerialPort::StopBits stopBits() const

Reimplemented Public Functions

virtual qint64 bytesAvailable() const override
virtual qint64 bytesToWrite() const override
virtual bool canReadLine() const override
virtual void close() override
virtual bool isSequential() const override
virtual bool open(QIODeviceBase::OpenMode mode) override
virtual bool waitForBytesWritten(int msecs = 30000) override
virtual bool waitForReadyRead(int msecs = 30000) override

Signals

void baudRateChanged(qint32 baudRate, QSerialPort::Directions directions)
void breakEnabledChanged(bool set)
void dataBitsChanged(QSerialPort::DataBits dataBits)
void dataTerminalReadyChanged(bool set)
void errorOccurred(QSerialPort::SerialPortError error)
void flowControlChanged(QSerialPort::FlowControl flow)
void parityChanged(QSerialPort::Parity parity)
void requestToSendChanged(bool set)
void stopBitsChanged(QSerialPort::StopBits stopBits)

Reimplemented Protected Functions

virtual qint64 readData(char *data, qint64 maxSize) override
virtual qint64 readLineData(char *data, qint64 maxSize) override
virtual qint64 writeData(const char *data, qint64 maxSize) override

Detailed Description

You can get information about the available serial ports using the QSerialPortInfo helper class, which allows an enumeration of all the serial ports in the system. This is useful to obtain the correct name of the serial port you want to use. You can pass an object of the helper class as an argument to the setPort() or setPortName() methods to assign the desired serial device.

After setting the port, you can open it in read-only (r/o), write-only (w/o), or read-write (r/w) mode using the open() method.

Note: The serial port is always opened with exclusive access (that is, no other process or thread can access an already opened serial port).

Use the close() method to close the port and cancel the I/O operations.

Having successfully opened, QSerialPort tries to determine the current configuration of the port and initializes itself. You can reconfigure the port to the desired setting using the setBaudRate(), setDataBits(), setParity(), setStopBits(), and setFlowControl() methods.

There are a couple of properties to work with the pinout signals namely: QSerialPort::dataTerminalReady, QSerialPort::requestToSend. It is also possible to use the pinoutSignals() method to query the current pinout signals set.

Once you know that the ports are ready to read or write, you can use the read() or write() methods. Alternatively the readLine() and readAll() convenience methods can also be invoked. If not all the data is read at once, the remaining data will be available for later as new incoming data is appended to the QSerialPort’s internal read buffer. You can limit the size of the read buffer using setReadBufferSize().

QSerialPort provides a set of functions that suspend the calling thread until certain signals are emitted. These functions can be used to implement blocking serial ports:

  • waitForReadyRead() blocks calls until new data is available for reading.
  • waitForBytesWritten() blocks calls until one payload of data has been written to the serial port.

See the following example:

int numRead = 0, numReadTotal = 0; char buffer[50]; for (;;) < numRead = serial.read(buffer, 50); // Do whatever with the array numReadTotal += numRead; if (numRead == 0 && !serial.waitForReadyRead()) break; >

If waitForReadyRead() returns false , the connection has been closed or an error has occurred.

If an error occurs at any point in time, QSerialPort will emit the errorOccurred() signal. You can also call error() to find the type of error that occurred last.

Programming with a blocking serial port is radically different from programming with a non-blocking serial port. A blocking serial port does not require an event loop and typically leads to simpler code. However, in a GUI application, blocking serial port should only be used in non-GUI threads, to avoid freezing the user interface.

For more details about these approaches, refer to the example applications.

The QSerialPort class can also be used with QTextStream and QDataStream’s stream operators (operator>()). There is one issue to be aware of, though: make sure that enough data is available before attempting to read by using the operator>>() overloaded operator.

Member Type Documentation

enum QSerialPort:: BaudRate

This enum describes the baud rate which the communication device operates with.

Note: Only the most common standard baud rates are listed in this enum.

Constant Value Description
QSerialPort::Baud1200 1200 1200 baud.
QSerialPort::Baud2400 2400 2400 baud.
QSerialPort::Baud4800 4800 4800 baud.
QSerialPort::Baud9600 9600 9600 baud.
QSerialPort::Baud19200 19200 19200 baud.
QSerialPort::Baud38400 38400 38400 baud.
QSerialPort::Baud57600 57600 57600 baud.
QSerialPort::Baud115200 115200 115200 baud.

enum QSerialPort:: DataBits

This enum describes the number of data bits used.

Constant Value Description
QSerialPort::Data5 5 The number of data bits in each character is 5. It is used for Baudot code. It generally only makes sense with older equipment such as teleprinters.
QSerialPort::Data6 6 The number of data bits in each character is 6. It is rarely used.
QSerialPort::Data7 7 The number of data bits in each character is 7. It is used for true ASCII. It generally only makes sense with older equipment such as teleprinters.
QSerialPort::Data8 8 The number of data bits in each character is 8. It is used for most kinds of data, as this size matches the size of a byte. It is almost universally used in newer applications.

enum QSerialPort:: Direction
flags QSerialPort:: Directions

This enum describes the possible directions of the data transmission.

Note: This enumeration is used for setting the baud rate of the device separately for each direction on some operating systems (for example, POSIX-like).

Constant Value Description
QSerialPort::Input 1 Input direction.
QSerialPort::Output 2 Output direction.
QSerialPort::AllDirections Input | Output Simultaneously in two directions.

The Directions type is a typedef for QFlags. It stores an OR combination of Direction values.

enum QSerialPort:: FlowControl

This enum describes the flow control used.

Constant Value Description
QSerialPort::NoFlowControl 0 No flow control.
QSerialPort::HardwareControl 1 Hardware flow control (RTS/CTS).
QSerialPort::SoftwareControl 2 Software flow control (XON/XOFF).

enum QSerialPort:: Parity

This enum describes the parity scheme used.

Constant Value Description
QSerialPort::NoParity 0 No parity bit it sent. This is the most common parity setting. Error detection is handled by the communication protocol.
QSerialPort::EvenParity 2 The number of 1 bits in each character, including the parity bit, is always even.
QSerialPort::OddParity 3 The number of 1 bits in each character, including the parity bit, is always odd. It ensures that at least one state transition occurs in each character.
QSerialPort::SpaceParity 4 Space parity. The parity bit is sent in the space signal condition. It does not provide error detection information.
QSerialPort::MarkParity 5 Mark parity. The parity bit is always set to the mark signal condition (logical 1). It does not provide error detection information.

enum QSerialPort:: PinoutSignal
flags QSerialPort:: PinoutSignals

This enum describes the possible RS-232 pinout signals.

Constant Value Description
QSerialPort::NoSignal 0x00 No line active
QSerialPort::DataTerminalReadySignal 0x04 DTR (Data Terminal Ready).
QSerialPort::DataCarrierDetectSignal 0x08 DCD (Data Carrier Detect).
QSerialPort::DataSetReadySignal 0x10 DSR (Data Set Ready).
QSerialPort::RingIndicatorSignal 0x20 RNG (Ring Indicator).
QSerialPort::RequestToSendSignal 0x40 RTS (Request To Send).
QSerialPort::ClearToSendSignal 0x80 CTS (Clear To Send).
QSerialPort::SecondaryTransmittedDataSignal 0x100 STD (Secondary Transmitted Data).
QSerialPort::SecondaryReceivedDataSignal 0x200 SRD (Secondary Received Data).

The PinoutSignals type is a typedef for QFlags. It stores an OR combination of PinoutSignal values.

enum QSerialPort:: SerialPortError

This enum describes the errors that may be contained by the QSerialPort::error property.

Constant Value Description
QSerialPort::NoError 0 No error occurred.
QSerialPort::DeviceNotFoundError 1 An error occurred while attempting to open an non-existing device.
QSerialPort::PermissionError 2 An error occurred while attempting to open an already opened device by another process or a user not having enough permission and credentials to open.
QSerialPort::OpenError 3 An error occurred while attempting to open an already opened device in this object.
QSerialPort::NotOpenError 10 This error occurs when an operation is executed that can only be successfully performed if the device is open. This value was introduced in QtSerialPort 5.2.
QSerialPort::WriteError 4 An I/O error occurred while writing the data.
QSerialPort::ReadError 5 An I/O error occurred while reading the data.
QSerialPort::ResourceError 6 An I/O error occurred when a resource becomes unavailable, e.g. when the device is unexpectedly removed from the system.
QSerialPort::UnsupportedOperationError 7 The requested device operation is not supported or prohibited by the running operating system.
QSerialPort::TimeoutError 9 A timeout error occurred. This value was introduced in QtSerialPort 5.2.
QSerialPort::UnknownError 8 An unidentified error occurred.

enum QSerialPort:: StopBits

This enum describes the number of stop bits used.

Constant Value Description
QSerialPort::OneStop 1 1 stop bit.
QSerialPort::OneAndHalfStop 3 1.5 stop bits. This is only for the Windows platform.
QSerialPort::TwoStop 2 2 stop bits.

Property Documentation

baudRate : qint32

This property holds the data baud rate for the desired direction

If the setting is successful or set before opening the port, returns true ; otherwise returns false and sets an error code which can be obtained by accessing the value of the QSerialPort::error property. To set the baud rate, use the enumeration QSerialPort::BaudRate or any positive qint32 value.

Note: If the setting is set before opening the port, the actual serial port setting is done automatically in the QSerialPort::open() method right after that the opening of the port succeeds.

Warning: Setting the AllDirections flag is supported on all platforms. Windows supports only this mode.

Warning: Returns equal baud rate in any direction on Windows.

The default value is Baud9600, i.e. 9600 bits per second.

Access functions:

qint32 baudRate (QSerialPort::Directions directions = AllDirections) const
bool setBaudRate (qint32 baudRate, QSerialPort::Directions directions = AllDirections)

Notifier signal:

void baudRateChanged (qint32 baudRate, QSerialPort::Directions directions)

[bindable] breakEnabled : bool

Note: This property supports QProperty bindings.

This property holds the state of the transmission line in break

Returns true on success, false otherwise. If the flag is true then the transmission line is in break state; otherwise is in non-break state.

Note: The serial port has to be open before trying to set or get this property; otherwise returns false and sets the NotOpenError error code. This is a bit unusual as opposed to the regular Qt property settings of a class. However, this is a special use case since the property is set through the interaction with the kernel and hardware. Hence, the two scenarios cannot be completely compared to each other.

[bindable] dataBits : DataBits

Note: This property supports QProperty bindings.

This property holds the data bits in a frame

If the setting is successful or set before opening the port, returns true ; otherwise returns false and sets an error code which can be obtained by accessing the value of the QSerialPort::error property.

Note: If the setting is set before opening the port, the actual serial port setting is done automatically in the QSerialPort::open() method right after that the opening of the port succeeds.

The default value is Data8, i.e. 8 data bits.

dataTerminalReady : bool

This property holds the state (high or low) of the line signal DTR

Returns true on success, false otherwise. If the flag is true then the DTR signal is set to high; otherwise low.

Note: The serial port has to be open before trying to set or get this property; otherwise false is returned and the error code is set to NotOpenError.

Access functions:

bool isDataTerminalReady ()
bool setDataTerminalReady (bool set)

Notifier signal:

void dataTerminalReadyChanged (bool set)

[bindable read-only] error : SerialPortError

Note: This property supports QProperty bindings.

This property holds the error status of the serial port

The I/O device status returns an error code. For example, if open() returns false , or a read/write operation returns -1 , this property can be used to figure out the reason why the operation failed.

The error code is set to the default QSerialPort::NoError after a call to clearError()

[bindable] flowControl : FlowControl

Note: This property supports QProperty bindings.

This property holds the desired flow control mode

If the setting is successful or set before opening the port, returns true ; otherwise returns false and sets an error code which can be obtained by accessing the value of the QSerialPort::error property.

Note: If the setting is set before opening the port, the actual serial port setting is done automatically in the QSerialPort::open() method right after that the opening of the port succeeds.

The default value is NoFlowControl, i.e. no flow control.

[bindable] parity : Parity

Note: This property supports QProperty bindings.

This property holds the parity checking mode

If the setting is successful or set before opening the port, returns true ; otherwise returns false and sets an error code which can be obtained by accessing the value of the QSerialPort::error property.

Note: If the setting is set before opening the port, the actual serial port setting is done automatically in the QSerialPort::open() method right after that the opening of the port succeeds.

The default value is NoParity, i.e. no parity.

requestToSend : bool

This property holds the state (high or low) of the line signal RTS

Returns true on success, false otherwise. If the flag is true then the RTS signal is set to high; otherwise low.

Note: The serial port has to be open before trying to set or get this property; otherwise false is returned and the error code is set to NotOpenError.

Note: An attempt to control the RTS signal in the HardwareControl mode will fail with error code set to UnsupportedOperationError, because the signal is automatically controlled by the driver.

Access functions:

bool isRequestToSend ()
bool setRequestToSend (bool set)

Notifier signal:

void requestToSendChanged (bool set)

[bindable] stopBits : StopBits

Note: This property supports QProperty bindings.

This property holds the number of stop bits in a frame

If the setting is successful or set before opening the port, returns true ; otherwise returns false and sets an error code which can be obtained by accessing the value of the QSerialPort::error property.

Note: If the setting is set before opening the port, the actual serial port setting is done automatically in the QSerialPort::open() method right after that the opening of the port succeeds.

The default value is OneStop, i.e. 1 stop bit.

Member Function Documentation

[explicit] QSerialPort:: QSerialPort ( QObject *parent = nullptr)

Constructs a new serial port object with the given parent.

[explicit] QSerialPort:: QSerialPort (const QString &name, QObject *parent = nullptr)

Constructs a new serial port object with the given parent to represent the serial port with the specified name.

The name should have a specific format; see the setPort() method.

[explicit] QSerialPort:: QSerialPort (const QSerialPortInfo &serialPortInfo, QObject *parent = nullptr)

Constructs a new serial port object with the given parent to represent the serial port with the specified helper class serialPortInfo.

[virtual noexcept] QSerialPort:: ~QSerialPort ()

Closes the serial port, if necessary, and then destroys object.

[signal] void QSerialPort:: baudRateChanged ( qint32 baudRate, QSerialPort::Directions directions)

This signal is emitted after the baud rate has been changed. The new baud rate is passed as baudRate and directions as directions.

Note: Notifier signal for property baudRate.

[override virtual] qint64 QSerialPort:: bytesAvailable () const

Returns the number of incoming bytes that are waiting to be read.

[override virtual] qint64 QSerialPort:: bytesToWrite () const

Returns the number of bytes that are waiting to be written. The bytes are written when control goes back to the event loop or when flush() is called.

[override virtual] bool QSerialPort:: canReadLine () const

Returns true if a line of data can be read from the serial port; otherwise returns false .

bool QSerialPort:: clear ( QSerialPort::Directions directions = AllDirections)

Discards all characters from the output or input buffer, depending on given directions directions. This includes clearing the internal class buffers and the UART (driver) buffers. Also terminate pending read or write operations. If successful, returns true ; otherwise returns false .

Note: The serial port has to be open before trying to clear any buffered data; otherwise returns false and sets the NotOpenError error code.

[override virtual] void QSerialPort:: close ()

Note: The serial port has to be open before trying to close it; otherwise sets the NotOpenError error code.

[signal] void QSerialPort:: dataBitsChanged ( QSerialPort::DataBits dataBits)

This signal is emitted after the data bits in a frame has been changed. The new data bits in a frame is passed as dataBits.

Note: Notifier signal for property dataBits.

[signal] void QSerialPort:: dataTerminalReadyChanged ( bool set)

This signal is emitted after the state (high or low) of the line signal DTR has been changed. The new the state (high or low) of the line signal DTR is passed as set.

Note: Notifier signal for property dataTerminalReady.

[signal] void QSerialPort:: errorOccurred ( QSerialPort::SerialPortError error)

This signal is emitted when an error occurs in the serial port. The specified error describes the type of error that occurred.

Note: Notifier signal for property error.

[signal] void QSerialPort:: flowControlChanged ( QSerialPort::FlowControl flow)

This signal is emitted after the flow control mode has been changed. The new flow control mode is passed as flow.

Note: Notifier signal for property flowControl.

bool QSerialPort:: flush ()

This function writes as much as possible from the internal write buffer to the underlying serial port without blocking. If any data was written, this function returns true ; otherwise returns false .

Call this function for sending the buffered data immediately to the serial port. The number of bytes successfully written depends on the operating system. In most cases, this function does not need to be called, because the QSerialPort class will start sending data automatically once control is returned to the event loop. In the absence of an event loop, call waitForBytesWritten() instead.

Note: The serial port has to be open before trying to flush any buffered data; otherwise returns false and sets the NotOpenError error code.

QSerialPort::Handle QSerialPort:: handle () const

If the platform is supported and the serial port is open, returns the native serial port handle; otherwise returns -1 .

Warning: This function is for expert use only; use it at your own risk. Furthermore, this function carries no compatibility promise between minor Qt releases.

[override virtual] bool QSerialPort:: isSequential () const

Always returns true . The serial port is a sequential device.

[override virtual] bool QSerialPort:: open ( QIODeviceBase::OpenMode mode)

Reimplements: QIODevice::open(QIODeviceBase::OpenMode mode).

Opens the serial port using OpenMode mode, and then returns true if successful; otherwise returns false and sets an error code which can be obtained by calling the error() method.

Note: The method returns false if opening the port is successful, but could not set any of the port settings successfully. In that case, the port is closed automatically not to leave the port around with incorrect settings.

[signal] void QSerialPort:: parityChanged ( QSerialPort::Parity parity)

This signal is emitted after the parity checking mode has been changed. The new parity checking mode is passed as parity.

Note: Notifier signal for property parity.

QSerialPort::PinoutSignals QSerialPort:: pinoutSignals ()

Returns the state of the line signals in a bitmap format.

From this result, it is possible to allocate the state of the desired signal by applying a mask «AND», where the mask is the desired enumeration value from QSerialPort::PinoutSignals.

Note: This method performs a system call, thus ensuring that the line signal states are returned properly. This is necessary when the underlying operating systems cannot provide proper notifications about the changes.

Note: The serial port has to be open before trying to get the pinout signals; otherwise returns NoSignal and sets the NotOpenError error code.

QString QSerialPort:: portName () const

Returns the name set by setPort() or passed to the QSerialPort constructor. This name is short, i.e. it is extracted and converted from the internal variable system location of the device. The conversion algorithm is platform specific:

Platform Brief Description
Windows Removes the prefix «\\.\» or «//./» from the system location and returns the remainder of the string.
Unix, BSD Removes the prefix «/dev/» from the system location and returns the remainder of the string.

qint64 QSerialPort:: readBufferSize () const

Returns the size of the internal read buffer. This limits the amount of data that the client can receive before calling the read() or readAll() methods.

A read buffer size of 0 (the default) means that the buffer has no size limit, ensuring that no data is lost.

[override virtual protected] qint64 QSerialPort:: readData ( char *data, qint64 maxSize)

Reimplements: QIODevice::readData(char *data, qint64 maxSize).

[override virtual protected] qint64 QSerialPort:: readLineData ( char *data, qint64 maxSize)

Reimplements: QIODevice::readLineData(char *data, qint64 maxSize).

[signal] void QSerialPort:: requestToSendChanged ( bool set)

This signal is emitted after the state (high or low) of the line signal RTS has been changed. The new the state (high or low) of the line signal RTS is passed as set.

Note: Notifier signal for property requestToSend.

void QSerialPort:: setPort (const QSerialPortInfo &serialPortInfo)

Sets the port stored in the serial port info instance serialPortInfo.

void QSerialPort:: setPortName (const QString &name)

Sets the name of the serial port.

The name of the serial port can be passed as either a short name or the long system location if necessary.

void QSerialPort:: setReadBufferSize ( qint64 size)

Sets the size of QSerialPort’s internal read buffer to be size bytes.

If the buffer size is limited to a certain size, QSerialPort will not buffer more than this size of data. The special case of a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default.

This option is useful if the data is only read at certain points in time (for instance in a real-time streaming application) or if the serial port should be protected against receiving too much data, which may eventually cause the application to run out of memory.

[signal] void QSerialPort:: stopBitsChanged ( QSerialPort::StopBits stopBits)

This signal is emitted after the number of stop bits in a frame has been changed. The new number of stop bits in a frame is passed as stopBits.

Note: Notifier signal for property stopBits.

[override virtual] bool QSerialPort:: waitForBytesWritten ( int msecs = 30000)

This function blocks until at least one byte has been written to the serial port and the bytesWritten() signal has been emitted. The function will timeout after msecs milliseconds; the default timeout is 30000 milliseconds. If msecs is -1, this function will not time out.

The function returns true if the bytesWritten() signal is emitted; otherwise it returns false (if an error occurred or the operation timed out).

[override virtual] bool QSerialPort:: waitForReadyRead ( int msecs = 30000)

This function blocks until new data is available for reading and the readyRead() signal has been emitted. The function will timeout after msecs milliseconds; the default timeout is 30000 milliseconds. If msecs is -1, this function will not time out.

The function returns true if the readyRead() signal is emitted and there is new data available for reading; otherwise it returns false (if an error occurred or the operation timed out).

[override virtual protected] qint64 QSerialPort:: writeData (const char *data, qint64 maxSize)

Reimplements: QIODevice::writeData(const char *data, qint64 maxSize).

© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *