Hello to all,
I have function that initates serial communication with another MCU, then listens and should collect a 16kb file send from the other end and write it in memory. My problem is that the last 16 bytes are missing - one for each loop that I make, but not inbetween loops, but at the end. Here is my code:
void inbound_transfer() {
String filename = "/backup.bin";
if (SPIFFS.exists(filename)) {
SPIFFS.remove(filename);
}
File f = SPIFFS.open(filename, "w");
size_t fsize = f.size();
const byte numChars = 512;
String receivedConfirmation;
byte rc;
bool moredata = 1; //there are bytes in the file that need to be received
//prepare sender
Serial.print("snd");
delay(10);
while (moredata == 1) {
// READ ANSWER FROM REMOTE DEVICE
byte buff[1024];
int len = readByteFromSerial(buff, 1024);
if (len > 0) {
len = 0;
f.write(buff, 1023);
}
if (Serial.available() > 0) {
moredata = 1;
yield();
}
else moredata = 0;
}
f.close();
transferCommand = 0;
}
and the readByteFromSerial function :
int readByteFromSerial(byte *buffer, int max_len )
{
int pos = 0;
unsigned long int init_time = millis();
unsigned long int wait_time = init_time + 1000;
while (!Serial.available())
{
// Serial.println("enter waiting for serial");
if (millis() >= wait_time) {
// no responce - just leave
// Serial.println("time is up");
return pos;
}
}
while (pos < max_len - 1)
//for ( ; pos <= max_len - 1; pos++)
{
if (Serial.available() > 0) {
byte readch = Serial.read();
buffer[pos] = readch;
pos++;
}
}
return pos;
}