Qt serial port does not read the string well - c++

I use Qt 5.4 on Ubuntu Gnome 14.04 LTS to reads a string line from serial port. Everything was OK, but when I re-installed Ubuntu Gnome 14.04 and Qt 5.4, my code of serial port does not work well. When the Arduino send "0" the code of Qt reads it like this "�" and the other numbers that sends over serial the Qt reads it as a letters and symbols. I think the problem with unicode of my Qt. The unicode of my ubuntu is en.US.UTF-8 and the QT unicode is setted to "system". Please help me :(
This is my code that read the data from serial port:
QByteArray input;
if (serial->canReadLine()) //chect if data line is ready
input.clear();
input = serial->readLine(); //read data line from sreial port
ui->label->setText(input);
qDebug ()<<input<<endl;
this code of Arduino it is working fine with CuteCom and Arduino serial monitor
const int analogInPin = A0;
unsigned int sensorValue = 0; // value read from the pot
void setup() {
Serial.begin(19200);
}
void loop() {
Serial.print("\n");
Serial.print("#");
for (int i=0; i < 5; i++) {
// read the analog in value:
sensorValue = analogRead(analogInPin);
Serial.print(sensorValue);
Serial.print("#");
};
sensorValue = analogRead(analogInPin);
Serial.print(sensorValue);
Serial.print("# \n");
}
Sorry for my English

If the parity or data/stop bit parameters are different you can still write and read, but you get "funny" output similar to the one you showed us above, and this is not a problem of the unicode setting (especially not with '0', which is a character of the ASCII set).
Try setting the same port parameters explicitly on both ends just before starting the communication.

There are several problems:
You didn't post enough code to know the context of how you use it. I'm assuming that you handle the data in a method attached to the readyRead signal.
You are only reading one line, where you should be reading lines until no more are available. The readyRead signal can be emitted with any number of bytes available for reading: these may make up no complete lines, or several complete lines! If you don't keep on reading lines until no more are available, you'll be severely lagging behind incoming data.
You are using implicit QByteArray to QString conversions. These are a bad code smell. Be explicit about it.
You have fairly verbose code. You don't need to clear a QByteArray before setting its value. You also should declare it at the point of use. Better yet, use type inference that C++11 brought.
Thus:
class MyWindow : public QDialog {
QSerialPort m_port;
void onData() {
while (m_port->canReadLine())
auto input = QString::fromLatin1(m_port->readLine());
ui->label->setText(input);
qDebug() << input;
}
}
...
public:
MyWindow(QWidget * parent = 0) : QDialog(parent) {
...
connect(&m_port, &QIODevice::readyRead, this, &MyWindow::onData);
}
};

Related

Arduino visual studio and bluetooth HC-05

