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 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 time
  16. import serial
  17. class LPC:
  18. """Interface for LPC in-system programming"""
  19. def __init__(self, serport, baudrate=115200, clock=12000, timeout=0.1):
  20. self._serport = serport
  21. self._baudrate = baudrate
  22. self._clock = clock
  23. self._timeout = timeout
  24. self._echo = True
  25. def open(self):
  26. """Open the serial port to communicate with the microcontroller"""
  27. self._uart = serial.Serial(self._serport, baudrate=self._baudrate,
  28. timeout=self._timeout)
  29. def _readline(self):
  30. """Read a line terminated with b'\r\n'"""
  31. s = b""
  32. while True:
  33. c = self._uart.read(1)
  34. if not c:
  35. # If we timed out, give up
  36. raise RecvTimeout(s)
  37. s += c
  38. if s.endswith(b"\r\n"):
  39. return s
  40. def _writeline(self, line, plain=False):
  41. """Write a line to the microcontroller and read the echoed response
  42. If plain is True, the command is taken to be raw binary data.
  43. """
  44. self._uart.write(line)
  45. self._uart.flush()
  46. # If echo is disabled, don't try to read back what we sent
  47. if not self.echo:
  48. return
  49. # Read the response, raising the exception if there is one
  50. if plain:
  51. response = self._uart.read(len(line))
  52. else:
  53. response = self._readline()
  54. # If we got the wrong response, raise an exception
  55. if response != line:
  56. raise ISPError("Wrong text echoed: {}".format(response))
  57. def _send_command_raw(self, cmd):
  58. """Send a command to the microcontroller, returning bytes"""
  59. self._writeline(cmd)
  60. return self._readline()
  61. def _send_command(self, cmd):
  62. """Send a command to the microcontroller, returning the result"""
  63. rr = self._send_command_raw(cmd)
  64. lr = [int(n) for n in rr.split()]
  65. lr[0] = ReturnCode(lr[0])
  66. if lr[0] != ReturnCode.CMD_SUCCESS:
  67. raise ISPError(lr)
  68. return lr
  69. def enter_isp(self, delay=0.01):
  70. """Enter ISP mode by controlling the DTR (/RST) and RTS (/ISP) lines
  71. This operation is performed synchronously, with delays.
  72. """
  73. self._uart.rts = True
  74. time.sleep(delay)
  75. self._uart.dtr = True
  76. time.sleep(delay)
  77. self._uart.dtr = False
  78. time.sleep(delay)
  79. self._uart.rts = False
  80. def synchronize(self, verbose=False):
  81. """Begin communication with the microcontroller"""
  82. # Synchronize with the MCU
  83. while True:
  84. # Send a ?
  85. self._uart.write(b"?")
  86. self._uart.flush()
  87. if verbose:
  88. print("?")
  89. # Receive a response
  90. try:
  91. s = self._readline()
  92. except RecvTimeout:
  93. continue
  94. # If we got the right response, break
  95. if s == b"Synchronized\r\n":
  96. break
  97. # Tell the MCU we've synchronized
  98. s = self._send_command_raw(b"Synchronized\r\n")
  99. # Next, it should say OK, at which point we're done synchronizing
  100. if s != b"OK\r\n":
  101. raise ISPError("Wrong response during synchronization")
  102. # Send clock frequency in kHz
  103. s = self._send_command_raw("{:d}\r\n".format(self._clock).encode(
  104. "utf-8"))
  105. # Next, it should say OK
  106. if s != b"OK\r\n":
  107. raise ISPError("Wrong response during synchronization")
  108. def close(self):
  109. """Close the serial port"""
  110. self._uart.close()
  111. def unlock(self, code="23130"):
  112. """Unlock the flash write, erase, and go commands"""
  113. self._send_command("U {}\r\n".format(code).encode("utf-8"))
  114. @property
  115. def baudrate(self):
  116. """The baud rate used for communication"""
  117. return self._uart.baudrate
  118. @baudrate.setter
  119. def baudrate(self, br):
  120. self._send_command("B {} {}\r\n".format(br,
  121. self._uart.stopbits).encode("utf-8"))
  122. # Update the baud rate for our UART
  123. self._uart.baudrate = br
  124. @property
  125. def stopbits(self):
  126. """The number of stop bits used for communication"""
  127. return self._uart.stopbits
  128. @stopbits.setter
  129. def stopbits(self, sb):
  130. self._send_command("B {} {}\r\n".format(self._uart.baudrate,
  131. sb).encode("utf-8"))
  132. # Update the number of stop bits for our UART
  133. self._uart.stopbits = sb
  134. @property
  135. def echo(self):
  136. """Whether the microcontroller echoes characters back to the host"""
  137. return self._echo
  138. @echo.setter
  139. def echo(self, setting):
  140. setting = bool(setting)
  141. self._send_command("A {}\r\n".format(int(setting)).encode("utf-8"))
  142. self._echo = setting
  143. def write_ram(self, start, data, count=None):
  144. """Write count bytes from data to RAM at the given start address
  145. Start and count must be multiples of four. If count is not specified,
  146. len(data) is used.
  147. """
  148. # Get the length of the data we're writing
  149. if count is None:
  150. count = len(data)
  151. # Ask to write data
  152. self._send_command("W {} {}\r\n".format(start, count).encode("utf-8"))
  153. # Send the data
  154. # NOTE: this is right for LPC8xx chips, not others
  155. self._writeline(data[:count], plain=True)
  156. return
  157. def read_memory(self, start, count):
  158. """Read count bytes starting at the given address
  159. Start and count must be multiples of four.
  160. """
  161. self._send_command("R {} {}\r\n".format(start, count).encode("utf-8"))
  162. return self._uart.read(count)
  163. def prepare_write(self, start, end=None):
  164. """Prepare the the given flash sector(s) for write operations
  165. If end is not specified, only the start sector is prepared.
  166. """
  167. if end is None:
  168. end = start
  169. self._send_command("P {} {}\r\n".format(start, end).encode("utf-8"))
  170. def copy_ram_to_flash(self, flash, ram, count):
  171. """Copy count bytes from RAM to flash
  172. The flash address should be a 64 byte boundary. Count should be a
  173. power of two in [64, 1024].
  174. """
  175. self._send_command("C {} {} {}\r\n".format(flash, ram, count).encode(
  176. "utf-8"))
  177. def go(self, address=0, mode=b"T"):
  178. """Jump to the given address, in the given mode of execution
  179. Of course, this function generally causes the ISP command handler to
  180. stop running, so it is typically appropriate to follow this with a call
  181. to LPC.close.
  182. """
  183. self._writeline("G {} {}\r\n".format(address, mode).encode("utf-8"))
  184. class ReturnCode(Enum):
  185. """LPC ISP return codes
  186. From UM10800, section 25.6.1.16.
  187. """
  188. CMD_SUCCESS = 0
  189. INVALID_COMMAND = 1
  190. SRC_ADDR_ERROR = 2
  191. DST_ADDR_ERROR = 3
  192. SRC_ADDR_NOT_MAPPED = 4
  193. DST_ADDR_NOT_MAPPED = 5
  194. COUNT_ERROR = 6
  195. INVALID_SECTOR = 7
  196. SECTOR_NOT_BLANK = 8
  197. SECTOR_NOT_PREPARED_FOR_WRITE_OPERATION = 9
  198. COMPARE_ERROR = 10
  199. BUSY = 11
  200. PARAM_ERROR = 12
  201. ADDR_ERROR = 13
  202. ADDR_NOT_MAPPED = 14
  203. CMD_LOCKED = 15
  204. INVALID_CODE = 16
  205. INVALID_BAUD_RATE = 17
  206. INVALID_STOP_BIT = 18
  207. CODE_READ_PROTECTION_ENABLED = 19
  208. class ISPError(IOError):
  209. """Generic error for ISP"""
  210. class RecvTimeout(ISPError):
  211. """Timeout while receiving a command"""