我正在尝试连接具有 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/