#include #include #include #include #include #include #include #include #include int set_uart(int fd,int speed,int bits,char check,int stop) { struct termios newtio,oldio; if(tcgetattr(fd,&oldio)!=0) { printf("tcgetattr oldio error\n"); return -1; } bzero(&newtio,sizeof(newtio)); newtio.c_cflag |= CLOCAL | CREAD ; newtio.c_cflag &= ~CSIZE; switch(bits) { case 7: newtio.c_cflag |= CS7; break; case 8: newtio.c_cflag |=CS8; break; } switch(check) { case 'O': newtio.c_cflag |= PARENB; newtio.c_cflag |= PARODD; newtio.c_iflag |= (INPCK|ISTRIP); break; case 'E': newtio.c_cflag |= PARENB; newtio.c_cflag |=~PARODD; newtio.c_iflag |= (INPCK|ISTRIP); break; case 'N': newtio.c_cflag &= ~PARENB; break; } switch(speed) { case 9600: cfsetispeed(&newtio,B9600); cfsetospeed(&newtio,B9600); break; case 115200: cfsetispeed(&newtio,B115200); cfsetospeed(&newtio,B115200); break; } switch(stop) { case 1: newtio.c_cflag &= ~CSTOPB; break; case 2: newtio.c_cflag |=CSTOPB; break; } tcflush(fd,TCIFLUSH); if(tcsetattr(fd,TCSANOW,&newtio)!=0) { printf("tcsetattr newtio error\n"); return -2; } return 0; } uint16_t CRC16_Modbus(uint8_t *data, uint8_t length) { uint16_t crc = 0xFFFF; // 初始化CRC寄存器 for (uint8_t i = 0; i < length; i++) { crc ^= data[i]; // 与当前字节异或 for (uint8_t j = 0; j < 8; j++) { // 处理每一位 if (crc & 0x0001) { crc = (crc >> 1) ^ 0xA001; // 异或多项式 } else { crc >>= 1; } } } // 高低字节交换 return (crc >> 8) | (crc << 8); } int main(int argc,char *argv[]) { int fd; unsigned char buf[128]; int count; fd= open("/dev/ttyS7",O_RDWR |O_NOCTTY | O_NDELAY); if(fd < 0) { printf("open ttyS7 error\n"); return -1; } /* fd= open("/dev/ttyS9",O_RDWR |O_NOCTTY | O_NDELAY); if(fd < 0) { printf("open ttyS9 error\n"); return -1; } */ set_uart(fd,9600,8,'N',1); // 定义要发送的十六进制数据:01 03 02 01 00 01 D4 72 unsigned char send_data[] = {0x01, 0x03, 0x02, 0x01, 0x00, 0x01, 0xD4, 0x72}; uint16_t crc_data= CRC16_Modbus(send_data, 6); printf("读取到 %X 字节响应数据:\n", crc_data); int send_len = sizeof(send_data); // 获取数据长度(8字节) // 发送数据 ssize_t write_ret = write(fd, send_data, send_len); if (write_ret < 0) { perror("write serial port error"); close(fd); return -1; } printf("成功发送 %zd 字节数据:", write_ret); for (int i = 0; i < send_len; i++) { printf("%02X ", send_data[i]); } printf("\n"); //write(fd,argv[1],strlen(argv[1])); sleep(1); count=read(fd,buf,sizeof(buf)); if (count < 0) { perror("read serial port error"); } else if (count == 0) { printf("未读取到响应数据\n"); } else { printf("读取到 %d 字节响应数据:", count); for (int i = 0; i < count; i++) { printf("%02X ", buf[i]); // 十六进制格式打印响应 } printf("\n"); } close(fd); return 0; }