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.

__init__.py 11KB

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