What I want is using visual studio to read and write to arduino UNO using a bluetooth device HC-05. In the previous step, I am able to communicate using visual studio c++ and Arduino directly through usb port. The code I am using is basically same as arduino and visual studio c++, 2 way serial communication. In arduino, I have command as:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0) {
char c = Serial.read();
if (c == '1')
Serial.write("FORW");
else if (c == '2')
Serial.write("LEFT");
else if (c == '3')
Serial.write("RIGTH");
else if (c == '4')
Serial.write("BACK");
else if (c == '5')
Serial.write("STOP");
else
Serial.write("Invalid");
}
and my/output is (using arduino usb directly):
Connection established!!!
Enter your command: 1
arduino: FORW
Enter your command: 2
arduino: LEFT
Enter your command: 3
arduino: RIGTH
Enter your command: 6
arduino: Invalid
Enter your command:
When I added a bluetooth Module HC-05 with it. Using serial monitor can get same output, but when I used visual studio, the first input never gives back a output, while for the following output, it always gives a previous output not a current one, as following:
Connection established!!!
Enter your command: 1
arduino:
Enter your command: 2
arduino: FORW
Enter your command: 1
arduino: LEFT
Enter your command: 4
arduino: FORW
Enter your command: 6
arduino: BACK
Enter your command: 2
arduino: Invalid
Enter your command:
I don't know if following steps may give error:
bluetooth is supplied with 5v
I cross connected bluetooth TX RX with Arduino Uno
bluetooth HC-05 is in default mode, I didn't change anything about it.
When bluetooth is connected with PC, it shows two ports: COM4 'DEV-B' & COM5,so I just changed the code in visual studio to make it connect to COM4.
Bound rate is set to be 9600 on Arduino also indicated in visual studio.
So any idea why this would happen?
Most probably the problem is that in 10ms the previous communication can't reach you.
Now, I don't have much experience in programming with plain C++ and visual studio (I usually use the managed C++ extensions and the event loop) but when I have to deal with serial ports I usually use either events or parallel threads.
When using events, I use the SerialPort class and its DataReceived event. Since you are using Visual C++ this is the method I suggest you to use. Just let VS create a base skeleton for you by creating a managed console application instead of an empty one and see how events work.
If you want to use multiple threads, just use one thread to check for the input and the other to check for the serial. I'm afraid I can't help you on how to start and handle the threads (you have to use some OS or library functions, maybe pthread's ones), but the two threads functions can be something like this:
void thread1()
{
while (1)
{
std::cout << "Enter your command: ";
std::cin.get(command, 2); //input command
int msglen = strlen(command);
if (port->WriteData(command, msglen)); //write to arduino
printf("\n(writing success)\n");
}
}
void thread2()
{
while (1)
{
int n = port->ReadData(data, 4);
if (n != -1){
data[n] = 0;
cout <<"arduino: " data << endl;
}
Sleep(10);
}
}
The third solution is to check the input and the serial only when some data is there:
std::cout << "Enter your command: ";
while(1)
{
if (_kbhit())
{
std::cin.get(command, 2); //input command
int msglen = strlen(command);
if (port->WriteData(command, msglen)); //write to arduino
printf("\n(writing success)\n");
std::cout << "Enter your command: ";
}
//read from arduino output
n = port->ReadData(data, 4);
if (n != -1)
{
data[n] = 0;
cout <<"arduino: " data << endl;
}
Sleep(10);
}
These are the solutions if you want to send multiple commands (i.e. make the program wait for the input, send it and then wait for another input).
If you want to just use it for one command and then exit, just wait for some data:
std::cout << "Enter your command: ";
std::cin.get(command, 2); //input command
int msglen = strlen(command);
if (port->WriteData(command, msglen)); //write to arduino
printf("\n(writing success)\n");
while ((n = port->ReadData(data, 4)) <= 0)
Sleep(10);
data[n] = 0;
cout <<"arduino: " data << endl;
The easiest but most unsuggested solution is to just increase the sleep period (e.g. to 50 ms) to allow the packets to be sent and received.
One more thing, since sooner or later you will face this problem. Usually with communication (be it serial, ethernet, ...) you don't have control on how often the driver tells you when it received the data. When you receive "FORW", you usually receive it as a block, but sometimes you receive a block with "FOR" and another with "W", or "FO" "RW", or "F" "ORW". Or you can receive two consecutive messages, for instance "FORWLEFT". Consequently you should either
decide a "terminator" character, for instance #. The sending function sends FORW#, the receiving tests each received character until it finds the terminator and then processes all it received till that moment. For instance, it receives "FO". Append to the buffer (FO). No terminator, no processing. Then it receives "RW". Append to the buffer (FORW). No terminator, no processing. Then it receives "#LEFT#". Append to the buffer (FORW#LEFT#). The first terminator is at position 5, so analyze the first 5 bytes (FORW#) and remove them from the buffer (which now contains LEFT#). Still a terminator, analyze. If you don't like #, you can use a carriage return (\n), a space, a string terminator (\0); every character you are NOT using in the strings is fine.
make each command exactly the same length (for instance 4 chars). Then read every byte until the buffer is longer or equal to 4 chars, and process the first n bytes.

QIODevice::readAll() not working properly?

I am currently working on a project that involves serial communication between a Arduino and a laptop. I know the Arduino is indeed sending the data that I need, see this picture: http://s1.postimg.org/w5wisaetr/Help.png
Now on the other end my laptop is connected to the Arduino and running a program that I made using QT Creator. However, when reading data from the serial Port I can't get the program to display this information.
I connected my readData() function to be executed when data is received like this:
connect(m_serialPort, SIGNAL(readyRead()), m_dataGathering, SLOT(newData()));
This works and the newData() function is called whenever something in transmitted from the Arduino. However the function newData() does not display the data that I need.
newData():
void DataGathering::newData()
{
QByteArray rMsg = m_serial->readAll();
qDebug() << rMsg.constData();
}
This only sends empty message to the display. Like this: http://s2.postimg.org/dkcyip2u1/empty.png
The following code however works:
void DataGathering::newData()
{
QByteArray rMsg("\nTest...");// = m_serial->readAll();
qDebug() << rMsg.constData();
}
This code display the message like it should.
However, another difference in the output display is that when the working code is executed my console also displays a lot of Framing errors, I assumed this is because the baudrate of the unwanted characters differs from the data that I need.
That is why i started questioning the readAll() function.
It is also obvious that the Arduino is not only sending the data that I need but also some unwanted characters (see image in first link), but I don't see this as a problem since I will filter this out later.
All help is very much appreciated.
Update: I found out that the readAll() function is returning QByteArrays with size() equals to 0.
Looks like the serial port QIODevice does not implement bytesAvailable, if it returns 0. This may also be why readAll() fails, depending on how it is implemented. But at least readAll() has the problem of not being able to report error.
Try using read method instead for better diagnostics, like this (untested):
void DataGathering::newData()
{
QByteArray rMsg;
for(;;) {
char buf[256]; // read data in this size chunks
qint64 len = m_serial->read(buf, sizeof buf);
if (len <= 0) {
if (len < 0) {
qDebug() << "newData() read error" << m_serial->errorString();
}
break; // for(;;)
}
rMsg.append(buf, len);
}
qDebug() << "newData() got byte array" << rMsg.size() << ":" << rMsg;
}
It may not solve your problem, but with luck it will give you error message.

Set widget label text in a thread in Qt

I'm new in Qt and I'm really stuck with threading. I know that this is question answered many times, but I can't figure out how to solve my problem. I have widget application with several labels and I have a class that reads data from serial port. I need to read data continuously and show them in labels. I've found many different answers about threading in Qt, but I cant get any of them to work. Can anyone point me to the right direction.
This code shows approximately what I want to achieve:
serial port class:
SerialPort *port;
int value1;
int value2;
int value3;
void Port::ReadData()
{
// First I send data to serial port as a QByteArray
QByteArray data = port.readAll();
value1 = data[0];
value2 = data[1];
value3 = data[3];
// Of course it's not really like this but I process data and assign them to
variables
}
Variables value1, value2 and value3 are public and I use label1->setText(portClass.value1) to show data. When I use this with a button click ti works but I want to close it to a loop and read data continuously.
labels have slots you can call from any thread using invokeMethod:
QMetaObject::invokeMethod (label1, "setText",
Q_ARG(QString,data[0]);
QMetaObject::invokeMethod (label2, "setText",
Q_ARG(QString,data[1]);
QMetaObject::invokeMethod (label3, "setText",
Q_ARG(QString,data[2]);

C++ Linux (Ubuntu) Writing to Serial Properly (For Arduino)

I'd like to know if there is a standard way to communicate with the serial device that is efficient. Should I be using a standard library? If so, which one?
Right now I'm fiddling around getting an LED to light up at a given amount based on number input. (Arduino code below). Just practice stuff.
See my overly simple and inefficient test:
#include <iostream>
#include <stdio.h>
using namespace std;
int
main()
{
FILE *file;
//Opening device file
int getnum;
while (true)
{
file = fopen("/dev/ttyACM5", "w");
cout << ">>" << endl;
cin >> getnum;
fprintf(file, "%d", getnum); //Writing to the file
fclose(file);
}
}
The while loop is cute, but hardly efficient if allowed to run without waiting for the user. I suspect the redundant fopen fclose use is stupid.
The microcontroller is going to be sensing states of a device and sending signals to the computer. The computer will do the "crunching" of all of these values, and sending messages back to alter the arduino's behavior. Basically the heavy thinking is being delegated to the computer, besides requiring human keyboard input.
Of course this is all for fun, but as you can see I need to "learn the rules" of serial interaction in C++! Any help or guidance greatly appreciated.
The arduino code:
char incomingByte = 0; // for incoming serial data
int led = 11;
int bright;
void
setup()
{
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void
loop()
{
// send data only when you receive data:
if (Serial.available() > 0)
{
// read the incoming byte:
incomingByte = Serial.read();
switch (incomingByte)
{
case '1':
bright = 10;
break;
case '2':
bright = 50;
break;
case '3':
bright = 255;
break;
default:
bright = 0;
break;
}
analogWrite(led, bright);
Serial.println(incomingByte);
}
}
I wonder why nobody answered this question for so long. Why are you saying this is an inefficient way? It isn't creating a physical file in the filesystem if you're referring to that. This is actually the right way to do it, just don't open and close the file descriptor inside the loop. If you want Serial.read to read a single value send '\n', fprint (file, "%d\n", value).

C++ - Making an event loop

Does anyone know how to make an event loop in c++ without a library? It doesn't have to be cross-platform, I'm on a Mac. Basically, I want the program to run and do nothing until the user presses the up arrow key, then the program will output "You pressed up" or something. All i can think of is having an infinite while or for loop and get input with cin, but I don't think cin can detect arrow keys and I believe it pauses the program until it reaches a '\n';
I would want it to look like this:
void RUN()
{
while(true)
{
// poll events and do something if needed
}
}
int main()
{
RUN();
}
I'm kinda sure it's possible without threads, and I've heard that this can be accomplished with fd_set or something, but I'm not sure how.
Any help would be really appreciated.
EDIT:
The program has to run in the background when there aren't any events. For example, Microsoft Word doesn't stop until the user presses a button, it keeps running. I want something like that, but command-line not GUI.
Since you're talking keyboard input, and not looking for a Mac look and feel, what you want is the UNIX way of doing it. And that is,
1) set the terminal in either raw or cbrk mode (I forget which).
2) now use read() to read single characters at a time.
3) temporarily echo the character read (as an int) so you can find what the up arrow key gives you.
As for the more general event loop question, where the only input device is the keyboard, you sit in a loop, and whenever a key is typed (in raw mode?) you call a routine with the value of the key typed. If you had more input devices, you would need multiple threads each could listen to a different device, putting what they find on a queues (with appropriate locking). The main loop would then check the queue and call a routine appropriately everytime something appears in it.
You can use ncurses and enable cbreak to get the raw input stream.
I've used a while loop with signal handlers. Like this incomplete snippet.
void getSomething()
{
std::cout << "Enter new step size: "; std::cout.flush();
std::cin >> globalVariable;
std::getchar(); // consume enter key.
}
void printCommands()
{
std::cout << "1: do something\n"
<< "q: quit\n"
<< "h: help\n"
<< std::endl;
}
void getCommand()
{
// Output prompt
std::cout << "Enter command ('h' for help): "; std::cout.flush();
// Set terminal to raw mode
int ret = system("stty raw");
// Wait for single character
char input = std::getchar();
// Reset terminal to normal "cooked" mode
ret = system("stty cooked");
std::cout << std::endl;
if (input == 'h') printCommands();
else if (input == '1') getSomething();
else if (input == 'q') {
g_next = true;
g_quit = true;
}
}
void
signalHandler(int signo)
{
if (signo == SIGINT) {
g_next = true;
} else if (signo == SIGQUIT) {
getCommand();
}
}
int main(int argc, char* argv[])
{
signal(SIGINT, signalHandler);
signal(SIGUSR1, signalHandler);
signal(SIGQUIT, signalHandler);
do {
// Stuff
} while (!g_quit);
exit(0);
}
The question has been updated to say "The program has to run in the background ... but command-line not GUI."
All traditional; *NIX shells that can put a program into the background also disconnect the program's standard input from the terminal, so AFAIK, this has become impossible.
This does not need to be Mac specific. The Mac supports *NIX mechanisms for reading characters from a keyboard.
AFAICT all the program is doing is waiting for a character, so it might as well block.
Normally the terminal device, tty (teletype!), is interpreting characters typed on the keyboard before your program can read them from standard input. Specifically the tty device normally buffers an entire line of text, and intercepts the rubout character (and a few others like CTRL+w) to edit the line of text. This pre-processing of characters is called a 'line discipline'
You need to set the tty device driver to stop doing that! Then you can get all of the characters the user types.
You change the device using ioctl or termios on the file descriptor.
Search for e.g. "ioctl tty line discipline raw" to understand the details, and find program examples.
You can set the terminal to 'raw' using the command line program stty.
Please read the stty man page because setting it back can be slightly tricky (NB: if you make a mistake it is often easier to kill the terminal, than try to fix it, because there is not echoing of anything you type)
It is possible that the up-arrow is not a single char, so it will require some byte-at-a-time decoding to avoid blocking at the wrong point in the input stream, i.e. if some input sequences are one character, and others two, or three characters, the decoding needs to happen at each byte to decide if there is a pending byte, or one too many read's might get issued, which would cause the program to block.