In-system programming tool for LPC microcontrollers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lpc.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. # Copyright 2017 Clayton G. Hobbs
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Interfaces for in-system programming of LPC microcontrollers"""
  15. import struct
  16. import time
  17. from enum import Enum
  18. import intelhex
  19. import serial
  20. from alpaca_isp.exceptions import *
  21. DEFAULT_BAUDRATE = 115200
  22. DEFAULT_CLOCK = 12000
  23. DEFAULT_TIMEOUT = 0.1
  24. class LPC:
  25. """Interface for LPC in-system programming"""
  26. def __init__(self, tty, baudrate=DEFAULT_BAUDRATE,
  27. clock=DEFAULT_CLOCK, timeout=DEFAULT_TIMEOUT):
  28. # If the first parameter is an LPC, initialize self from that
  29. if isinstance(tty, LPC):
  30. o = tty
  31. self._tty = o._tty
  32. self._baudrate = o._baudrate
  33. self._clock = o._clock
  34. self._timeout = o._timeout
  35. self._echo = o._echo
  36. try:
  37. self._uart = o._uart
  38. except AttributeError:
  39. # If there's no o._uart, that's not a problem
  40. pass
  41. # Otherwise, initialize from the parameters
  42. else:
  43. self._tty = tty
  44. self._baudrate = baudrate
  45. self._clock = clock
  46. self._timeout = timeout
  47. self._echo = True
  48. def open(self):
  49. """Open the serial port to communicate with the microcontroller"""
  50. self._uart = serial.Serial(self._tty, baudrate=self._baudrate,
  51. timeout=self._timeout)
  52. def _readline(self):
  53. """Read a line terminated with b'\r\n'"""
  54. s = b""
  55. while True:
  56. c = self._uart.read(1)
  57. if not c:
  58. # If we timed out, give up
  59. raise RecvTimeout(s)
  60. s += c
  61. if s.endswith(b"\r\n"):
  62. return s
  63. def _writeline(self, line, plain=False):
  64. """Write a line to the microcontroller and read the echoed response
  65. If plain is True, the command is taken to be raw binary data.
  66. """
  67. self._uart.write(line)
  68. self._uart.flush()
  69. # If echo is disabled, don't try to read back what we sent
  70. if not self.echo:
  71. return
  72. # Read the response, raising the exception if there is one
  73. if plain:
  74. response = self._uart.read(len(line))
  75. else:
  76. response = self._readline()
  77. # If we got the wrong response, raise an exception
  78. if response != line:
  79. raise ISPError("Wrong text echoed: {}".format(response))
  80. def _send_command_raw(self, cmd):
  81. """Send a command to the microcontroller, returning bytes"""
  82. self._writeline(cmd)
  83. return self._readline()
  84. def _send_command(self, cmd):
  85. """Send a command to the microcontroller, returning the result"""
  86. r = self._send_command_raw(cmd)
  87. r = ReturnCode(int(r))
  88. if r != ReturnCode.CMD_SUCCESS:
  89. raise ISPError(r)
  90. return r
  91. def enter_isp(self, delay=0.01):
  92. """Enter ISP mode by controlling the DTR (/RST) and RTS (/ISP) lines
  93. This operation is performed synchronously, with delays.
  94. """
  95. self._uart.rts = True
  96. time.sleep(delay)
  97. self._uart.dtr = True
  98. time.sleep(delay)
  99. self._uart.dtr = False
  100. time.sleep(delay)
  101. self._uart.rts = False
  102. def synchronize(self, verbose=False, max_tries=None):
  103. """Begin communication with the microcontroller
  104. If verbose is True, prints a . for every synchronization attempt.
  105. If max_tries is an integer, attempt to synchronize at most that many
  106. times before failing by raising RecvTimeout.
  107. """
  108. # Synchronize with the MCU
  109. while True:
  110. # Send a ?
  111. self._uart.write(b"?")
  112. self._uart.flush()
  113. if verbose:
  114. print(".", end="", flush=True)
  115. # Receive a response
  116. try:
  117. s = self._readline()
  118. except RecvTimeout:
  119. if max_tries is not None:
  120. max_tries -= 1
  121. if max_tries <= 0:
  122. raise
  123. continue
  124. # If we got the right response, break
  125. if s == b"Synchronized\r\n":
  126. break
  127. # Tell the MCU we've synchronized
  128. s = self._send_command_raw(b"Synchronized\r\n")
  129. # Next, it should say OK, at which point we're done synchronizing
  130. if s != b"OK\r\n":
  131. raise ISPError("Wrong response during synchronization")
  132. # Send clock frequency in kHz
  133. s = self._send_command_raw("{:d}\r\n".format(self._clock).encode(
  134. "utf-8"))
  135. # Next, it should say OK
  136. if s != b"OK\r\n":
  137. raise ISPError("Wrong response during synchronization")
  138. def close(self):
  139. """Close the serial port"""
  140. self._uart.close()
  141. def unlock(self, code="23130"):
  142. """Unlock the flash write, erase, and go commands"""
  143. self._send_command("U {}\r\n".format(code).encode("utf-8"))
  144. @property
  145. def baudrate(self):
  146. """The baud rate used for communication"""
  147. return self._uart.baudrate
  148. @baudrate.setter
  149. def baudrate(self, br):
  150. self._send_command("B {} {}\r\n".format(br,
  151. self._uart.stopbits).encode("utf-8"))
  152. # Update the baud rate for our UART
  153. self._uart.baudrate = br
  154. @property
  155. def stopbits(self):
  156. """The number of stop bits used for communication"""
  157. return self._uart.stopbits
  158. @stopbits.setter
  159. def stopbits(self, sb):
  160. self._send_command("B {} {}\r\n".format(self._uart.baudrate,
  161. sb).encode("utf-8"))
  162. # Update the number of stop bits for our UART
  163. self._uart.stopbits = sb
  164. @property
  165. def echo(self):
  166. """Whether the microcontroller echoes characters back to the host"""
  167. return self._echo
  168. @echo.setter
  169. def echo(self, setting):
  170. setting = bool(setting)
  171. self._send_command("A {}\r\n".format(int(setting)).encode("utf-8"))
  172. self._echo = setting
  173. def write_ram(self, start, data, count=None):
  174. """Write count bytes from data to RAM at the given start address
  175. Start and count must be multiples of four. If count is not specified,
  176. len(data) is used.
  177. """
  178. # Get the length of the data we're writing
  179. if count is None:
  180. count = len(data)
  181. # Ask to write data
  182. self._send_command("W {} {}\r\n".format(start, count).encode("utf-8"))
  183. # Send the data
  184. # NOTE: this is right for LPC8xx chips, not others
  185. self._writeline(data[:count], plain=True)
  186. return
  187. def read_memory(self, start, count):
  188. """Read count bytes starting at the given address
  189. Start and count must be multiples of four.
  190. """
  191. self._send_command("R {} {}\r\n".format(start, count).encode("utf-8"))
  192. return self._uart.read(count)
  193. def prepare_write(self, start=None, end=None):
  194. """Prepare the the given flash sector(s) for write operations
  195. If end is not specified, only the start sector is prepared.
  196. If neither start nor end is specified, prepares all flash sectors.
  197. """
  198. if start is None and end is None:
  199. start = 0
  200. end = len(self._chip.sectors) - 1
  201. elif end is None:
  202. end = start
  203. self._send_command("P {} {}\r\n".format(start, end).encode("utf-8"))
  204. def copy_ram_to_flash(self, flash, ram, count):
  205. """Copy count bytes from RAM to flash
  206. The flash address should be a 64 byte boundary. Count should be a
  207. power of two in [64, 1024].
  208. """
  209. self._send_command("C {} {} {}\r\n".format(flash, ram, count).encode(
  210. "utf-8"))
  211. def go(self, address=0, mode=b"T"):
  212. """Jump to the given address, in the given mode of execution
  213. Of course, this function generally causes the ISP command handler to
  214. stop running, so it is typically appropriate to follow this with a call
  215. to LPC.close.
  216. """
  217. self._writeline("G {} {}\r\n".format(address, mode).encode("utf-8"))
  218. def erase(self, start=None, end=None):
  219. """Erase the given flash sector(s)
  220. If end is not specified, only the start sector is erased.
  221. If neither start nor end is specified, erases all flash sectors.
  222. """
  223. if start is None and end is None:
  224. start = 0
  225. end = len(self._chip.sectors) - 1
  226. elif end is None:
  227. end = start
  228. self._send_command("E {} {}\r\n".format(start, end).encode("utf-8"))
  229. def blank_check(self, start, end=None):
  230. """Check if the given flash sectors are blank
  231. If end is not specified, only the start sector is checked.
  232. Returns None if the sector is blank, or a tuple containing the offset
  233. and value of the first non-blank word location if the sector is not
  234. blank. If CRP is enabled, the offset and value are always reported as
  235. zero.
  236. """
  237. if end is None:
  238. end = start
  239. try:
  240. self._send_command("I {} {}\r\n".format(start, end).encode(
  241. "utf-8"))
  242. except ISPError as e:
  243. # Return a tuple for SECTOR_NOT_BLANK
  244. if e.args[0] == ReturnCode.SECTOR_NOT_BLANK:
  245. offset = int(self._readline())
  246. value = int(self._readline())
  247. return (offset, value)
  248. raise
  249. @property
  250. def part_id(self):
  251. """The identification number for the part"""
  252. self._send_command(b"J\r\n")
  253. return int(self._readline())
  254. @property
  255. def boot_code_version(self):
  256. """The boot code version number (major, minor)"""
  257. self._send_command(b"K\r\n")
  258. major = int(self._readline())
  259. minor = int(self._readline())
  260. return (major, minor)
  261. def compare(self, addr1, addr2, count):
  262. """Compart count bytes starting from the two addresses
  263. Both addresses should be on word boundaries, and count should be a
  264. multiple of four.
  265. Returns None if the two blocks are equal, or the byte offset of the
  266. first mismatched word if they are not.
  267. """
  268. try:
  269. self._send_command("M {} {} {}\r\n".format(addr1, addr2,
  270. count).encode("utf-8"))
  271. except ISPError as e:
  272. # Return an offset for COMPARE_ERROR
  273. if e.args[0] == ReturnCode.COMPARE_ERROR:
  274. return int(self._readline())
  275. raise
  276. @property
  277. def uid(self):
  278. """The microcontroller's unique ID, as bytes"""
  279. self._send_command(b"N\r\n")
  280. words = []
  281. for _ in range(4):
  282. words.append(int(self._readline()))
  283. return struct.pack("<4I", *words)
  284. def read_crc32(self, start, count):
  285. """Compute the CRC checksum of a black of RAM or flash
  286. Start must be on a word boundary, and count must be a multiple of four.
  287. """
  288. self._send_command("S {} {}\r\n".format(start, count).encode("utf-8"))
  289. return int(self._readline())
  290. def flash_hex(self, ihex):
  291. """Write an IntelHex object to flash"""
  292. sectors_used = self._chip.sectors_used(ihex.segments())
  293. class LPC8xx(LPC):
  294. """Interface for LPC8xx in-system programming"""
  295. def __init__(self, lpc, chip):
  296. """Initialize an LPC8xx from an existing LPC object"""
  297. super().__init__(lpc)
  298. self._chip = chip
  299. class ReturnCode(Enum):
  300. """LPC ISP return codes
  301. From UM10800, section 25.6.1.16.
  302. """
  303. CMD_SUCCESS = 0
  304. INVALID_COMMAND = 1
  305. SRC_ADDR_ERROR = 2
  306. DST_ADDR_ERROR = 3
  307. SRC_ADDR_NOT_MAPPED = 4
  308. DST_ADDR_NOT_MAPPED = 5
  309. COUNT_ERROR = 6
  310. INVALID_SECTOR = 7
  311. SECTOR_NOT_BLANK = 8
  312. SECTOR_NOT_PREPARED_FOR_WRITE_OPERATION = 9
  313. COMPARE_ERROR = 10
  314. BUSY = 11
  315. PARAM_ERROR = 12
  316. ADDR_ERROR = 13
  317. ADDR_NOT_MAPPED = 14
  318. CMD_LOCKED = 15
  319. INVALID_CODE = 16
  320. INVALID_BAUD_RATE = 17
  321. INVALID_STOP_BIT = 18
  322. CODE_READ_PROTECTION_ENABLED = 19