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

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