PDA

View Full Version : how can 20 Bytes be put into a string[20] in Qt and then be sent by a serial port



Alex22
18th November 2016, 07:30
Hi
I have two questions. I need first to put 20 bytes into a string[20]. In C++ i did that by this code:


string[0]='ab'; //ab is in Hex (0xab)
string[1]='50'; //50 is in Hex (0x50)
.
.
.
string[19]='54' //54 is in Hex


After filling string[20], i must send it by serial port.
My first question is: how could i write above code in Qt to send by a serialport?
and my second question is: can i use QByteArray and then use QSerialPort::write(QByteArray)?

ChrisW67
18th November 2016, 07:55
The answer to the second question is yes.

The answer to the first is in two parts:

The code you present does not do what you describe assuming that "string" is an array of char. 'ab' is not a character literal equal to 0xab.
When you correct that, you can use QByteArray in the same way.

Your program will still be in C++: Qt is not a language.

Alex22
18th November 2016, 08:15
When you correct that, you can use QByteArray in the same way.


Thanks Chris. Then must i use QByteArray::append() to fill 20 bytes into a QByteArray? is this garantide to send exactly 20 bytes to another device by serial port?

ChrisW67
19th November 2016, 20:06
You can use QByteArray::append() and if you append 20 bytes to an empty QByteArray then that's how many bytes will be sent. Using append() will extend the array to add the new bytes.

You can use a number of different QByteArray constructors or QByteArray::resize() to create an "empty" 20 byte buffer and operator[] to address individual bytes.in this way the QByteArray code could even look like the bare C-style code you started with.