🛠 Pont Linux ↔ Arduino : appeler des fonctions du sketch M4 depuis Python (RPC)

Arduino Portenta X8 · intermediaire · Schéma : IMG-portenta-x8-intermediaire-1-portenta-x8-rpc-python-m4.svg — Arduino Portenta X8 en deux colonnes : à gauche un conteneur Python avec un script appelant subtract(7,4), à droite le cœur Cortex-M4 du STM32H747XI avec la fonction bindée, flèches aller-retour étiquetées msgpack-RPC et m4-proxy ports 5001-5020, terminal affichant le résultat 3

Objectives

The core of the X8 architecture: making Linux and Arduino talk to each other. The official bridge is a msgpack-RPC: on the Linux side, the systemd service m4-proxy (preinstalled, listening on port 5001) acts as the broker; on the M4 side, the RPC library from the Mbed core allows you to RPC.bind C++ functions callable from containers, and RPC.call to call functions served by Linux. You will replay the official tutorial "Python ↔ Arduino data exchange": an M4 sketch that exposes subtract, and a Python container that calls it — with the M4 serial monitor proxied on /dev/ttyGS0.

Hardware

Complete Code

// rpc_server_m4.ino — pattern de l'exemple officiel PortentaX8_EchoServer
#include "SerialRPC.h"   // proxy du moniteur serie vers Linux
#include "RPC.h"         // msgpack-RPC M4 <-> Linux via m4-proxy

// Fonction tournee sur le M4, appelable depuis un conteneur Linux
int subtract(int a, int b) { return a - b; }

void setup {
  Serial.begin(115200);          // visible cote Linux via m4-proxy
  pinMode(LED_BUILTIN, OUTPUT);
  RPC.bind("subtract", subtract);   // enregistre l'API pour Linux
}

void loop {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
  // Appel vers Linux : « whoami » est servi par le service m4-proxy
  if (Serial.available) {
    String cmd = Serial.readStringUntil('\n');
    if (cmd.startsWith("whoami")) {
      auto res = RPC.call("whoami").as<std::string>;
      Serial.println(res.c_str);
    }
  }
}
# cote Linux (conteneur arduino/python-rpc-serial) — appel du M4
# lance : adb shell puis docker exec -it python-rpc-serial python3
import rpc
client = rpc.Client("127.0.0.1", 5001)     # le broker m4-proxy
print(client.call("subtract", 7, 4))        # -> 3, calcule sur le M4

Expected Verification

After flashing the M4 sketch and launching the container, the Python call subtract(7, 4) returns 3 — computed physically on the Cortex-M4. By typing whoami on the proxied serial port, it is the M4 that queries Linux and prints fio. The broker service is monitored with sudo journalctl -fu m4-proxy: this is the first place to look when RPC is not responding.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials