LEGO EV3 – Saving an Array to a File

I was recently asked in a forum on how to save an array from the EV3 to a file.  Imagine you are taking data with a sensor, then storing the sequential measurements in an array, and you would like to analyze this data.  You could use the data logging feature, but let’s say you wanted to include this option in a program.  This came up for one of my WRO teams in 2015 where they were trying to scan the map legend as fast as possible.  The method that they used to develop an algorithm was to read the data as fast as possible, store it in an array, then save it as a file.  After that, they downloaded the data and developed filtering and sampling methods using Excel.  This allowed them to visually look at the data as they were developing the algorithm.  Later, they left the code in the program so that they could go back and look at the data if the robot failed to interpret the data correctly.  This gave them the option to determine what went wrong, and how to fix it.

Anyway, the EV3 does not deal with arrays particularly gracefully.  Further, it deals with exporting files with about as much grace.  The method that we used was simply:

  1. Issue a delete file command for the filename you intend to use.  If you don’t, the write data to a file simply appends, and it would be appending to an old file (if one exists by the same name).
  2. Read the length of the array.  Since our measurements were based on taking as many readings as possible, the length of the array varied from run to run, and if you attempt to access an array element longer than the array is, the EV3 crashes and does wonderful unpredictable things.
  3. Setup a loop to run for a specific number of iterations.  The number of iterations is the length of the array.
  4. Within the loop, perform the following steps:
    1. Read the array at the index value of the current loop iteration.
    2. Use the file access command to write the data to a file.  Note that the file names all through this need to be the same.  This appends the data to the end of the file.
    3. Iterate the loop for the number of times that equals the length of the array.
  5. After the loop completes, close the file.

An example in EV3-G is shown below.  This was copied from a MyBlock, so it assumes that the array of data named MeasuredData already exists, and is filled with data.

This entry was posted in Robotics and tagged , , . Bookmark the permalink.