Linux串口应用程序不工作

标签 linux serial-port embedded-linux

我正在尝试连接具有 RS232 接口(interface)的热敏打印机。

当与 putty、terraterm 和 minicom 一起使用时,打印机工作正常。

但我无法在 linux 中使用 C 程序使其工作。

程序如下:

#include <stdbool.h>
#include <time.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/poll.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>


#define _POSIX_SOURCE 1 /* POSIX compliant source */


struct termios options;


int main(void /*int argc,char *argv[]*/)
{
    int fd; /* File descriptor for the port */


      fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
      if (fd == -1)
      {
       /*
    * Could not open the port.
    */

    perror("open_port: Unable to open /dev/ttyS0 - ");
      }
      else
      {

    printf("Success\n");

        /*
     * Get the current options for the port...
     */

    tcgetattr(fd, &options);

        /*
         * Set the baud rates to 9600...
         */

    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);

    /*
     * Enable the receiver and set local mode...
     */

    options.c_cflag |= (CLOCAL | CREAD);



    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    options.c_cflag &= ~CRTSCTS;


    options.c_iflag |= (IXON | IXOFF | IXANY);

    /*
     * Set the new options for the port...
     */

    tcsetattr(fd, TCSANOW, &options);

    write(fd, "abcd", 4);

      }


      return 0;

}

最佳答案

串口有可能已经被另一个应用程序打开。

使用以下行获取错误代码并找到问题所在。在 open() 调用中,tcsetattr()write()...

#include <error.h>

printf ("Error no is : %d\n", errno);
printf("Error description is : %s\n",strerror(errno));

关于Linux串口应用程序不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8151036/

相关文章:

python - pyserial - 如何读取从串行设备发送的最后一行

embedded - 学习电路板启动和硬件诊断的最佳方法是什么?

linux - 使用 hcidump 获取 RSSI

c++ - 在 Linux 上如何将桌面捕获为 OpenGL 纹理?

c - 为什么从 sockaddr_in 到 sockaddr 的转换有效

python - 在 python IDE 上正确运行的 linux 终端中运行的 python 应用程序的错误输出

c# - C# 和 java write() 之间的区别

linux - 如何在 u-boot 中禁用串行控制台(非内核)

linux - 具有快速启动功能的 Raspberry Pi 嵌入式编程

c - 为什么程序死于使用 malloc 和 free(相同地址)