Skip to content

Instantly share code, notes, and snippets.

@slzatz
Created May 19, 2022 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slzatz/5ccf5ba5d7a0b098e7d953a3c83babb1 to your computer and use it in GitHub Desktop.
Save slzatz/5ccf5ba5d7a0b098e7d953a3c83babb1 to your computer and use it in GitHub Desktop.
transfer files to mcu
from time import sleep
import serial
import sys
from os.path import exists
def print_lines(lines):
for line in lines:
print(line.decode("utf-8", "ignore"))
def write(cmd):
for i in range(len(cmd)):
ser.write(cmd[i].encode("utf-8"))
#ser.write(cmd[i]) # doesn't work
x = ser.read()
print(x.decode("utf-8"), end='')
sleep(0.02)
def writefile(data):
#for i in range(len(data)):
i = 0
d = 64 # how many bytes sent each time
ln = len(data)
#ln = 100
while 1:
ser.write(data[i:i+d])
i += d
if i == ln:
x = ser.read_until()
y = ser.read_until()
print("-->", x+y, "<--")
break
if i + d > ln:
ser.write(data[i:ln])
sleep(0.1)
x = ser.read_until()
y = ser.read_until()
print("--->", x+y, "<---")
sleep(0.1)
x = ser.read_until()
y = ser.read_until()
print("--->", x+y, "<---")
break
sleep(0.1) #0.1
x = ser.read_until()
y = ser.read_until()
print("-->", x+y, "<--")
if len(sys.argv) == 1:
sys.exit("You need to supply a filename")
fname = sys.argv[1]
response = input(f"Do you want to transfer {fname} to the MCU? (y/N): ")
if response[0].lower() != 'y':
sys.exit("")
with open(fname, mode = 'rb') as f:
text = f.read()
if len(sys.argv) == 3:
dir = sys.argv[2]
else:
dir = ""
file_size = len(text)
if not exists(fname):
sys.exit("The file name you gave doesn't exist")
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate=115200, #115200
#parity=serial.PARITY_NONE,
#stopbits=serial.STOPBITS_ONE,
#bytesize=serial.EIGHTBITS
#timeout=3
)
ser.write_timeout = 0
ser.timeout = 3
if not ser.is_open:
sys.exit("Serial port is not open")
sleep(2)
write("mount\r\n")
lines = ser.readlines()
print_lines(lines)
sleep(1)
write(f"writefile2 {dir}/{fname} {file_size}\r\n")
sleep(5)
i = 0
while 1:
line = ser.readline()
print(f"{i}: {line}")
s = line[:-2].decode("utf-8")
if s == "error":
sys.exit("There was an error with writefile")
elif s == "ok":
break
i+=1
z = ser.read(2)
print(f"z = {z}")
sleep(.1)
writefile(text) #8192
sleep(0.5)
write("ls\r\n")
sleep(0.5)
lines = ser.readlines()
print_lines(lines)
print("done")
ser.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment