Linux下can和canopen同时用

本代码主要介绍Linux下在使用can的同时使用canopen,并且对can总线的数据进行监测的。

Linux系统:Ubuntu

Python版本:Python3

环境:已安装好can canopen模块

#!/usr/bin/env python3
# coding: utf-8

import multiprocessing
import time
import os
import can
import canopen

def canBusInit():
    try:
        os.system('sudo ifconfig can0 down')
        os.system('sudo ip link set can0 type can bitrate 250000')
        os.system('sudo ifconfig can0 up')
        return can.interface.Bus(bustype='socketcan', channel='can0', bitrate=250000)
    except:
        time.sleep(5)
        print("canbus  restart")
        canBusInit()

def canTest():
    print("canTestProcess start")
    while(1):
        time.sleep(1)
        msg = can.Message(arbitration_id=0x123, data=[0, 1, 2, 3, 4, 5, 6, 7], extended_id=False)
        bus.send(msg)

def canopenTest():
    print("canopenTest start")
    while(1):
        time.sleep(1)
        node.nmt.state = 'PRE-OPERATIONAL'
        # 等待3s
        time.sleep(1)
        # 把slave从PRE-OPERATIONAL设置为OPERATIONAL状态
        node.nmt.state = 'OPERATIONAL'

def listenTest():
    print("shellTest start")
    bus = can.interface.Bus(channel='can0', bustype='socketcan',bitrate=250000) 
    while(1):
        msgFrombed = bus.recv(timeout=0)
        if msgFrombed is not None:
            print(msgFrombed)

def main(): 
    p1 = multiprocessing.Process(target=canTest)
    p2 = multiprocessing.Process(target=canopenTest)
    p3 = multiprocessing.Process(target=listenTest)
    p1.start()
    p2.start()
    p3.start()    

if __name__ == '__main__': 
    #init canbus
    bus = canBusInit()

    #re-using a bus
    network = canopen.Network()
    network.bus = bus
    listeners = network.listeners
    notifier = can.Notifier(bus, listeners, 0.5)

    # 添加slave节点,其id是6,对象字典为CANopenSocket.eds
    node = canopen.RemoteNode(6, 'CANopenSocket.eds')
    network.add_node(node)

    #start main
    main()

运行该脚本,可以在终端打印如下信息,说明can和canopen能同时用,并且能监控到发送出去的数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值