如何打开 Marlin 3d 打印机 SD 卡中的文件并将其内容读入 cha*?

问题描述 投票:0回答:0

我需要编写自定义函数以使用 cardreader.h 库(Anycubic Kobra max firmare)将其添加到 Marlin (2.x.x) 固件中,以便读取 gcode 文件并提取开头的注释(缩略图数据) .我的代码没有返回任何编译错误,我知道 SD 卡已安装,但在串行监视器中返回“打开文件时出错”。我现在文件存在,名称是正确的但由于某种原因我无法打开它并阅读它。

这里是代码:

#include "../../../../sd/cardreader.h"

char* readThumbnailComments(const char *filename) {
  if (!card.isMounted()) {
    SERIAL_ECHOLNPGM("Card not mounted!");
    return NULL;
  } else {
    SERIAL_ECHOLNPGM("Card mounted!");
  }

  char nonConstFilename[32];
  strncpy(nonConstFilename, filename, sizeof(nonConstFilename));
  nonConstFilename[sizeof(nonConstFilename) - 1] = '\0';

  card.openFileRead(nonConstFilename);

  char *result = (char*) malloc(492 * sizeof(char));
  size_t result_size = 492;
  result[0] = '\0';

  if (card.isFileOpen()) {
    char buffer[492];
    size_t index = 0;
    bool capture_comments = false;

    while (card.read(&buffer[index], 1) == 1) { // Read one character at a time
      if (buffer[index] == '\n' || buffer[index] == '\r') {
        buffer[index] = '\0'; // Null-terminate the string

        if (capture_comments) {
          if (strncmp(buffer, "; thumbnail end", 15) == 0) {
            break; // Stop capturing comments
          } else {
            if (index > 2) {
              strncat(result, buffer + 2, result_size - strlen(result) - 1); // Copy without the "; "
              strncat(result, "\n", result_size - strlen(result) - 1); // Add a newline character
            }
          }
        } else {
          if (strncmp(buffer, "; thumbnail begin", 17) == 0) {
            capture_comments = true; // Start capturing comments
          }
        }
        index = 0; // Reset the index
      } else {
        index = (index < sizeof(buffer) - 1) ? index + 1 : index;
      }
    }

    card.closefile(false); // Close the file
  } else {
    SERIAL_ECHOLNPGM("Error opening file");
    free(result);
    return NULL;
  }

  return result;
}

从 UI 菜单 cpp 文件我使用以下命令:

 card.mount(); // Initialize the SD card
 char *thumbnail_comments = readThumbnailComments(filenavigator.filelist.longFilename());

现在,如果我打印出 thumbnail_comments,它会显示为空,并在控制台“打开文件时出错”中提到谎言

有什么建议吗?

file firmware g-code
© www.soinside.com 2019 - 2024. All rights reserved.