Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <termios.h>
- #define DEVICE "/dev/ttyUSB0" // serial device path
- #define BAUDRATE B115200 // baud rate
- #define DEVICE_ADDR 1 // device address
- #define FUNCTION_CODE 3 // function code
- #define START_ADDR_HI 0x01 // starting address (high byte)
- #define START_ADDR_LO 0x91 // starting address (low byte)
- #define DATA_LEN_HI 0x00 // number of registers to read (high byte)
- #define DATA_LEN_LO 0x01 // number of registers to read (low byte)
- // compute the CRC for the message
- unsigned short compute_crc(unsigned char *data, int len)
- {
- unsigned short crc = 0xFFFF;
- int i, j;
- for (i = 0; i < len; i++) {
- crc ^= data[i];
- for (j = 0; j < 8; j++) {
- if (crc & 0x0001) {
- crc >>= 1;
- crc ^= 0xA001;
- } else {
- crc >>= 1;
- }
- }
- }
- return crc;
- }
- int main()
- {
- int fd, bytes_sent, bytes_recv;
- struct termios options;
- unsigned char send_data[] = { DEVICE_ADDR, FUNCTION_CODE, START_ADDR_HI, START_ADDR_LO, DATA_LEN_HI, DATA_LEN_LO };
- unsigned short crc;
- unsigned char crc_hi, crc_lo;
- unsigned char recv_data[1024];
- // compute CRC for the message
- crc = compute_crc(send_data, sizeof(send_data));
- crc_hi = crc >> 8;
- crc_lo = crc & 0xFF;
- // append CRC to the message
- send_data[sizeof(send_data)] = crc_lo;
- send_data[sizeof(send_data) + 1] = crc_hi;
- // open serial device
- if ((fd = open(DEVICE, O_RDWR | O_NOCTTY)) == -1) {
- perror("open");
- exit(1);
- }
- // set serial port options
- tcgetattr(fd, &options);
- cfsetispeed(&options, BAUDRATE);
- cfsetospeed(&options, BAUDRATE);
- options.c_cflag |= (CLOCAL | CREAD);
- options.c_cflag &= ~PARENB;
- options.c_cflag &= ~CSTOPB;
- options.c_cflag &= ~CSIZE;
- options.c_cflag |= CS8;
- options.c_cc[VMIN] = 1;
- options.c_cc[VTIME] = 0;
- tcsetattr(fd, TCSANOW, &options);
- // send data
- if ((bytes_sent = write(fd, send_data, sizeof(send_data) + 2)) == -1) {
- perror("write");
- exit(1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement