Editing Arduino using Python

I’ve been experimenting with an Arduino Nano BLE recently. I wanted to take that program to the next level by creating an interface in Python. This interface would allow you to change variables in the Arduino sketch and run the sketch itself, all via Python.

The first step of this project, and the subject of this post, was learning to edit variables in the Arduino .ino file from inside python. The user running my Python script should be able to change variables inside the Arduino sketch without having to open it. This proved quite challenging. Python does not allow for reading a file, writing to a specific line and then closing that file without a bit of hackery1.

Here are the steps I took to achieve this:

  1. Open the file as read-only (meaning you cannot edit the file directly)
  2. Create a copy of the contents of that file(e.g. $fileData)
  3. Close the file

Next, edit what you want and save it to the file

  1. Edit the specific line(s) of $fileData needed
  2. Open the file again, this time in write mode
  3. Copy the contents of $fileData into the file
  4. Close the file

The code itself is relatively simple, I’ll outline it below:

with open('C:\\path\\to\\file\\Arduino.ino', 'r') as file:
  data = file.readlines()
(% endhighlight %)

These two lines encompass the first three steps. First, with open [...] as file opens the file you need in read-only mode, r. You can of course edit the path to file to whatever you want.

The second line of code reads the file and assigns every single line to a variable data. Using with open() means that as soon as the code underneath is executed the file is automatically closed.

data[5] = "int delay = 50"

This edits the 5th line in the data we saved and, in this case, inserts a variable.

with open('C:\\path\\to\\file\\Arduino.ino', 'w') as file:

The first line opens the file again, this time in write mode w.

This allows for the second line, where it writes the variable data back into the file with our changes included.

That’s all you need to edit any specific lines in a file. Any questions? Feel free to send me a message here.

  1. Note that this may not be the most efficient/only way of doing this. I’m only an amateur Python programmer. However, after an hour or two of research, this was the simplest solution I could find.