Zeyad
Zeyad

Reputation: 821

Read data from a serial port to USB in Ubuntu using C++

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?

Upvotes: 4

Views: 12452

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129524

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.

Upvotes: 5

Matt Kleinsmith
Matt Kleinsmith

Reputation: 1139

#include <iostream>
#include <fstream>

int main () {
    std::string str;
    std::fstream f;
    f.open("/dev/ttyS0");
    while (f >> str)
    {
        std::cout << str;
    }
}

Here's a working snippet. When I had this question I struggled to find the needed include statements and the correct namespace.

This answer was based on Mats Petersson's answer

Edit: This would be more appropriate as a comment to Mats Petersson's answer. The comment could be:

"#include fstream for fstream and #include iostream for string and cout. The namespace of fstream and cout is std."

Upvotes: 0

Related Questions