我正在将二进制数据从 arduino 发送到运行此代码的串行端口。
在十六进制模式下使用cutecom可以清楚地读取我对该串行端口的期望。如下所示。
00000000: 24 04 85 ab 47 43 04 04 24 04 85 ab 47 43 04 04
00000010: 24 04 85 ab 47 43 04 04 24 04 85 ab 47 43 04 04
到这里没有问题。我不认为我需要提供 arduino 代码。
我正在尝试用 c 读同样的东西。然而下面的代码只打印这个:
24 85 ab 47 43 24 85 ab 47 43 24 85 ab 47 43
由于某些原因,它跳过了 04。有什么想法吗?
#include <stdio.h>
#include <fcntl.h> /* File Control Definitions */
#include <termios.h> /* POSIX Terminal Control Definitions */
#include <unistd.h> /* UNIX Standard Definitions */
#include <errno.h> /* ERROR Number Definitions */
#include <signal.h>
#include <string.h>
#include <stdint.h>
int open_serial(char *port, int baud);
void main(void)
{
int tty = open_serial("/dev/ttyUSB0", B115200);
uint8_t buff[256]; /* Buffer to store the data received */
int n; /* Number of bytes read by the read() system call */
while (1) {
n = read(tty, &buff, sizeof buff);
if (n > 0){
//printf("-%d-\n ", n);
for(int i=0;i<n;i++){
printf("%02x ", buff[i]);
}
fflush(stdout);
}
}
}
int open_serial(char *port, int baud)
{
int fd = open( port, O_RDWR | O_NOCTTY);
if(fd == -1) /* Error Checking */
printf("\n Error! in Opening tty ");
struct termios SerialPortSettings; /* Create the structure */
tcgetattr(fd, &SerialPortSettings); /* Get the current attributes of the Serial port */
/* Setting the Baud rate */
cfsetispeed(&SerialPortSettings,B115200); /* Set Read Speed as 115200 */
cfsetospeed(&SerialPortSettings,B115200); /* Set Write Speed as 115200 */
/* 8N1 Mode */
SerialPortSettings.c_cflag &= ~PARENB; /* Disables the Parity Enable bit(PARENB),So No Parity */
SerialPortSettings.c_cflag &= ~CSTOPB; /* CSTOPB = 2 Stop bits,here it is cleared so 1 Stop bit */
SerialPortSettings.c_cflag &= ~CSIZE; /* Clears the mask for setting the data size */
SerialPortSettings.c_cflag |= CS8; /* Set the data bits = 8 */
SerialPortSettings.c_cflag &= ~CRTSCTS; /* No Hardware flow Control */
SerialPortSettings.c_cflag |= CREAD | CLOCAL; /* Enable receiver,Ignore Modem Control lines */
SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY); /* Disable XON/XOFF flow control both i/p and o/p */
SerialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* Non Cannonical mode */
SerialPortSettings.c_oflag &= ~OPOST;/*No Output Processing*/
/* Setting Time outs */
SerialPortSettings.c_cc[VMIN] = 10; /* Read at least 10 characters */
SerialPortSettings.c_cc[VTIME] = 0; /* Wait indefinetly */
if((tcsetattr(fd,TCSANOW,&SerialPortSettings)) != 0) /* Set the attributes to the termios structure*/
printf("\n ERROR ! in Setting attributes");
else
printf("\n BaudRate = 115200 StopBits = 1 Parity = none\n");
/*------------------------------- Read data from serial port -----------------------------*/
tcflush(fd, TCIFLUSH); /* Discards old data in the rx buffer */
return fd;
}