Sending Hexadecimal data through Serial Port Communication in Linux

后端 未结 3 595
旧巷少年郎
旧巷少年郎 2021-01-03 09:11

I have got a task of sending hexadecimal data to my COMPORT in linux. I have written this simple C code, but it sends only a decimal number. Can anyone help me in sending an

相关标签:
3条回答
  • 2021-01-03 09:19

    There are several problems with the code:

    • The text read from the console is interpreted as decimal ("%d"); if you want it to be interpreted as hexadecimal, use "%x".
    • The write() is pathological. The third argument is the number of bytes to write, not the value. It should be either

      n = write (fd, "ATZ\r", 4); // there are 4 bytes to write to init the modem

    or

    char  buf[10];
    n = sprintf (buf, "%x", number);   // convert to hex
    n = write (fd, buf, n);            // send hex number out port
    
    0 讨论(0)
  • 2021-01-03 09:34

    This function will take a hex string, and convert it to binary, which is what you want to actually send. the hex representation is for humans to be able to understand what is being sent, but whatever device you are communicating with, will probably need the actual binary values.

    // 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;
    }
    
    0 讨论(0)
  • 2021-01-03 09:36

    write is defined as:

     ssize_t write(int fd, const void *buf, size_t count);
    

    That is, it sends count bytes to fd from buf. In your case, the data is always the string "AZTR\r", plus undefined data after that (if count is > 5). Your program sends neither hexadecimal nor decimal data.

    Do you want to send binary data or a string of hexadecimal characters?

    For option one, you can use: write(fd, somebuffer, len);, where some buffer is a pointer to any set of bytes (including ints, etc).

    For option two, first convert your data to a hexadecimal string using sprintf with %02X as the format string, then proceed to write that data to the port.

    0 讨论(0)
提交回复
热议问题