我的C++代码有问题:
我正在尝试连接到设备,向其写入十六进制数字并接收十六进制响应。我尝试了各种用于写入数据和读取的 C++ 代码,我根本没有任何反应。设备可以正常打开,但是我不能读写。
但是,如果我在 termainl 上运行命令,我可以从设备读取并将其保存到文件中。任何人都可以帮助它。我也确实注意到我必须回显两次才能阅读回复。我使用的命令:
stty -F /dev/ttymxc3 -echo -onlcr 9600
cat /dev/ttymxc3 >rear.bin&
echo -ne '\xfa\x03\xaa' > /dev/ttymxc3
echo -ne '\xfa\x03\xaa' > /dev/ttymxc3
我用的测试代码
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <strings.h>
#include <time.h>
#define BAUDRATE B9600
#define DEVICE "/dev/ttymxc3"
#define HEX_DATA_LEN 3
#define HEX_DATA_SEND "\xfa\x03\xaa"
#define READ_INTERVAL_SEC 5
#define READ_COUNT 20
int main()
{
int fd;
struct termios oldtio, newtio;
unsigned char buf[256];
printf("Opening device %s\n", DEVICE);
fd = open(DEVICE, O_RDWR | O_NOCTTY);
if (fd < 0) {
perror(DEVICE);
return -1;
}
printf("Setting terminal attributes...\n");
tcgetattr(fd, &oldtio);
bzero(&newtio, sizeof(newtio));
newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 1;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &newtio);
printf("Sending hex data...\n");
write(fd, HEX_DATA_SEND, HEX_DATA_LEN);
sleep(1);
printf("Reading response...\n");
int n = read(fd, buf, sizeof(buf));
if (n > 0) {
printf("Received response: ");
for (int i = 0; i < n; i++) {
printf("0x%02x ", buf[i]);
}
printf("\n");
}
printf("Reading from device every %d seconds for %d times...\n", READ_INTERVAL_SEC, READ_COUNT);
for (int i = 0; i < READ_COUNT; i++) {
sleep(READ_INTERVAL_SEC);
n = read(fd, buf, sizeof(buf));
if (n > 0) {
printf("Received data: ");
for (int j = 0; j < n; j++) {
printf("0x%02x ", buf[j]);
}
printf("\n");
}
}
printf("Closing device...\n");
tcsetattr(fd, TCSANOW, &oldtio);
close(fd);
return 0;
}
我正在尝试连接到设备,向其写入十六进制数字并接收十六进制响应。我尝试了各种用于写入数据和读取的 C++ 代码,我根本没有任何反应。设备可以正常打开,但是我不能读写。
但是,如果我在 termainl 上运行命令,我可以从设备读取并将其保存到文件中。任何人都可以帮助它。我也确实注意到我必须回显两次才能阅读回复。我使用的命令: