简体   繁体   中英

Serial port won't open in linux ubuntu

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM