Python – CAN Bus uitlezen
Op deze pagina vind je een voorbeeld hoe je CAN Bus uitleest in Python3
Wat heb je nodig?
- Python library: python-can
Installatie:
git clone https://github.com/hardbyte/python-can.git
Cloning into ‘python-can’…
remote: Enumerating objects: 18, done.
remote: Counting objects: 100% (18/18), done.
remote: Compressing objects: 100% (16/16), done.
remote: Total 13080 (delta 3), reused 2 (delta 2), pack-reused 13062
Receiving objects: 100% (13080/13080), 4.07 MiB | 5.77 MiB/s, done.
Resolving deltas: 100% (9522/9522), done.
cd python-can
sudo python3 setup.py install
Voorbeeld uitlezen
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# import the library import can # create a bus instance # many other interfaces are supported as well (see below) bus = can.Bus(interface='socketcan', channel='can0', receive_own_messages=True) # iterate over received messages for msg in bus: print("{:X}: {}".format(msg.arbitration_id, msg.data)) # or use an asynchronous notifier notifier = can.Notifier(bus, [can.Logger("recorded.log"), can.Printer()]); |
1 2 3 4 5 6 7 8 |
10: bytearray(b'co\xa2\x00\x00\x00\x00\x00') 10: bytearray(b'co\xa3\x00\x00\x00\x00\x00') 10: bytearray(b'co\xa4\x00\x00\x00\x00\x00') 10: bytearray(b'co\xa5\x00\x00\x00\x00\x00') 10: bytearray(b'co\xa6\x00\x00\x00\x00\x00') 10: bytearray(b'co\xa7\x00\x00\x00\x00\x00') 10: bytearray(b'co\xa8\x00\x00\x00\x00\x00') 10: bytearray(b'co\xa9\x00\x00\x00\x00\x00') |
Voorbeeld schrijven
1 2 3 4 5 6 7 8 9 10 |
# import the library import can # create a bus instance # many other interfaces are supported as well (see below) bus = can.Bus(interface='socketcan', channel='can0', receive_own_messages=True) # send a message message = can.Message(arbitration_id=0x20, is_extended_id=False, data=[1, 0x22, 0x33]) bus.send(message, timeout=0.2) |