Skip to content

Instantly share code, notes, and snippets.

@Lokno
Created August 10, 2021 20:16
Show Gist options
  • Save Lokno/e1c7227211cc9ac46cf32ca38faa921c to your computer and use it in GitHub Desktop.
Save Lokno/e1c7227211cc9ac46cf32ca38faa921c to your computer and use it in GitHub Desktop.
Script that uses arduino-cli to discover a Arduino board attached to serial to compile and upload an Arduino sketch
# Script that uses arduino-cli to discover a Arduino board attached
# to serial to compile and upload an Arduino sketch
#!/usr/bin/env python3
from subprocess import check_output
import re
import sys
program_name = ''
if len(sys.argv) > 1:
program_name = sys.argv[1]
out = check_output(["arduino-cli","board","list"]).decode()
board_re = re.compile('(COM[0-9]+) Serial Port \(USB\) (.*) (arduino:[^:]+:[^ ]+|Unknown)')
boards = {p:(n,b) for p,n,b in board_re.findall(out)}
if len(boards) > 0:
ports = boards.keys()
port = list(ports)[0]
if len(boards) > 1:
port = input(f'Found multiple boards:\n{out:s}\nSelect the port of the desired board: ')
while port not in ports:
port = input(f'Not a valid port. Select the port of the desired board: ')
fqbn = boards[port][1]
if boards[port][0] == 'Unknown' or boards[port][0] == 'Unknown': # TODO: Not sure about output here
fqbn = input(f'Board on port {port:s} of unknown type. Please enter FQBN: ')
if program_name == '':
program_name = input('Please enter the name of the sketch: ')
compile_cmd = ["arduino-cli","compile","--fqbn",fqbn,program_name]
upload_cmd = ["arduino-cli","upload","-p",port,"--fqbn",fqbn,program_name]
print('\n' + ' '.join(compile_cmd))
print(check_output(["arduino-cli","compile","--fqbn",fqbn,program_name]).decode())
print(' '.join(upload_cmd))
print(check_output(["arduino-cli","upload","-p",port,"--fqbn",fqbn,program_name]).decode())
else:
print('No boards found. Did you forget to connect them? :3c')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment