pdf-icon

UIFlow Guide

UIFlow 1.0 Blockly

Event

Unit

UIFlow 1.0 Project

CAN

案例程序

使用ESP32内部CAN控制器资源,实现CAN总线数据收发,注:使用前需要为设备接入 CAN UNIT .

from m5stack import *
from m5ui import *
from uiflow import *
from machine import CAN
import time

setScreenColor(0x222222)

frame = None

label0 = M5TextBox(16, 53, "Device State: ", lcd.FONT_Default, 0x00ff7c, rotate=0)
label1 = M5TextBox(126, 53, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)
label2 = M5TextBox(16, 97, "message: ", lcd.FONT_Default, 0x00ff7c, rotate=0)
label3 = M5TextBox(16, 132, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)
label4 = M5TextBox(16, 162, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)
label5 = M5TextBox(16, 192, "Text", lcd.FONT_Default, 0xFFFFFF, rotate=0)

def buttonA_wasPressed():
  global frame
  can.send([0, 1, 2, 3, 4, 5, 6, 7], 0)
  pass
btnA.wasPressed(buttonA_wasPressed)

def buttonB_wasPressed():
  global frame
  can.clear_tx_queue()
  can.clear_rx_queue()
  pass
btnB.wasPressed(buttonB_wasPressed)

def buttonC_wasPressed():
  global frame
  can.restart()
  pass
btnC.wasPressed(buttonC_wasPressed)


can = CAN(0, extframe=True, mode=CAN.NORMAL, baudrate=CAN.BAUDRATE_25K, tx_io=17, rx_io=16, auto_restart=False)
while True:
  label1.setText(str(can.state()))
  if can.any():
    frame = can.recv()
    label3.setText(str(frame[0]))
    label4.setText(str(frame[1]))
    label5.setText(str(frame[3]))
  wait_ms(30)
  wait_ms(2)

功能说明

from machine import CAN
can = CAN(0, extframe=True, mode=CAN.NORMAL, baudrate=CAN.BAUDRATE_25K, tx_io=17, rx_io=16, auto_restart=False)
  • 初始化CAN总线, 配置是否为拓展帧模式,工作模式(常规模式, 回环模式等)以及波特率设置
can.any()
  • 检查FIFO中是否有未读的数据
frame = can.recv()
  • 接收数据
can.send([0, 1, 2, 3, 4, 5, 6, 7], id)
  • 发送一条数据,并指定数据帧的ID, ID长度为1个byte, 传入的数据类型要求为list或是tuple, 数据帧的数据长度要求是8个byte
can.setfilter(0, CAN.FILTER_RAW_SINGLE, [])
  • 设置过滤组
can.state()
  • 获取CAN控制器状态
can.clear_rx_queue()
  • 清除接收队列
can.clear_tx_queue()
  • 清除发送队列
can.clearfilter()
  • 清除过滤组
can.restart()
  • 重启CAN总线
can.deinit()
  • 停止CAN总线
On This Page