任何人都可以帮助我使用我用于从串行设备读取数据的代码,因为我收到了错误的数据,数据应该是常量,但每次执行程序时它都在变化。正确的输出是25 4f 00 16
。我收到的数据是8 4 8a 9
。
我注意到一个奇怪的事情是,在显示数据之前,如果我在其中没有任何内容运行while(1)循环,那么我会收到正确的数据。为什么会这样?为什么我没有得到正确的输出。?
所以我想知道:
1.为什么我在cutecom(串行终端)上收到正确的数据时收到错误的数据
为什么每次执行代码时数据都会发生变化。
为什么我必须在代码中使用while(1)才能获得正确的数据
请帮忙。
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <math.h>
#define portname "/dev/ttyUSB7"
int set_interface_attribs (int fd, int speed, int parity)
{
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (fd, &tty) != 0)
{
// error_message ("error %d from tcgetattr", errno);
printf("error opening the device");
return -1;
}
cfsetospeed (&tty, speed);
cfsetispeed (&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
// enable reading
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr (fd, TCSANOW, &tty) != 0)
{
// error_message ("error %d from tcsetattr", errno);
printf("error opening the device");
return -1;
}
return -1;
}
int set_blocking (int fd, int should_block)
{
struct termios tty;
memset (&tty, 0, sizeof tty);
if (tcgetattr (fd, &tty) != 0)
{
//error_message ("error %d from tggetattr", errno);
printf("error opening the device");
}
tty.c_cc[VMIN] = should_block ? 1 : 0;
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
if (tcsetattr (fd, TCSANOW, &tty) != 0)
// error_message ("error %d setting term attributes", errno);
printf("error opening the device");
return -1;
}
int main()
{
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
printf("error opening the device");
}
set_interface_attribs (fd, B9600, 0);
set_blocking (fd, 0);
unsigned char receivebuffer[4] ; //Storing the values in receivebuffer
read (fd, receivebuffer, sizeof receivebuffer); //reading the data
//while(1)
// {
// }
printf(" values are %x %x %x %x \n\n",receivebuffer[3],receivebuffer[2],receivebuffer[1],receivebuffer[0]) //printing the received data in hex format;
return 0;
}