3我有一个小的 C 程序,用于通过串行端口读取和写入十六进制数据。在阅读时我没有问题,但是当我尝试这样编写十六进制数据时:
static const unsigned char cmdActuatorOn[] = "\x41\x54\x2B\x18\x12\x00\x12\x4B"
我看到写入函数仅通过串行端口发送 5 个字节……所以我想它出于任何原因将十六进制数据剪切为“0x00”字符。在我的串口设置下面:
int init_port(char const *const device)
{
int descriptor, result;
struct termios settings;
descriptor = open(device, O_RDWR | O_NOCTTY);
result = fcntl(descriptor, F_SETFL, O_NONBLOCK);
result = tcgetattr(descriptor, &settings);
settings.c_cflag &= ~PARENB;
settings.c_cflag &= ~CSTOPB;
settings.c_cflag &= ~CSIZE;
settings.c_cflag |= CS8;
settings.c_iflag |= IGNPAR;
settings.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY | INPCK);// raw data input mode
settings.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);// raw data output
settings.c_oflag &= ~OPOST;// setting timeouts
settings.c_cc[VMIN] = 1; // minimum number of chars to read in noncanonical (raw mode)
settings.c_cc[VTIME] = 5; // time in deciseconds to wait for data in noncanonical mode (raw mode)
cfsetispeed(&settings, B9600);
cfsetospeed(&settings, B9600);
result = tcsetattr(descriptor, TCSANOW, &settings);
return descriptor;
}
写入数据的函数是:
int write_port(void const *const data, size_t const size)
{
unsigned char const *p = (unsigned char const *)data;
unsigned char const *const q = (unsigned char const *)data + size;
ssize_t n;
while (p < q) {
do {
n = write(port_descriptor, p, (size_t)(q - p));
} while (n == (ssize_t)-1 && errno == EINTR);
if (n == (ssize_t)-1 && errno == EWOULDBLOCK) {
/* Sleep for a millisecond, then retry. */
usleep(1000);
continue;
}
if (n == (ssize_t)-1)
return errno;
else
if (n < (ssize_t)1)
return EIO;
p += (size_t)n;
}
if (p != q)
return EIO;
return 0;
}
我调用函数 write_data 如下:
result = write_port(cmdActuatorOn, strlen(cmdActuatorOn));
这适用于其他二进制数据:
static const unsigned char cmdGetCoordAddress[] = "\x40\x04\x2B\x02\x08\x52\x41\x9D";
static const unsigned char cmdReadCoordChannelAddress[] = "\x43\x12\x0B\x07\x08";
static const unsigned char cmdReadCoordPanId[] = "\xAF\x50\x2B\x07\x09\x52\x49\x90";
在这种情况下,写入函数将所有正确的字节写入串行端口。只有cmdActuatorOn没有,所以我认为 0x00 是问题所在。
我的错误在哪里?我的串口配置错误?我将其设置为与原始模式一起使用...不正确吗?
非常感谢