写linux的read函数串口答应CAN通信数据的代码
时间: 2023-03-10 16:25:33 浏览: 100
可以参考下面的代码例子:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>#define CAN_BUFFER_LENGTH 8int main(int argc, char **argv)
{
int fd;
unsigned char Buff[CAN_BUFFER_LENGTH];
int nBytes;
int i;
struct termios options;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK); tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
tcsetattr(fd, TCSANOW, &options); ioctl(fd, FIONREAD, &nBytes);
if (nBytes > 0)
{
nBytes = read(fd, Buff, CAN_BUFFER_LENGTH);
for (i = 0; i < nBytes; i++)
{
printf("%02X ", Buff[i]); // print as Hex
}
}
close(fd);
return 0;
}