Sunday, August 23, 2015

How to get the Mindstorms Ev3 brick to read coordinates from a file

In order to plot drawings I needed to read coordinates from a file, while running a program on the Ev3 brick. It turns out to be a very tricky task that is not well documented. The limitations I did know were:

  • Ev3 can only read a whole line per file access
  • There are no text manipulation blocks that allow me to split lines by commas
  • There is no way to detect the end of a file
  • I will have to put x coordinates and y coordinates in separate files

What is the file format used by the Ev3 for writing numbers?

I started by generating a file full of numbers from an Ev3 program so I could reverse engineer the file format. I made a simple program that divides 1 by 2 about 20 times.
Next I opened the file in vi to see what was in there:
A ha! This is very enlighting. My conclusions from this little test:
  • It seems that numbers have 4 decimal places
  • Numbers are separated by ascii 13
  • The file extension is .rtf
  • ...but the file format is txt. It has nothing to do with the Rich Text Files. 
TextEdit on Mac will not open the file. Only vi or sublime text are working for me. On to the next phase.

How to generate number files that the Ev3 can read

Now it's just a matter of writing my list of coordinates to file. In Python that looks like this:
xfile = open('x.rtf', 'w')
yfile = open('y.rtf', 'w')

for x,y in pointlist:
    #write each number on a new line
    xfile.write("{:.4f}".format(x)+chr(13))
    yfile.write("{:.4f}".format(y)+chr(13))

xfile.close()
yfile.close()


Test if the Ev3 can read the numbers

Finally I wrote a litte program that reads from the file, performs some math and plots the result to the screen. And behold, when I compare to the original text file, it works!