0

I can't open serial port to start communication in linux ubuntu. I've tried this:

int OpenPort(void) {

int fd; 

fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);

if(fd == -1)
{
  printf("Failed to open port.\n");
}
else
{
    fcntl(fd, F_SETFL, 0);
    printf("Opened!\n");
}

return(fd);
}

int main()
{
  int x = OpenPort();
  printf("%i\n", x);

  exit(0);
}

I'm new in linux and found this code online, but it doesn't work for me.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
user2081328
  • 159
  • 3
  • 15
  • What is the error? Try to replace `printf("Failed to open port.\n")` to `printf("Failed to open port: %s.\n", strerror(errno))` or `perror("Failed to open port.")`. – loentar Feb 25 '14 at 12:51
  • 1
    When a system call fails, you should print the value of [`errno`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/errno.html) which contains the error code. You can get a nice printable string with the [`strerror`](http://pubs.opengroup.org/onlinepubs/009695399/functions/strerror.html) function. You can also use the [`perror`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/perror.html) function to print the message directly. – Some programmer dude Feb 25 '14 at 12:51
  • error is Permission denied – user2081328 Feb 25 '14 at 12:52

1 Answers1

2

You need to run as superuser/root to access serial port in linux. Try running your binary as sudo. If you can verify this is the problem but you do not want your process to be run by root user there are options you can use in your code to obtain root privileges. This answer might be useful reading How to programmatically gain root privileges?

Community
  • 1
  • 1
mathematician1975
  • 21,161
  • 6
  • 59
  • 101
  • 1
    It works with sudo, but how to run it without it? How to get permissions? I'm running ubuntu as administrator. – user2081328 Feb 25 '14 at 12:57
  • @user2081328 See that answer that I have linked to in my edit. – mathematician1975 Feb 25 '14 at 12:58
  • @user2081328 By the way I noticed you have asked 13 questions here on SO but have not accepted any answers. If you find that an answer solved your problem you can accept it. This helps people who look at your question in future to see which is the best solution. – mathematician1975 Feb 25 '14 at 13:00