使用最少代码行的系统设置将原始字节写入串行(Linux C)

时间:2018-03-27 02:53:16

标签: c string serial-port hex byte

我正在试图找出一种在C语言中创建自己程序的方法(可能的代码行数最少),这需要4个参数为十六进制数。然后将这些数字转换为其原始字符串等效值,然后通过串行线路(无需等待串行输入)以系统确定的波特率(通过stty命令)向下发送。

因此,沿串行线发送的整个输出如下:

来源(在本例中,123的字符代码)    目的地(在本例中,为46的字符代码)    参数1    参数2    参数3    参数4    校验和(在本例中为79的字符代码)

因此,如果我将以下内容指定为命令行参数:

31 41 32 42

然后第3到第6个字节的数据应成为:

1 A 2 B

虽然这段代码不是100%完成的,但有一种更简单的方法可以在命令行中以字符串格式获取一组原始十六进制值,并将它们全部转换为一个4字节的字符串,我可以将其附加到7字节数据包,我可以一次性发送到串口?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

//including this file causes "too few arguments to function "write"" error
#include <unistd.h>

int main(int argc,char* argv[]){
  if (argc < 5){
      printf("4 hex values needed\n");
      return -1;
  }
  int fd=open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_SYNC);
  if (fd < 0){
      printf("Can't open port\n");
      return -1;
  }
  unsigned char src,dest,byte1,byte2,byte3,byte4,checksum;
  src=(unsigned char)123;
  dest=(unsigned char)46;
  byte1=(unsigned char)strtoll(argv[1],NULL,16);
  byte2=(unsigned char)strtoll(argv[2],NULL,16);
  byte3=(unsigned char)strtoll(argv[3],NULL,16);
  byte4=(unsigned char)strtoll(argv[4],NULL,16);
  checksum=(unsigned char)79;
  write(fd,src);
  write(fd,dest);
  write(fd,byte1);
  write(fd,byte2);
  write(fd,byte3);
  write(fd,byte4);
  write(fd,checksum);
  close(fd);
  return 0;
}

1 个答案:

答案 0 :(得分:2)

您可以声明保存消息的buffer,并使用初始化程序初始化源,目标和校验和字节。然后,您可以使用for循环来转换参数。最后,write需要一个长度。 因此,openclose之间的代码可以像这样实现:

unsigned char buffer[] = { 123, 46, 0, 0, 0, 0, 79 };
for (int i = 1; i < 5; i++)
    buffer[i+1] = strtol(argv[i], NULL, 16);
write(fd, buffer, sizeof(buffer));