Enlace serial#
Introducción#
SerialLink permite que dos V5 Brains se comuniquen enviando y recibiendo datos seriales sin procesar a través de VEX Link. En lugar de mensajes etiquetados, SerialLink transmite un búfer (una cadena o una matriz de bytes). Esto lo hace útil para la comunicación avanzada entre robots, como la transmisión de datos de sensores, el envío de formatos de paquetes personalizados o la creación de un protocolo propio basado en bytes.
Cada uso de send agrega datos al búfer de recepción del V5 Brain vinculado. Los datos se leen en el orden en que llegan (primero en entrar, primero en salir). Si se envían varios búferes antes de que el otro V5 Brain use receive, permanecen en cola y se devuelven uno a uno en el orden en que se enviaron. Debido a que los datos pueden acumularse en la cola, enviar repetidamente grandes búferes en cada ciclo puede generar retrasos; para enlaces críticos en tiempo real, envíe solo lo que necesite.
Importante: Ambos robots deben estar ejecutando proyectos que utilicen SerialLink al mismo tiempo, o no se enviarán ni recibirán datos.
This page uses link as the example SerialLink name. Replace it with your own configured name as needed.
A continuación se muestra una lista de los métodos disponibles:
is_linked– Devuelve si este Cerebro está conectado activamente a su Cerebro emparejado.send– Envía un mensaje corto (con datos int/float opcionales) al Brain emparejado.receive– Espera y devuelve el siguiente mensaje entrante.received– Registra una función que se llamará cada vez que se reciba un nuevo mensaje.
Crear un enlace#
Crea un SerialLink en ambos V5 Brains para establecer un canal de comunicación entre ellos, ya sea de forma inalámbrica con las radios de robot V5 o mediante un cable inteligente, de modo que los robots puedan enviarse datos seriales sin procesar.
SerialLink(smartport, name, linktype, wired)
Parámetro |
Descripción |
|---|---|
|
El puerto inteligente utilizado para esta conexión es aquel al que está conectado el V5 Robot Radio (inalámbrico) o al que está conectado el Smart Cable (con cable). Se escribe como |
|
El nombre único que se le dará a este enlace como una cadena. |
|
El rol que este Cerebro utilizará para este par de enlaces. Cada par debe incluir un Administrador y un Trabajador:
|
|
Opcional. Indica si la conexión es por cable o inalámbrica:
|
Código para el Robot 1
""" Create a wireless link in Port 1 name: VEXRoboticsLink123456789 linktype: Manager """ link = SerialLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER)Código para el Robot 2
""" Create a wireless link in Port 1 name: VEXRoboticsLink123456789 linktype: Worker """ link = SerialLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER)
Métodos disponibles#
Una vez configurado SerialLink y conectados los módulos Brains, puede utilizar los métodos que se describen a continuación para enviar, recibir y responder a datos seriales sin procesar.
is_linked#
is_linked El método devuelve si los V5 Brains en un SerialLink están emparejados entre sí.
True– Los dos cerebros V5 están emparejados y comunicándose a través de este enlace.False– Los dos cerebros V5 no están emparejados en este enlace.
Nota: Es recomendable comprobar siempre que los V5 Brains estén conectados al inicio de un proyecto antes de ejecutar cualquier otro código.
Usage:
link.is_linked()
Parámetros |
Descripción |
|---|---|
Este método no tiene parámetros. |
Código para el Robot 1
# Send a message to the other robot # Create the link link = SerialLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") link.send("HELLO")Código para el Robot 2
# Display the message that Robot 1 sends # Create the link link = SerialLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() def received_message(bytearray, length): # Slice the bytearray to the valid data data = bytearray[:length] # Decode and strip the message before displaying it text = data.decode().strip() brain.screen.print("Got: ", text) # Call received_message whenever a message is received link.received(received_message)
send#
send transmite bytes seriales sin procesar al otro V5 Brain vinculado.
Al leer esos datos con receive, receive solo devolverá un valor una vez que haya recopilado la cantidad de bytes especificada por su receive parámetro. Debido a eso, si su código siempre llama a length con una lengthfija, debe asegurarse de que cada mensaje enviado con send tenga exactamente esa cantidad de bytes (a menudo mediante relleno) para que el receptor no se bloquee esperando bytes adicionales.
Si no quieres depender de un recuento exacto de bytes, usa received en su lugar; te permite manejar cualquier byte que esté disponible sin requerir una longitud específica.
Usage:
send(buffer)
Parámetros |
Descripción |
|---|---|
|
Los datos que se enviarán al otro cerebro V5 vinculado. Esto puede ser una cadena |
Código para el Robot 1
# Send a message to the other robot # Create the link link = SerialLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") link.send("HELLO")Código para el Robot 2
# Display the message that Robot 1 sends # Create the link link = SerialLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() def received_message(bytearray, length): # Slice the bytearray to the valid data data = bytearray[:length] # Decode and strip the message before displaying it text = data.decode().strip() brain.screen.print("Got: ", text) # Call received_message whenever a message is received link.received(received_message)
receive#
receive devuelve datos seriales del otro V5 Brain vinculado en orden FIFO (los datos no leídos más antiguos primero).
Debido a que receive espera un número exacto de bytes, la mensajería de longitud fija a menudo requiere relleno cuando se usa send para que cada mensaje alcance el tamaño esperado. Si el remitente transmite menos de length bytes, receive seguirá esperando los bytes restantes y no devolverá nada.
If the queue is empty and you provide a timeout, receive waits up to that many milliseconds for new data. If nothing arrives in that window, it returns None. Any data sent afterward remains queued to be read later.
Usage:
receive(length, timeout)
Parámetros |
Descripción |
|---|---|
|
El número de bytes a recibir. |
|
Opcional. Indica cuánto tiempo en milisegundos esperará |
Código para el Robot 1
# Send a math problem for the other Brain to solve # Create the link link = SerialLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") """ Change whether to "add" or "subtract", then what numbers to use in the operation. """ packet = "add,7,2.5" # Pad with spaces until it's exactly 16 bytes while len(packet) < 16: packet = packet + " " link.send(packet)Código para el Robot 2
# Solve the math problem that the other Brain sends # Create the link link = SerialLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() # Receive exactly 16 bytes buffer = link.receive(16) # Remove the added " " padding text = buffer.decode().strip() # Separate the operator and numbers parts = text.split(",") operator = parts[0] a = float(parts[1]) b = float(parts[2]) # Use what operator was sent if operator == "add": result = a + b elif operator == "subtract": result = a - b # If not "add" or "subtract", do nothing else: pass brain.screen.print("Result = ", result)
received#
received registra una función que se llamará cada vez que el V5 Brain reciba datos seriales.
Usage:
link.received(callback)
Parámetros |
Descripción |
|---|---|
|
Una función definida previamente que se ejecuta cuando el cerebro V5 recibe datos seriales. |
received devolución de llamada se llaman con dos argumentos:
Firma de devolución de llamada:
callback(buffer, length)
Argumento |
Descripción |
|---|---|
|
Un array de bytes |
|
El número de bytes válidos recibidos en el búfer |
Código para el Robot 1
# Send a message to the other robot # Create the link link = SerialLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") link.send("HELLO")Código para el Robot 2
# Display the message that Robot 1 sends # Create the link link = SerialLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() def received_message(bytearray, length): # Slice the bytearray to the valid data data = bytearray[:length] # Decode and strip the message before displaying it text = data.decode().strip() brain.screen.print("Got: ", text) # Call received_message whenever a message is received link.received(received_message)