【发布时间】:2017-07-25 08:44:29
【问题描述】:
我必须使用 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);
}
}
【问题讨论】:
-
没有“十六进制数据”之类的东西(可能是字符串形式的除外)。十六进制是许多可能的数字文本表示之一。
0xFC是252是0374(和 CCLII)。 -
你忘了说是什么问题。
-
我无法使用我的程序获得准确的数据,例如“FC 05 50 AA 05”。但我能够在 GTK+ 串口终端工具中得到正确的响应
-
@molbdnilo 甚至更多 :) 二进制 11111100(2) 三进制 100100(3) 四进制 3330(4) 五进制 2002(5) Senary 1100(6) 八进制 374(8) 十二进制 190(12)十六进制 FC(16) Vigesimal CC(20) Base 36 70(36)
-
(1) 您的 termios 配置不会(但应该)清除
c_oflag成员中的 OPOST。 (2) 语句sprintf(write_buffer+(i),"%c", dispense_card[i])只复制一个字节;这是一种非常昂贵的复制方法。 (3)您似乎抱怨阅读问题,但尚未发布任何与阅读相关的代码。
标签: c linux serial-port usbserial