Read data from a serial port to USB in Ubuntu using C++
Start by opening a file (fstream, FILE * or OS handle) to "/dev/ttySn" where n
is the number of the device, then read away.
#include <string>
#include <fstream>
#include <iostream>
std::string str;
std::fstream f;
f.open("/dev/ttyS0");
while (f >> str)
{
std::cout << str;
}
That should "echo" out the contents of ttyS0 - that may of course be the "wrong" port for your device, but if you know where it is connected that should do the job. You may also need to set the configuration of the port. For example, using the stty
command - baudrate would be the most important, so something like stty -F /dev/ttyS0 19200
will set the baudrate (actually bitrate) to 19200 bits per second. Most other parameters are probably ok.
Zeyad
Updated on June 05, 2022Comments
-
Zeyad almost 2 years
I have a GPS that has a serial port, and it has a transfer cable from serial to USB. It is connected to the laptop through USB, and is transmitting data in Hex. I want to use this data in my C++ code on Ubuntu. Any ideas where could I start, and how I could manage to read the data?
-
Richard Chambers about 11 yearsSee this stack overflow on setting up the connection stackoverflow.com/questions/5347962/…
-
Richard Chambers about 11 yearsAnd then this one on reading and writing the device stackoverflow.com/questions/5014451/…
-
dbasnett about 11 yearsAnd you can help us help you by posting the exact manufacturer and model of the GPS.
-
Zeyad about 11 yearsnavilock.de/produkte/G_60109/merkmale.html?setLanguage=en this is the exact GPS we are using here.
-
Lightness Races in Orbit over 5 yearsIt's not "transmitting data in hex". It's transmitting data in some encoded binary form like all computers do - you're just looking at the values in hex.
-
-
Zeyad about 11 yearsThank you. I have a second question how do I know the port of the device ?
-
Mats Petersson about 11 yearsI have no idea. Try having a look in
dmesg
or something to find which port the kernel gives it when you plug your USB serial port in. -
Lightness Races in Orbit over 5 yearsI've corrected Mats's answer; probably no need for this now