使用jSSC将数据写入Arduino Uno

时间:2017-09-22 21:02:01

标签: java c arduino jssc

我正在使用jSSC编写一段用Java进行串行通信的代码,但我不知道我做错了什么。基本上我必须向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;
  }
}

0 个答案:

没有答案