Ejemplo de envio y recepcion Python CAN / SLCAN

SLCAN es un protocolo de interfaz CAN que opera via comunicacion serial. Es a menudo usado para conectar a interfaces CAN via USB.

El siguiente ejemplo usa la libreria python-can para enviar y recibir mensajes CAN via SLCAN.

La intencion basica es tener dos adaptadores CAN separados (como el FYSETC UCAN realmente barato con el slcan firmware)

Primero, instala la libreria python-can:

install_python_can.sh
pip install python-can

Ejemplo de sender

Este codigo se conecta a /dev/ttyACM0 y repetidamente envia un solo mensaje CAN:

slcan_sender.py
#!/usr/bin/env python3
import can
import time

# Configuracion para el dispositivo SLCAN
slcan_device = '/dev/ttyACM0'
baud_rate = 500000  # Establece el baud rate apropiado para tu setup

# Crear una instancia de CAN bus usando la interfaz SLCAN
bus = can.interface.Bus(interface='slcan', channel=slcan_device, bitrate=baud_rate)

# Definir un mensaje CAN simple
can_id = 0x123  # CAN ID
data = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]  # 8 bytes de data

# Crear un mensaje CAN
message = can.Message(arbitration_id=can_id, data=data, is_extended_id=False)

try:
    while True:
        # Enviar el mensaje CAN
        bus.send(message)
        print(f"Sent: {message}")

        # Esperar un segundo antes de enviar el siguiente mensaje
        time.sleep(1)

except KeyboardInterrupt:
    print("Stopped by user")

except can.CanError as e:
    print(f"CAN error: {e}")

Ejemplo de salida

slcan_sender_output.txt
Sent: Timestamp:        0.000000    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Sent: Timestamp:        0.000000    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Sent: Timestamp:        0.000000    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Sent: Timestamp:        0.000000    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Sent: Timestamp:        0.000000    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Sent: Timestamp:        0.000000    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Sent: Timestamp:        0.000000    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Sent: Timestamp:        0.000000    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08

Ejemplo de receiver

Este codigo se conecta a /dev/ttyACM1 y escucha mensajes CAN entrantes (y los imprime en la linea de comandos):

slcan_receiver.py
#!/usr/bin/env python3
import can

# Configuracion para el dispositivo SLCAN
slcan_device = '/dev/ttyACM1'
baud_rate = 500000  # Establece el baud rate apropiado para tu setup

# Crear una instancia de CAN bus usando la interfaz SLCAN
bus = can.interface.Bus(interface='slcan', channel=slcan_device, bitrate=baud_rate)

try:
    print("Listening for CAN messages on", slcan_device)
    while True:
        # Leer un mensaje del CAN bus
        message = bus.recv()

        if message is not None:
            print(f"Received: {message}")

except KeyboardInterrupt:
    print("Stopped by user")

except can.CanError as e:
    print(f"CAN error: {e}")

Ejemplo de salida

slcan_receiver_output.txt
Listening for CAN messages on /dev/ttyACM1
Received: Timestamp: 1722300573.156834    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Received: Timestamp: 1722300573.157226    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Received: Timestamp: 1722300573.157592    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Received: Timestamp: 1722300573.157937    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Received: Timestamp: 1722300573.979205    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Received: Timestamp: 1722300574.979508    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Received: Timestamp: 1722300575.979660    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Received: Timestamp: 1722300576.979969    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08
Received: Timestamp: 1722300577.980201    ID:      123    S Rx                DL:  8    01 02 03 04 05 06 07 08

Echa un vistazo a artículos similares por categoría: Python CAN