我的任务是将十六进制数据发送到 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);
也就是说,它将count
个字节从buf
发送到fd
。在您的情况下,数据始终是字符串“AZTR\r”,加上之后未定义的数据(如果计数 > 5)。您的程序既不发送十六进制数据也不发送十进制数据。
你想发送二进制数据还是一串十六进制字符?
对于选项一,您可以使用:write(fd, somebuffer, len);
,其中 some buffer 是指向任何字节集(包括 int 等)的指针。
对于选项二,首先使用 sprintf
将您的数据转换为十六进制字符串,格式字符串为 %02X
,然后继续写入
将该数据发送到端口。
关于c - 在 Linux 中通过串口通信发送十六进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6555541/