code.py
 1  # SPDX-FileCopyrightText: 2020 Jeff Epler for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  import struct
 6  import time
 7  
 8  import board
 9  import canio
10  import digitalio
11  
12  # If the CAN transceiver has a standby pin, bring it out of standby mode
13  if hasattr(board, 'CAN_STANDBY'):
14      standby = digitalio.DigitalInOut(board.CAN_STANDBY)
15      standby.switch_to_output(False)
16  
17  # If the CAN transceiver is powered by a boost converter, turn on its supply
18  if hasattr(board, 'BOOST_ENABLE'):
19      boost_enable = digitalio.DigitalInOut(board.BOOST_ENABLE)
20      boost_enable.switch_to_output(True)
21  
22  # Use this line if your board has dedicated CAN pins. (Feather M4 CAN and Feather STM32F405)
23  can = canio.CAN(rx=board.CAN_RX, tx=board.CAN_TX, baudrate=250_000, auto_restart=True)
24  # On ESP32S2 most pins can be used for CAN.  Uncomment the following line to use IO5 and IO6
25  #can = canio.CAN(rx=board.IO6, tx=board.IO5, baudrate=250_000, auto_restart=True)
26  
27  old_bus_state = None
28  count = 0
29  
30  while True:
31      bus_state = can.state
32      if bus_state != old_bus_state:
33          print(f"Bus state changed to {bus_state}")
34          old_bus_state = bus_state
35  
36      now_ms = (time.monotonic_ns() // 1_000_000) & 0xffffffff
37      print(f"Sending message: count={count} now_ms={now_ms}")
38  
39      message = canio.Message(id=0x408, data=struct.pack("<II", count, now_ms))
40      can.send(message)
41  
42      time.sleep(.5)
43      count += 1