Simulink与Python之间的UDP通讯
解决问题
在当前项目中同时使用python和Matlab/Simulink,两个软件之间的不可避免的需要数据交互。使用UDP通讯可以满足二者的互相发送和接收数据。本文python程序参考 https://blog.csdn.net/qq_41871826/article/details/104172653
软件版本
Matlab 2021b
python 3.7
Simulink设置
从Simulink模块库中拖出UDP Send 模块和Byte packing模块,连接六路数据通道。(数据从simulink发送到python )
Byte packing设置如下
UDP send 设置如下
从Simulink模块库中拖出UDP Receive 模块和Byte unpacking模块,连接六路数据接收通道。(接收从python发送到simulink的数据 )
UDP receive 设置如下
Byte unpacking设置如下
上述的IP地址视需要而定
Python数据发送程序
该程序对应simulink的UDP接收模块
#!/usr/bin/env python
# -*- coding: utf-8 -*
import socket, struct, os
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
def main():
# -------------------------------- Initializing --------------------------------------------
# Create a socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serveraddr = ("172.22.51.198", 9202)
count = 0
# Create an increment for while loop
while count < 10:
send_msg_code = struct.pack("6d", 1.1,1.2, 1.3,1.4,1.5,1.6) #对应Simulin的六路数据接收
udp_socket.sendto(send_msg_code, serveraddr)
count += 1
print(send_msg_code)
sleep(1)
# Close the udp socket.
udp_socket.close()
if __name__ == "__main__":
main()
Python数据接收程序
该程序对应simulink的UDP数据发送模块
#!/usr/bin/env python
# -*- coding: utf-8 -*
import socket, struct, os
import numpy as np
import matplotlib.pyplot as plt
def main():
# -------------------------------- Initializing --------------------------------------------
# Create a socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Bind the IP address and port.
localaddr = ("172.22.51.198", 8087)
udp_socket.bind(localaddr)
# Create an increment for while loop
count = 0
# Create a list to restor the data from simulink.
data_collect = []
# Create a path to save figure:
path1 = 'D:/TJU/HansRobot_Control/Motion_Control_V01'
print("Please open the Simulink file under the current working directory")
print("The program is waiting until you run the Simulink file.")
#----------------------------------- Data Receiving ----------------------------------------
# Using a loop to receive data from Simulink
while count < 10: # Can be modified by (simulationTime/sampleTime).
# Start to receive data from Simulink.
recv_data = udp_socket.recvfrom(1024)
# recv_data will return tuple, the first element is DATA, and the second is address information
recv_msg = recv_data[0]
send_addr = recv_data[1]
# Decode the data from Simulink whose type is double and return a tuple
#recv_msg_decode = struct.unpack("d", recv_msg)[0]
print(send_addr,recv_msg)
recv_msg_decode = struct.unpack("6d", recv_msg)[1]
print(struct.unpack("dddddd", recv_msg),recv_msg_decode)
# Restore the data to a list:
data_collect.append(recv_msg_decode)
# Set the condition to jump out of this loop ???
# Print the address information and the received data
print("Number from MATLAB %s is : %s" % (str(send_addr), recv_msg_decode))
count += 1
# Close the udp socket.
udp_socket.close()
# ------------------------------------ Visualization -----------------------------------------------
# Set the time axis, 10 is the simulation end time that can be modified by user.
index = list(np.linspace(0, 10, (len(data_collect))))
plt.plot(index, data_collect)
plt.title("Signal Received from Simulink")
plt.xlabel("Time")
plt.ylabel("Received Data")
plt.savefig(os.path.join(path1, 'data_figure.png'), dpi=600)
print("Close the figure to restart.")
plt.show()
if __name__ == "__main__":
main()
Simulink文件链接:
https://pan.baidu.com/s/1YGmFIq3jd8RWQo45E6L75g
提取码:y2ok
2023/2/2