例程讲解-02-can CAN通信

# CAN 扩展板示例
#
# 此示例演示了两个摄像机之间的CAN通信。
# 注意:您需要两个CAN收发器扩展板和DB9电缆才能运行此示例。

import time, omv
from pyb import CAN

# 注意:在接收节点上设置为False。
TRANSMITTER = True

can = CAN(2, CAN.NORMAL)
# 设置不同的波特率(默认为125Kbps)
# 注意:以下参数仅适用于H7。
#
# can.init(CAN.NORMAL, prescaler=32, sjw=1, bs1=8, bs2=3) # 125Kbps
# can.init(CAN.NORMAL, prescaler=16, sjw=1, bs1=8, bs2=3) # 250Kbps
# can.init(CAN.NORMAL, prescaler=8,  sjw=1, bs1=8, bs2=3) # 500Kbps
# can.init(CAN.NORMAL, prescaler=4,  sjw=1, bs1=8, bs2=3) # 1000Kbps

can.restart()

if (TRANSMITTER):
    while (True):
        # Send message with id 1
        can.send('Hello', 1)
        time.sleep_ms(1000)

else:
    # 在接收节点上运行。
    if (omv.board_type() == 'H7'): # FDCAN
        # Set a filter to receive messages with id=1 -> 4
        # Filter index, mode (RANGE, DUAL or MASK), FIFO (0 or 1), params
        can.setfilter(0, CAN.RANGE, 0, (1, 4))
    else:
        # Set a filter to receive messages with id=1, 2, 3 and 4
        # Filter index, mode (LIST16, etc..), FIFO (0 or 1), params
        can.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4))

    while (True):
        # Receive messages on FIFO 0
        print(can.recv(0, timeout=10000))

在 OpenMV RT 上不能用pyb模块,只能使用以下machine模块:

# CAN 扩展板示例
#
# 此示例演示了两个摄像机之间的CAN通信。
# 注意:您需要两个CAN收发器扩展板和DB9电缆才能运行此示例。
import time
from machine import CAN

# 注意:在接收节点上设置为False。
TRANSMITTER = True

can = CAN(0, CAN.NORMAL, baudrate=1000000, auto_restart=True)

if TRANSMITTER:
    while True:
        # Send message with id 1
        can.send("Hello", 1, timeout=100, extframe=False)
        time.sleep_ms(1000)

else:
    # Runs on the receiving node.
    # Set a filter to receive messages with id=1 and 2
    # Filter index, mode (DUAL, etc..), FIFO (0), params
    can.setfilter(0, CAN.DUAL, 0, [1, 2])

    while True:
        # Receive messages on FIFO 0 (there's only one fifo)
        print(can.recv(0, timeout=10000))

results matching ""

    No results matching ""