[英]Sending Hexadecimal data through Serial Port Communication in Linux
我的任务是向 linux 中的 COMPORT 发送十六进制数据。 我写了这个简单的 C 代码,但它只发送一个十进制数。 谁能帮我发送一个十六进制位。
这是我写的代码
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
int number,n;
void main(void){
open_port();
}
int open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/ttyACM0 - ");
}
else{
printf("Port Opened successfully\n");
number = 1;
while(number!=55){
scanf("%d",&number);
n = write(fd, "ATZ\r", number);
if (n < 0)
fputs("write() of 4 bytes failed!\n", stderr);
}
}
return (fd);
}
请帮忙
提前致谢:):)
write
定义为:
ssize_t write(int fd, const void *buf, size_t count);
也就是说,它从buf
向fd
发送count
字节。 在您的情况下,数据始终是字符串“AZTR\r”,加上之后的未定义数据(如果计数> 5)。 您的程序既不发送十六进制数据,也不发送十进制数据。
您要发送二进制数据还是十六进制字符串?
对于选项一,您可以使用: write(fd, somebuffer, len);
,其中一些缓冲区是指向任何字节集(包括整数等)的指针。
对于选项二,首先使用sprintf
将您的数据转换为十六进制字符串,并将%02X
作为格式字符串,然后继续将该数据write
端口。
代码有几个问题:
"%d"
); 如果您希望将其解释为十六进制,请使用"%x"
。write()
是病态的。 第三个参数是要写入的字节数,而不是值。 它应该是
n = 写入 (fd, "ATZ\r", 4); // 有 4 个字节要写入初始化调制解调器
或者
char buf[10];
n = sprintf (buf, "%x", number); // convert to hex
n = write (fd, buf, n); // send hex number out port
这个 function 将采用十六进制字符串,并将其转换为二进制,这就是您要实际发送的内容。 十六进制表示是为了让人类能够理解正在发送的内容,但无论您与之通信的任何设备,都可能需要实际的二进制值。
// Converts a hex representation to binary using strtol()
unsigned char *unhex(char *src) {
unsigned char *out = malloc(strlen(src)/2);
char buf[3] = {0};
unsigned char *dst = out;
while (*src) {
buf[0] = src[0];
buf[1] = src[1];
*dst = strtol(buf, 0, 16);
dst++; src += 2;
}
return out;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.