c - 在 Linux 中通过串口通信发送十六进制数据

标签 c linux usb hex

我的任务是将十六进制数据发送到 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/

相关文章:

linux - 如何在头尾操作的文件中使用管道?

linux - 是否有用于访问 EWMH/NetWM 函数的库和 header ?

c# - 如何通过C#检测USB Wifi插入计算机?

c++ - 如何将python dict发送到C++

在C中创建bmp文件

c - 重用缓冲区指针_before_ free

c++ - 为什么 CUDA 固定内存这么快?

php - 我需要在我的服务器上运行我作为任务编写的 PHP 脚本

linux - 关闭 USB 端口的电源

windows - 以编程方式启用 Powershell 是否可以接受?