I am trying to read some data from an SD card and I can successfully open the file and read from it normally at first. I read it in 8 byte chunks but stop, once the file.available() evaluates to false. I counted up the bytes I read and it stops exactly after 8192 bytes even though the file is roughly 11 kilobytes. I have attached the relevant code below, thanks in advance!
The file.available() method should be called consistently in the loop to check the file state accurately. Your current code has file.available() outside of the main reading loop. You could adjust the code to keep file.available() as a condition for reading:
void stream_move_data() {
static long size = 0;
while (gcodeFile.available()) {
MoveData dat;
int bytesRead = gcodeFile.read(&dat, sizeof(MoveData));
if (bytesRead < sizeof(MoveData)) {
// If we didn't read a full MoveData struct, break the loop
break;
}
if (!dat.x || !dat.y) {
continue;
}
size += bytesRead;
Serial.println(size);
move_servos(dat.x, dat.y);
delay(2);
}
}
Thanks for the reply! I am using an Arduino Uno.
Here is the complete code
struct MoveData
{
float x;
float y;
};
void stream_move_data()
{
if (!gcodeFile.available()){
return;
}
MoveData dat;
gcodeFile.read(&dat, sizeof(MoveData));
// static MoveData prev_dat = ;
if(!dat.x || !dat.y){
return;
}
static long size = 0;
size += 8;// getting the size
Serial.println(size);
move_servos(dat.x, dat.y);
delay(2);
}
void loop(){
stream_move_data();
handle_button_presses(); // currently empty
};
void setup_file_stream()
{
if (!SD.begin(PIN_SPI_CS))
{
Serial.println("Failed to open SD card");
}
bmpFile = SD.open("/test/test.bmp", FILE_READ); // this one is opened just fine
gcodeFile = SD.open("/test/test.pjk", FILE_READ); // file is there but can't be opened
if (!bmpFile.available())
{
Serial.println("Failed to open the BMP image on the SD card");
}
if(!gcodeFile.available()){
Serial.println("Failed to open the GCODE file on the SD card");
}
Serial.flush();
}
That's still not full code as it does not compile due to missing variables and functions.
Please attach your gcode file; you might have to zip it to be able to upload if it's not a file with the extension txt.
I'm not familiar with gcode files; according to Guide: CNC File Formats - MEKANIKA gcode files are text files. In which case my question would be why you try to read the as binary by dumping it in a struct with two floats?
You've made yourself blind. Print an (error) message so you can see why you aborted stream_move_data().