通过串口读取ELM327芯片时遇到问题。 这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h
#include <sys/ioctl.h>
#define DEVICE "/dev/ttyUSB0"
#define SPEED B38400
int main()
{
struct termios old_stdio; //save the current port settings
int tty_fd; //file descriptor for serial port
int retval, res, n, res2, read1, wri;
char buf[255];
char buf2[255];
tty_fd = open(DEVICE, O_RDWR | O_NOCTTY | O_NDELAY );
if(tty_fd < 0)
{
perror(DEVICE);
exit(-1);
}
printf("Init 1 complete.\n");
tcflush(tty_fd, TCIOFLUSH);
fcntl(tty_fd, F_SETFL, 0);
if(tcgetattr(tty_fd, &old_stdio) != 0)
{
perror(DEVICE);
exit(-1);
}
printf("Init 2 complete.\n");
struct termios newtio;
if(tcgetattr(tty_fd, &newtio) != 0)
{
perror(DEVICE);
exit(-1);
}
cfsetospeed(&newtio, B38400);
cfsetispeed(&newtio, B38400);
printf("Init 3 complete.\n");
newtio.c_cflag |= CLOCAL | CREAD | HUPCL;
newtio.c_iflag |= ICRNL | IGNPAR;
newtio.c_lflag &= !(ICANON | ISIG);
newtio.c_lflag |= ECHOK | ECHOE | ECHOKE;
newtio.c_oflag |= ONLCR;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
if(tcsetattr(tty_fd, TCSANOW, &newtio) != 0)
{
perror(DEVICE);
exit(-1);
}
printf("Init 4 complete.\n");
for(n = 55; n > 0; n--)
{
printf("Please enter a command: ");
(void)fgets(buf2, 255, stdin);
printf("Ok.input was %s ",&buf2);
(void)write(tty_fd, buf2, strlen(buf2));
(void)write(tty_fd, "\r", 1);
printf("Ok. Waiting for reply\n");
res = read(tty_fd, &buf, 255);
printf("Read:%d %s \n",res, &buf);
}
//restore the original port settings
tcsetattr(tty_fd, TCSANOW, &old_stdio);
close(tty_fd);
return EXIT_SUCCESS; //return all good
}
我可以写信给设备,但写完atz
之后,阅读功能并没有读取任何东西。但在再次输入\n
之后,它会在终端打印输出。
Init 1 complete.
Init 2 complete.
Init 3 complete.
Init 4 complete.
Please enter a command: atz
Ok.input was atz
Ok. Waiting for reply
Read:0
Please enter a command:
Ok.input was
Ok. Waiting for reply
Read:20 atz
ELM327 v1.5
>�
Please enter a command:
任何人都知道为什么会发生这种情况?