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

  • 4
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
如果您下载了本程序,但是该程序存在问题无法运行,那么您可以选择退款或者寻求我们的帮助(如果找我们帮助的话,是需要追加额外费用的)。另外,您不会使用资源的话(这种情况不支持退款),也可以找我们帮助(需要追加额外费用) MATLAB(Matrix Laboratory)是一款由美国MathWorks公司开发的高性能商业数学软件,它集成了高级技术计算语言、交互式环境以及丰富的工具箱,被广泛应用于工程计算、数据分析、算法开发和科学可视化等领域。MATLAB的核心功能包括: 1. **数值计算**:支持大规模矩阵和数组运算,对线性代数、微积分、概率统计等数学问题提供高效解决方案。 2. **编程环境**:提供了易于使用的脚本编写与函数定义界面,支持面向对象编程,并可通过M文件实现模块化程序设计。 3. **数据可视化**:内置强大的二维和三维图形绘制功能,能够创建高质量的数据图表,便于数据分析和结果展示。 4. **工具箱扩展**:MathWorks为MATLAB提供了众多领域的专业工具箱,如信号处理、图像处理、通信系统、控制系统、机器学习、深度学习、量化金融、优化算法等,极大地扩展了MATLAB的应用范围。 5. **Simulink仿真**:作为MATLAB的重要组成部分,Simulink是一个动态系统建模、仿真和基于模型的设计环境,特别适用于多域物理系统和嵌入式系统的模拟和实时测试。 6. **集成能力**:MATLAB可以与其他编程语言(如C、C++、Java、Python等)及外部应用程序进行数据交换和联合开发,也可以调用硬件接口进行实时实验和控制。 7. **交互式工作空间**:用户可以在命令窗口中直接输入表达式并立即得到结果,这种交互式的特性使得快速原型设计和调试变得极为便利。 总之,MATLAB是科学家、工程师和技术人员进行科研、教育和工业应用不可或缺的强大工具之一,尤其在需要大量数值计算和复杂系统建模的场景下发挥着重要作用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值