How to connect to a serial port in Linux using c++?

In Linux all devices have a file in /dev directory, so the communication with these devices is very simple, just need to open necessary file, and make read and write operations upon them.

In this article is shown how to connect to serial port in Linux, using c++.

First of all we include all needed libraries, and declare all necessary variables:

#include <stdio.h>

#include <string.h>

#include <fcntl.h>

#include <errno.h>

#include <termios.h>

#include <unistd.h>

int fd1;

int fd2;

char *buff,*buffer,*bufptr;

int wr,rd,nbytes,tries;

int main()

{

return 0;

}

Next step, we connect to device through associated file and check the connection:

fd1=open(“/dev/ttyS0″, O_RDWR | O_NOCTTY | O_NDELAY);

if (fd1 == -1 )

{

perror(“open_port: Unable to open /dev/ttyS0 – “);

}

else

{

fcntl(fd1, F_SETFL,0);

printf(“Port 1 has been sucessfully opened and %d is the file description\n”,fd1);

}

Where, “/dev/ttyS0” is associated with COM1 port.

With following code we send to device some bits:

wr=write(fd1,”ATZ\r”,4);

And for reading response from device:

rd=read(fd1,buff,10);

printf(“Bytes sent are %d \n”,rd);

At the end, close the connection:

close(fd1);

Enjoy!

About these ads

8 Responses to “How to connect to a serial port in Linux using c++?”

  1. Gordon Says:

    Hi,

    Thanks for the example, it was really helpful. I found that you can achieve pretty much the same result using file IO streams. I find them a bit easier to use…

    Cheers,
    Gordon

  2. Dam Says:

    Are you talking about how to write to port with C++ <— not C

  3. mohammad Says:

    Thanks A LOT !!!

  4. Mark Says:

    Thanks for posting this, but how is this C++? It’s pure C.

  5. jlmuniz Says:

    Why are you saying is C++ when you are using stdio.h wich is a “C” library, instead of , i dont see inheritance, polymorphism, etc…

  6. Messer Says:

    Great tut! Thanks a lot.
    Solved my issue definitely!

    Regards;


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: