I'm writing a piece of code in Java using jSSC for serial communication, but I don't know what I'm doing wrong. Basically I have to send a 32k file to an Arduino Uno and the Arduino has to process the data and send all bytes to an external device.
I also have this coded in C (not my code), and it works perfectly.
This is the Java code:
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);
}
}
}
And this is the working C code:
// 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);
}
I also tried to add delays / decreasing the baud rate and set the flow control of the serial port first to NONE then to FLOWCONTROL_XONXOFF_IN | FLOWCONTROL_XONXOFF_OUT but nothing changed.
Here you can see the difference between the Java wrong output and the C right output. You can open these files with just a Notepad.
This is the Arduino code that controls the bytes sent by the Java/C code:
// 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;
}
}