gpt4 book ai didi

c - 从串行端口读取十六进制数据数组字节值

转载 作者:太空宇宙 更新时间:2023-11-04 12:23:44 25 4
gpt4 key购买 nike

我必须使用 C 程序从串口读取数据。我正在发送十六进制数组数据,设备将响应请求的相应响应。

我已经尝试使用 GTK+ 串行端口终端,例如,如果我写入数据“FC 05 40 2B 15”,设备将返回响应为“FC 05 50 AA 05”。

有人请指导我得到这个,我已经尝试了很长时间。

我在这里附上了我的代码。

void main()
{
int fd;
struct termios SerialPortSettings;
char write_buffer[512];
int dispense_card[5] = { 0XFC,0X05,0x40,0x2B,0x15 };
//char dispense[7] = {0x02,0x31,0x35,0x44,0x43,0x03,0x02};
int bytes_read = 0;
FILE* lfp;
time_t now;
time(&now);

//lfp = fopen("carddispense.log","a+");
fd = open("/dev/ttyUSB1",O_RDWR | O_NOCTTY);
if(fd == -1)
{
//fprintf(lfp,"\nError! in Opening ttyUSB0 %s", ctime(&now));
printf("\nError in Opening in ttyUSB0\n");
exit(1);
}
else
{ printf("\nttyUSB0 Opened Successfully\n");
//fprintf(lfp,"Card reader has been used %s", ctime(&now));

tcgetattr(fd, &SerialPortSettings); /* save current serial port settings */
cfsetispeed(&SerialPortSettings,B9600); /* Baud rate for read */
cfsetospeed(&SerialPortSettings,B9600);

SerialPortSettings.c_cflag &= PARENB; // No Parity
SerialPortSettings.c_cflag &= ~CSTOPB; //Stop bits = 1
SerialPortSettings.c_cflag &= ~CSIZE; /* Clears the Mask */
SerialPortSettings.c_cflag |= CS8; /* Set the data bits = 8 */

SerialPortSettings.c_cflag &= ~CRTSCTS; /*Turn off hardware based flow control */

SerialPortSettings.c_cflag |= CREAD | CLOCAL; /* Turn on the receiver of the serial port (CREAD) */

SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY); /*Turn off hardware based flow control */

SerialPortSettings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* NON Cannonical mode for serial communication */

SerialPortSettings.c_cc[VMIN] = 100; /* Read 128 characters */
SerialPortSettings.c_cc[VTIME] = 0; /* Wait indefinitely */

tcsetattr(fd,TCSANOW,&SerialPortSettings);
int pos =0,percent_count = 0;
int i;
for(i=0;i<5;i++)
{
printf("number = %x\t",dispense_card[i]);
sprintf(write_buffer+(i),"%c", dispense_card[i]);
}
printf("write_buffer%s\n",write_buffer);
//printf("write_buffer length: %d\n",strlen(write_buffer));

write(fd,write_buffer,strlen(write_buffer));
close(fd);
}
}

最佳答案

试试这个

char tx_buf[5];
char rx_buf[5];

sprintf(tx_buf, "%c%c%c%c%c",0XFC,0X05,0x40,0x2B,0x15);
write(fd, tx_buf, 5);

while (1) {
int n = read (fd, rx_buf, 5);
if (n > 0) {
for(int i=0; i<n; i++) {
printf("data i: %02X ", rx_buf[i]); // "FC 05 50 AA 05"
}
}
}
close(fd);

关于c - 从串行端口读取十六进制数据数组字节值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45298211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com