MATLAB SIMULINK 处理编程串行通信?

问题描述

如何从 MATLAB Simulink(串行发送块)发送一些数据并在处理编程中接收该值?我完全需要一个浮点数或整数。 我使用的是虚拟串口,例如COM1用于SIMULINK串口配置,COM2用于处理。

解决方法

您可以使用 Processing Serial Library 连接串行端口。

一旦快速和肮脏的选项也从 SIMULINK 发送作为以换行符 ('\n') 结尾的字符串的数据。

使用 bufferUntil('\n')serialEvent() 的组合,您可以监听完整的字符串,无论是 int 还是 float 并简单地解析它。

这是上面示例的修改版本,用于说明解析:

// Example by Tom Igoe 
 
import processing.serial.*; 
 
Serial myPort;    // The serial port
PFont myFont;     // The display font
String inString;  // Input string from serial port
int lf = 10;      // ASCII linefeed 
 
void setup() { 
  size(400,200); 
  // You'll need to make this font with the Create Font Tool 
  myFont = loadFont("ArialMS-18.vlw"); 
  textFont(myFont,18); 
  // List all the available serial ports: 
  printArray(Serial.list()); 
  // I know that the first port in the serial list on my mac 
  // is always my  Keyspan adaptor,so I open Serial.list()[0]. 
  // Open whatever port is the one you're using. 
  myPort = new Serial(this,Serial.list()[0],9600); 
  myPort.bufferUntil(lf); 
} 
 
void draw() { 
  background(0); 
  text("received: " + inString,10,50); 
} 
 
void serialEvent(Serial p) { 
  inString = p.readString(); 
  // if we received a valid string from Simulink
  if(inString != null && inString.length() > 0){
    // trim white space (\n,etc.)
    inString = inString.trim();
    // parse value
    int valueAsInt = int(inString);
    float valueAsFloat = float(inString);
    println("received: ",valueAsInt,valueAsFloat);
  }
  
} 

请注意,以上内容未经测试(因为我没有 Simulink),但它应该说明了这个想法。 (记得在运行前仔细检查并更新使用的串口,当然要匹配 Simulink 和 Processing 之间的波特率)。

这将是一种简单的方法,但不是一种非常有效的方法,因为您需要为浮点值发送多个字节。

如果您只需要发送最多 255(一个字节)的 int,您可以在 Processing 中简单地使用 readByte()。如果你需要发送一个更大的整数(例如 16 位或 32 位整数),那么你需要像 readBytes() 这样的东西来缓冲单个字节,然后将它们组合成一个更大的更高精度的整数。 (类似于浮动)。

许多年前,我记得与一位才华横溢的机器人工程师一起工作,他使用的是 Simulink,但我们没有使用 Serial,而是使用本地机器上的套接字来让软件相互通信。在那种情况下,因为我们需要一个恒定的快速数据流,所以我们使用了 UDP 套接字(在 Processing 中可以由 oscP5 library 处理)。可能值得检查是否有用于基于 UDP 的 OSC(开放式声音控制)协议的 Simulink 插件/库。使用整数/浮点数打包命名消息会更容易,因为您不必从头开始编写通信协议。