我需要用 C 为 Linux 的条形码阅读器编写驱动程序。条形码阅读器通过串行总线工作。当我向条形码阅读器发送一组命令时,条形码阅读器应该向我返回状态消息。我设法配置了端口并创建了一个信号处理程序。在信号处理程序中,我读取串行总线接收的数据。
所以问题是:我应该读取缓冲区中的数据然后使用它吗?我什至可以使用以这种方式配置的端口将数据写入缓冲区吗?当设备回复我时,根据该回复数据,我需要向设备发送另一个命令。另外,我可以write()
用来写消息吗?如果我不能使用它,我应该使用什么命令?你能帮我写写命令吗?
我发送给设备的命令总是 7 个字节,但回复数据在 7-32 个字节之间变化。如果读取函数发送不同数量的读取字节,我如何确定我收到了所有数据,以便我可以使用它?
这是我写的一些代码。我是否朝着正确的方向前进?再一次,这个想法非常简单:我正在向设备发送命令,设备会打断我并回复。我阅读了发送的内容,处理回复数据,并根据该数据发送另一个命令。谢谢转发。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <errno.h>
#include <termios.h>
void signal_handler_IO (int status); /* definition of signal handler */
int n;
int fd;
int connected;
char buffer[14];
int bytes;
struct termios termAttr;
struct sigaction saio;
int main(int argc, char *argv[])
{
fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/ttyO1\n");
exit(1);
}
saio.sa_handler = signal_handler_IO;
saio.sa_flags = 0;
saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);
fcntl(fd, F_SETFL, FNDELAY);
fcntl(fd, F_SETOWN, getpid());
fcntl(fd, F_SETFL, O_ASYNC );
tcgetattr(fd,&termAttr);
//baudRate = B115200;
cfsetispeed(&termAttr,B115200);
cfsetospeed(&termAttr,B115200);
termAttr.c_cflag &= ~PARENB;
termAttr.c_cflag &= ~CSTOPB;
termAttr.c_cflag &= ~CSIZE;
termAttr.c_cflag |= CS8;
termAttr.c_cflag |= (CLOCAL | CREAD);
termAttr.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
termAttr.c_iflag &= ~(IXON | IXOFF | IXANY);
termAttr.c_oflag &= ~OPOST;
tcsetattr(fd,TCSANOW,&termAttr);
printf("UART1 configured....\n");
connected = 1;
while(connected == 1){
//write function and read data analyze(Processing)
}
close(fd);
exit(0);
}
void signal_handler_IO (int status)
{
bytes = read(fd, &buffer, sizeof(buffer));
printf("%s\n", buffer);
}