系统细节:Debian Jessie,gcc 4:4.9.2-2
我尝试使用以下代码对连接在串行端口上的仪器(自定义硬件,115200波特)进行长期测试:
while (1)
{
// Setup nonblocking IO (unused)
FD_SET(open_fds.serial.fd,&rset);
usleep(1000000);
// Write to instrument
printf("About to send this message:\n");
print_struct(i % 2 ? msg_test_be : msg_test_le, 12, 4);
printf("Transmitting message as %s endian. Attempt number: %d\n", i % 2 ? "big" : "little", i);
txlen = write(open_fds.serial.fd, i % 2 ? msg_test_be : msg_test_le, NUM_BITS_PER_CMD/CHAR_BIT);//
printf("%d bytes transmitted\n", txlen);
// Read from instrument
printf("Attempting to read from instrument. If this doesn't work, the serial connection may not be set up properly.\n");
printf("Press Ctrl+C to cancel.\n");
recvlen = read(open_fds.serial.fd, output, NUM_BYTES_PER_RESPONSE);
printf("%d bytes read.\n", recvlen);
printf("Response as hex:\n");
print_struct((unsigned char *)output, recvlen, 15);
i++;
}
以下是print_struct
的代码:
void print_struct(unsigned char *p, size_t length, int bytes_per_line)
{
int i = 0;
int modulus = bytes_per_line > MIN_BYTES_PER_LINE ? bytes_per_line : MIN_BYTES_PER_LINE;
//printf("modulus: %d\n", modulus);
for(i = 0; i < length; i++)
{
// Every "modulus" lines (excluding 0) print a newline.
if(i && !(i % modulus) && i + 1 <= length)
{
printf("\n");
}
printf("%02x ", p[i]);
}
// Throw in an extra newline to avoid colliding with other messages.
printf("\n");
return;
}
这适用于约700次迭代,然后它挂起。我觉得我有一些设置缺失可能导致它挂起,我想确保在部署仪器时不会发生这种情况。以下是我的串口设置:
int initSerial(int fd_tty, speed_t baud_rate, int vmin, int vtime)
{
struct termios options;
if(tcgetattr(fd_tty, &options) != 0)
{
//fprintf(fptr_log, "Error %d from tcgetattr in %s (%s)\n", errno, strerror(errno), __func__);
syslog(LOG_ERR, "Error %d from tcgetattr in %s (%s)\n", errno, strerror(errno), __func__);
return EXIT_FAILURE;
}
// Set the baud rates to whatever is needed... (Max 115200)
cfsetispeed(&options, baud_rate);
cfsetospeed(&options, baud_rate);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
options.c_cc[VMIN] = vmin;
options.c_cc[VTIME] = vtime;
options.c_cflag |= CREAD | CLOCAL;
cfmakeraw(&options);
// TODO: Add these functionalities back in.
// options.c_cc[VMIN] = vmin; // vmin input bytes are enough to return from read()
// options.c_cc[VTIME] = vtime; // Or wait 0.1*vtime s if nothing to read
// Set the new options for the port...
tcflush(fd_tty, TCIFLUSH);
if(tcsetattr(fd_tty, TCSANOW, &options) !=0)
{
//fprintf(fptr_log, "Error %d from tcsetattr: %s\n", errno, strerror(errno));
syslog(LOG_ERR, "Error %d from tcsetattr in %s (%s)\n", errno, strerror(errno), __func__);
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
我过去曾遇到过错误的串口设置问题,但是不知道在任何一个设置上都指责。有什么想法吗?