Advertisement
edensheiko

c code rs_2323

Apr 9th, 2023
631
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6. #include <termios.h>
  7.  
  8. #define DEVICE "/dev/ttyUSB0" // serial device path
  9. #define BAUDRATE B115200 // baud rate
  10. #define DEVICE_ADDR 1 // device address
  11. #define FUNCTION_CODE 3 // function code
  12. #define START_ADDR_HI 0x01 // starting address (high byte)
  13. #define START_ADDR_LO 0x91 // starting address (low byte)
  14. #define DATA_LEN_HI 0x00 // number of registers to read (high byte)
  15. #define DATA_LEN_LO 0x01 // number of registers to read (low byte)
  16.  
  17. // compute the CRC for the message
  18. unsigned short compute_crc(unsigned char *data, int len)
  19. {
  20.     unsigned short crc = 0xFFFF;
  21.     int i, j;
  22.  
  23.     for (i = 0; i < len; i++) {
  24.         crc ^= data[i];
  25.         for (j = 0; j < 8; j++) {
  26.             if (crc & 0x0001) {
  27.                 crc >>= 1;
  28.                 crc ^= 0xA001;
  29.             } else {
  30.                 crc >>= 1;
  31.             }
  32.         }
  33.     }
  34.  
  35.     return crc;
  36. }
  37.  
  38. int main()
  39. {
  40.     int fd, bytes_sent, bytes_recv;
  41.     struct termios options;
  42.     unsigned char send_data[] = { DEVICE_ADDR, FUNCTION_CODE, START_ADDR_HI, START_ADDR_LO, DATA_LEN_HI, DATA_LEN_LO };
  43.     unsigned short crc;
  44.     unsigned char crc_hi, crc_lo;
  45.     unsigned char recv_data[1024];
  46.  
  47.     // compute CRC for the message
  48.     crc = compute_crc(send_data, sizeof(send_data));
  49.     crc_hi = crc >> 8;
  50.     crc_lo = crc & 0xFF;
  51.  
  52.     // append CRC to the message
  53.     send_data[sizeof(send_data)] = crc_lo;
  54.     send_data[sizeof(send_data) + 1] = crc_hi;
  55.  
  56.     // open serial device
  57.     if ((fd = open(DEVICE, O_RDWR | O_NOCTTY)) == -1) {
  58.         perror("open");
  59.         exit(1);
  60.     }
  61.  
  62.     // set serial port options
  63.     tcgetattr(fd, &options);
  64.     cfsetispeed(&options, BAUDRATE);
  65.     cfsetospeed(&options, BAUDRATE);
  66.     options.c_cflag |= (CLOCAL | CREAD);
  67.     options.c_cflag &= ~PARENB;
  68.     options.c_cflag &= ~CSTOPB;
  69.     options.c_cflag &= ~CSIZE;
  70.     options.c_cflag |= CS8;
  71.     options.c_cc[VMIN] = 1;
  72.     options.c_cc[VTIME] = 0;
  73.     tcsetattr(fd, TCSANOW, &options);
  74.  
  75.     // send data
  76.     if ((bytes_sent = write(fd, send_data, sizeof(send_data) + 2)) == -1) {
  77.         perror("write");
  78.         exit(1);
  79.     }
  80.  
  81.    
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement