c - 打开并配置串口

标签 c serial-port

我编写了以下代码,在其中打开并配置我的串行端口设备

int open_port(void)
{
 int fd; // file description for the serial port 
 fd = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);
 if(fd == -1) // if open is unsucessful
  {
   //perror("open_port: Unable to open /dev/ttyAMA0 - ");
   printf("open_port: Unable to open /dev/ttyAMA0. \n");
  }
 else
 {
  fcntl(fd, F_SETFL, 0);
  printf("port is open.\n");
 }

return(fd);
} //open_port

并配置端口

int configure_port(int fd)      // configure the port
{
 struct termios port_settings;      // structure to store the port settings in
 cfsetispeed(&port_settings, B9600);    // set baud rates
 cfsetospeed(&port_settings, B9600);
 port_settings.c_cflag &= ~PARENB;    // set no parity, stop bits, data bits
 port_settings.c_cflag &= ~CSTOPB;
 port_settings.c_cflag &= ~CSIZE;
 port_settings.c_cflag |= CS8;
 tcsetattr(fd, TCSANOW, &port_settings);    // apply the settings to the port
 return(fd);
} //configure_port 

我的问题(也许很简单)是我必须在这两个函数中精确更改什么才能拥有

FILE *fd;
fd=fopen("/dev/ttyUSB0","r");

而不是 fd= open(...) 等?

最佳答案

您能否在初始化后的下一次调用中将文件描述符(fd)转换为文件指针(fp)?

文件* fp = fdopen(fd,"w")

关于c - 打开并配置串口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17022874/

相关文章:

Python没有名为serial的模块/没有名为requests的模块

connection - Minicom 启动时没有 cmd

windows - Windows 7打开串口命令

serial-port - 串口发送/接收错误字符

c - 硬编码指针值

MySQL:使用 C 将值插入列

c - 读取文件并跳过空格?

c - 如何使用 scanf 与 3 个整数和它们之间的 '/'

c - 为单个测试可执行文件的范围替换通用 .o 文件中的 C 函数

c# - 判断串口是普通COM还是SPP