2

我正在使用 jSSC 用 Ja​​va 编写一段代码进行串行通信,但我不知道我做错了什么。基本上我必须向 Arduino Uno 发送一个 32k 文件,而 Arduino 必须处理数据并将所有字节发送到外部设备。

我也有这个用 C 编码的(不是我的代码),它工作得很好。

这是Java代码:

private void writeBytes() {
  if(!fileSAV.exists()) {
    System.out.println("Could not find GAME.sav file!\nMake sure you have the GAME.sav file in the same folder "
      + "of this program.");
  } else {
    BufferedReader bufferedReaderRAM = null;
    char[] writingBuffer = new char[100];
    int totalByte = 0;
    try {
      bufferedReaderRAM = new BufferedReader(new FileReader(fileSAV));
    } catch (FileNotFoundException e) {
      System.out.println("Could not create bufferedReaderRAM!\n" + e);
    }
    try {
      while(bufferedReaderRAM.read(writingBuffer, 0, 64) > -1) {
        String stringRAM = new String(writingBuffer, 0, 64);
        try {
          connection.getSerialPort().writeBytes(stringRAM.getBytes());
        } catch (SerialPortException e) {
          System.out.println("Could not write GAME.sav file!\n" + e);
        }
        totalByte += 64;
        if(totalByte > 1024 * (kByte + 1) && totalByte < 1024 * (kByte + 2)) {
          kByte++;
          System.out.print(kByte + "K" + " ");
        }
      }
      bufferedReaderRAM.close();
    } catch (IOException e) {
      System.out.println("Could not write GAME.sav file!\n" + e);
    }
  }
}

这是有效的 C 代码:

// Read from file to serial - used writing to RAM
void read_from_file(char* filename) {
  // Load a new file
  FILE *pFile = fopen(filename, "rb");
  // Wait a little bit until we start getting some data
  #ifdef _WIN32
    Sleep(500);
  #else
    usleep(500000); // Sleep for 500 milliseconds
  #endif
  int Kbytesread = 0;
  int uptoKbytes = 1;
  unsigned char readbuf[100];
  while(1) {
    if (!(fread((char *) readbuf, 1, 64, pFile))) {
      break;
    }
    readbuf[64] = 0;
    // Send 64 bytes at a time
    RS232_SendBuf(cport_nr, readbuf, 64);
    printf("#");
    Kbytesread += 64;
    if (Kbytesread / 1024 == uptoKbytes) {
      printf("%iK", (Kbytesread/1024));
      uptoKbytes++;
    }
    fflush(stdout);
    #ifdef _WIN32
      Sleep(5);
    #else
      usleep(5000); // Sleep for 200 milliseconds
    #endif
  }
  fclose(pFile);
}

我还尝试添加延迟/降低波特率,并首先将串行端口的流量控制设置为 NONE,然后设置为 FLOWCONTROL_XONXOFF_IN | FLOWCONTROL_XONXOFF_OUT 但没有任何改变。

在这里你可以看到Java错误输出和C正确输出的区别。您可以只用记事本打开这些文件。

这是控制 Java/C 代码发送的字节的 Arduino 代码:

// Switch RAM banks
for (uint8_t bank = 0; bank < ramBanks; bank++) {
  write_byte(0x4000, bank);
  // Write RAM
  for (uint16_t ramAddress = 0xA000; ramAddress <= ramEndAddress; ramAddress++) {
    // Wait for serial input
    while (Serial.available() <= 0);
    // Read input
    uint8_t readValue = (uint8_t) Serial.read();
    // Write to RAM
    mreqPin_low;
    write_byte(ramAddress, readValue);
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    mreqPin_high;
  }
}
4

0 回答 0