pyb.CAN.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. .. currentmodule:: pyb
  2. .. _pyb.CAN:
  3. class CAN -- controller area network communication bus
  4. ======================================================
  5. CAN implements the standard CAN communications protocol. At
  6. the physical level it consists of 2 lines: RX and TX. Note that
  7. to connect the pyboard to a CAN bus you must use a CAN transceiver
  8. to convert the CAN logic signals from the pyboard to the correct
  9. voltage levels on the bus.
  10. Example usage (works without anything connected)::
  11. from pyb import CAN
  12. can = CAN(1, CAN.LOOPBACK)
  13. can.setfilter(0, CAN.LIST16, 0, (123, 124, 125, 126)) # set a filter to receive messages with id=123, 124, 125 and 126
  14. can.send('message!', 123) # send a message with id 123
  15. can.recv(0) # receive message on FIFO 0
  16. Constructors
  17. ------------
  18. .. class:: pyb.CAN(bus, ...)
  19. Construct a CAN object on the given bus. *bus* can be 1-2, or ``'YA'`` or ``'YB'``.
  20. With no additional parameters, the CAN object is created but not
  21. initialised (it has the settings from the last initialisation of
  22. the bus, if any). If extra arguments are given, the bus is initialised.
  23. See :meth:`CAN.init` for parameters of initialisation.
  24. The physical pins of the CAN busses are:
  25. - ``CAN(1)`` is on ``YA``: ``(RX, TX) = (Y3, Y4) = (PB8, PB9)``
  26. - ``CAN(2)`` is on ``YB``: ``(RX, TX) = (Y5, Y6) = (PB12, PB13)``
  27. Class Methods
  28. -------------
  29. .. classmethod:: CAN.initfilterbanks(nr)
  30. Reset and disable all filter banks and assign how many banks should be available for CAN(1).
  31. STM32F405 has 28 filter banks that are shared between the two available CAN bus controllers.
  32. This function configures how many filter banks should be assigned to each. *nr* is the number of banks
  33. that will be assigned to CAN(1), the rest of the 28 are assigned to CAN(2).
  34. At boot, 14 banks are assigned to each controller.
  35. Methods
  36. -------
  37. .. method:: CAN.init(mode, extframe=False, prescaler=100, \*, sjw=1, bs1=6, bs2=8, auto_restart=False)
  38. Initialise the CAN bus with the given parameters:
  39. - *mode* is one of: NORMAL, LOOPBACK, SILENT, SILENT_LOOPBACK
  40. - if *extframe* is True then the bus uses extended identifiers in the frames
  41. (29 bits); otherwise it uses standard 11 bit identifiers
  42. - *prescaler* is used to set the duration of 1 time quanta; the time quanta
  43. will be the input clock (PCLK1, see :meth:`pyb.freq()`) divided by the prescaler
  44. - *sjw* is the resynchronisation jump width in units of the time quanta;
  45. it can be 1, 2, 3, 4
  46. - *bs1* defines the location of the sample point in units of the time quanta;
  47. it can be between 1 and 1024 inclusive
  48. - *bs2* defines the location of the transmit point in units of the time quanta;
  49. it can be between 1 and 16 inclusive
  50. - *auto_restart* sets whether the controller will automatically try and restart
  51. communications after entering the bus-off state; if this is disabled then
  52. :meth:`~CAN.restart()` can be used to leave the bus-off state
  53. The time quanta tq is the basic unit of time for the CAN bus. tq is the CAN
  54. prescaler value divided by PCLK1 (the frequency of internal peripheral bus 1);
  55. see :meth:`pyb.freq()` to determine PCLK1.
  56. A single bit is made up of the synchronisation segment, which is always 1 tq.
  57. Then follows bit segment 1, then bit segment 2. The sample point is after bit
  58. segment 1 finishes. The transmit point is after bit segment 2 finishes.
  59. The baud rate will be 1/bittime, where the bittime is 1 + BS1 + BS2 multiplied
  60. by the time quanta tq.
  61. For example, with PCLK1=42MHz, prescaler=100, sjw=1, bs1=6, bs2=8, the value of
  62. tq is 2.38 microseconds. The bittime is 35.7 microseconds, and the baudrate
  63. is 28kHz.
  64. See page 680 of the STM32F405 datasheet for more details.
  65. .. method:: CAN.deinit()
  66. Turn off the CAN bus.
  67. .. method:: CAN.restart()
  68. Force a software restart of the CAN controller without resetting its
  69. configuration.
  70. If the controller enters the bus-off state then it will no longer participate
  71. in bus activity. If the controller is not configured to automatically restart
  72. (see :meth:`~CAN.init()`) then this method can be used to trigger a restart,
  73. and the controller will follow the CAN protocol to leave the bus-off state and
  74. go into the error active state.
  75. .. method:: CAN.state()
  76. Return the state of the controller. The return value can be one of:
  77. - ``CAN.STOPPED`` -- the controller is completely off and reset;
  78. - ``CAN.ERROR_ACTIVE`` -- the controller is on and in the Error Active state
  79. (both TEC and REC are less than 96);
  80. - ``CAN.ERROR_WARNING`` -- the controller is on and in the Error Warning state
  81. (at least one of TEC or REC is 96 or greater);
  82. - ``CAN.ERROR_PASSIVE`` -- the controller is on and in the Error Passive state
  83. (at least one of TEC or REC is 128 or greater);
  84. - ``CAN.BUS_OFF`` -- the controller is on but not participating in bus activity
  85. (TEC overflowed beyond 255).
  86. .. method:: CAN.info([list])
  87. Get information about the controller's error states and TX and RX buffers.
  88. If *list* is provided then it should be a list object with at least 8 entries,
  89. which will be filled in with the information. Otherwise a new list will be
  90. created and filled in. In both cases the return value of the method is the
  91. populated list.
  92. The values in the list are:
  93. - TEC value
  94. - REC value
  95. - number of times the controller enterted the Error Warning state (wrapped
  96. around to 0 after 65535)
  97. - number of times the controller enterted the Error Passive state (wrapped
  98. around to 0 after 65535)
  99. - number of times the controller enterted the Bus Off state (wrapped
  100. around to 0 after 65535)
  101. - number of pending TX messages
  102. - number of pending RX messages on fifo 0
  103. - number of pending RX messages on fifo 1
  104. .. method:: CAN.setfilter(bank, mode, fifo, params, \*, rtr)
  105. Configure a filter bank:
  106. - *bank* is the filter bank that is to be configured.
  107. - *mode* is the mode the filter should operate in.
  108. - *fifo* is which fifo (0 or 1) a message should be stored in, if it is accepted by this filter.
  109. - *params* is an array of values the defines the filter. The contents of the array depends on the *mode* argument.
  110. +-----------+---------------------------------------------------------+
  111. |*mode* |contents of *params* array |
  112. +===========+=========================================================+
  113. |CAN.LIST16 |Four 16 bit ids that will be accepted |
  114. +-----------+---------------------------------------------------------+
  115. |CAN.LIST32 |Two 32 bit ids that will be accepted |
  116. +-----------+---------------------------------------------------------+
  117. |CAN.MASK16 |Two 16 bit id/mask pairs. E.g. (1, 3, 4, 4) |
  118. | | | The first pair, 1 and 3 will accept all ids |
  119. | | | that have bit 0 = 1 and bit 1 = 0. |
  120. | | | The second pair, 4 and 4, will accept all ids |
  121. | | | that have bit 2 = 1. |
  122. +-----------+---------------------------------------------------------+
  123. |CAN.MASK32 |As with CAN.MASK16 but with only one 32 bit id/mask pair.|
  124. +-----------+---------------------------------------------------------+
  125. - *rtr* is an array of booleans that states if a filter should accept a
  126. remote transmission request message. If this argument is not given
  127. then it defaults to ``False`` for all entries. The length of the array
  128. depends on the *mode* argument.
  129. +-----------+----------------------+
  130. |*mode* |length of *rtr* array |
  131. +===========+======================+
  132. |CAN.LIST16 |4 |
  133. +-----------+----------------------+
  134. |CAN.LIST32 |2 |
  135. +-----------+----------------------+
  136. |CAN.MASK16 |2 |
  137. +-----------+----------------------+
  138. |CAN.MASK32 |1 |
  139. +-----------+----------------------+
  140. .. method:: CAN.clearfilter(bank)
  141. Clear and disables a filter bank:
  142. - *bank* is the filter bank that is to be cleared.
  143. .. method:: CAN.any(fifo)
  144. Return ``True`` if any message waiting on the FIFO, else ``False``.
  145. .. method:: CAN.recv(fifo, list=None, \*, timeout=5000)
  146. Receive data on the bus:
  147. - *fifo* is an integer, which is the FIFO to receive on
  148. - *list* is an optional list object to be used as the return value
  149. - *timeout* is the timeout in milliseconds to wait for the receive.
  150. Return value: A tuple containing four values.
  151. - The id of the message.
  152. - A boolean that indicates if the message is an RTR message.
  153. - The FMI (Filter Match Index) value.
  154. - An array containing the data.
  155. If *list* is ``None`` then a new tuple will be allocated, as well as a new
  156. bytes object to contain the data (as the fourth element in the tuple).
  157. If *list* is not ``None`` then it should be a list object with a least four
  158. elements. The fourth element should be a memoryview object which is created
  159. from either a bytearray or an array of type 'B' or 'b', and this array must
  160. have enough room for at least 8 bytes. The list object will then be
  161. populated with the first three return values above, and the memoryview object
  162. will be resized inplace to the size of the data and filled in with that data.
  163. The same list and memoryview objects can be reused in subsequent calls to
  164. this method, providing a way of receiving data without using the heap.
  165. For example::
  166. buf = bytearray(8)
  167. lst = [0, 0, 0, memoryview(buf)]
  168. # No heap memory is allocated in the following call
  169. can.recv(0, lst)
  170. .. method:: CAN.send(data, id, \*, timeout=0, rtr=False)
  171. Send a message on the bus:
  172. - *data* is the data to send (an integer to send, or a buffer object).
  173. - *id* is the id of the message to be sent.
  174. - *timeout* is the timeout in milliseconds to wait for the send.
  175. - *rtr* is a boolean that specifies if the message shall be sent as
  176. a remote transmission request. If *rtr* is True then only the length
  177. of *data* is used to fill in the DLC slot of the frame; the actual
  178. bytes in *data* are unused.
  179. If timeout is 0 the message is placed in a buffer in one of three hardware
  180. buffers and the method returns immediately. If all three buffers are in use
  181. an exception is thrown. If timeout is not 0, the method waits until the
  182. message is transmitted. If the message can't be transmitted within the
  183. specified time an exception is thrown.
  184. Return value: ``None``.
  185. .. method:: CAN.rxcallback(fifo, fun)
  186. Register a function to be called when a message is accepted into a empty fifo:
  187. - *fifo* is the receiving fifo.
  188. - *fun* is the function to be called when the fifo becomes non empty.
  189. The callback function takes two arguments the first is the can object it self the second is
  190. a integer that indicates the reason for the callback.
  191. +--------+------------------------------------------------+
  192. | Reason | |
  193. +========+================================================+
  194. | 0 | A message has been accepted into a empty FIFO. |
  195. +--------+------------------------------------------------+
  196. | 1 | The FIFO is full |
  197. +--------+------------------------------------------------+
  198. | 2 | A message has been lost due to a full FIFO |
  199. +--------+------------------------------------------------+
  200. Example use of rxcallback::
  201. def cb0(bus, reason):
  202. print('cb0')
  203. if reason == 0:
  204. print('pending')
  205. if reason == 1:
  206. print('full')
  207. if reason == 2:
  208. print('overflow')
  209. can = CAN(1, CAN.LOOPBACK)
  210. can.rxcallback(0, cb0)
  211. Constants
  212. ---------
  213. .. data:: CAN.NORMAL
  214. CAN.LOOPBACK
  215. CAN.SILENT
  216. CAN.SILENT_LOOPBACK
  217. The mode of the CAN bus used in :meth:`~CAN.init()`.
  218. .. data:: CAN.STOPPED
  219. CAN.ERROR_ACTIVE
  220. CAN.ERROR_WARNING
  221. CAN.ERROR_PASSIVE
  222. CAN.BUS_OFF
  223. Possible states of the CAN controller returned from :meth:`~CAN.state()`.
  224. .. data:: CAN.LIST16
  225. CAN.MASK16
  226. CAN.LIST32
  227. CAN.MASK32
  228. The operation mode of a filter used in :meth:`~CAN.setfilter()`.