#include "hx_serial.h" #include #include #include #include #define BUFFER_SIZE 1024 #define OUTPUT_FILE "serial_data.txt" int main() { by_serial_t serial_port; char buffer[BUFFER_SIZE]; int bytes_read; int total_bytes_read = 0; FILE *output_file; // 初始化串口 if (by_serial_init(&serial_port, "/dev/ttyUSB1") != 0) { fprintf(stderr, "Failed to initialize serial port\n"); return -1; } by_serial_set_baudrate(&serial_port, 115200); by_serial_set_parity(&serial_port, 8, 1, 'N'); // 打开输出文件 output_file = fopen(OUTPUT_FILE, "wb"); if (output_file == NULL) { fprintf(stderr, "Failed to open output file\n"); close(serial_port.fd); return -1; } printf("Reading from serial port. Press ENTER to stop...\n"); // 循环读取串口数据 while (1) { // // 检查用户输入 // if (fgetc(stdin) == '\n') { // break; // } // 检查缓冲区中是否有数据 int used_len = by_serial_get_used_buffer_len(&serial_port); if (used_len <= 0) { usleep(100000); // 等待 100ms // printf("no data\n"); continue; }else{ printf("used_len = %d; ", used_len); } // 读取数据 bytes_read = by_serial_read(&serial_port, buffer, BUFFER_SIZE); if (bytes_read < 0) { fprintf(stderr, "Error reading from serial port\n"); break; } total_bytes_read += bytes_read; printf("Total bytes read: %d\n", total_bytes_read); // 将数据以 ASCII 格式写入文件 // fwrite(buffer, 1, bytes_read, output_file); for (int i = 0; i < bytes_read; i++) { fprintf(output_file, "%02X ", (unsigned char)buffer[i]); } fprintf(stderr, "Wrote %d bytes to file\n", bytes_read); } // 关闭文件和串口 fclose(output_file); close(serial_port.fd); printf("Data capture stopped. Data saved to %s\n", OUTPUT_FILE); return 0; }