从Python实时传输数据到MATLAB

0 投票
1 回答
2540 浏览
提问于 2025-04-18 15:16

我正在使用Python从USB输入设备读取数据。我想知道有没有办法能让这些数据和MATLAB中的模型实时交换。现在我做法是把读取到的数据保存到一个.mat文件里,然后让模型从这个文件中读取,这样做不是很直观。以下是我使用的代码:

    #Import the needed libraries
    import usb.core,usb.util,sys,time
    import sys
    from array import *
    import scipy.io

    #find our device
    dev = usb.core.find(idVendor=0x046d, idProduct=0xc29a)

    # was it found?
    if dev is None:
       raise ValueError('Device not found')

   # set the active configuration. With no arguments, the first
   # configuration will be the active one
   try:
     dev.set_configuration()
     #In the event of an error
   except usb.core.USBError as e:
     print('Cannot set configuration the device: %s' %str(e))
     sys.exit()

   # get an endpoint instance
   cfg = dev.get_active_configuration()
   intf = cfg[(0,0)]
   ep = usb.util.find_descriptor(
               intf,
     # match the first IN endpoint
     custom_match = \
     lambda e: \
     usb.util.endpoint_direction(e.bEndpointAddress) == \
     usb.util.ENDPOINT_IN)

  #Initialising variables
  #Databases for access in MATLAB
  gas_pedal_data={}
  brake_pedal_data={}
  steering_wheel_bit5_data={}
  steering_wheel_bit6_data={}
  gas_pedal=[]
  brake_pedal=[]
  steering_wheel_bit5=[]
  steering_wheel_bit6=[]
  i=0
  #Read data from the device as long as it is connected
  while(dev!= None):
       try:
          #Read data
          data = dev.read(ep.bEndpointAddress, ep.wMaxPacketSize,
                          timeout=1000)
          gas_pedal.append(data[6])
          gas_pedal_data['gas_pedal']=gas_pedal
          scipy.io.savemat('test.mat',gas_pedal_data)
          brake_pedal.append(data[7])
          brake_pedal_data['brake_pedal']=brake_pedal
          scipy.io.savemat('test.mat',brake_pedal_data)
          steering_wheel_bit5.append(data[4])
          steering_wheel_bit5_data['steering_wheel_bit5']=steering_wheel_bit5
          scipy.io.savemat('test.mat',steering_wheel_bit5_data)
          steering_wheel_bit6.append(data[5])
          steering_wheel_bit6_data['steering_wheel_bit6']=steering_wheel_bit6
          scipy.io.savemat('test.mat',steering_wheel_bit6_data)
       except usb.core.USBError as e:
          print("Error readin data: %s" %str(e))
          time.sleep(5)
          continue

1 个回答

0

你有几个选择。

  • 你可以在Matlab里定期检查某个文件是否存在,然后在有新数据时读取它。
  • 你可以打开一个管道,让Python和Matlab之间进行通信(这也需要在Matlab那边定期检查)。具体的代码可以参考这里
  • 你可以使用本地的UDP或TCP套接字进行通信。可以通过使用PNET(这同样需要定期检查),或者使用Matlab的仪器控制工具箱(这个可以让你设置一个回调函数)。

因为Matlab是单线程的,所以你的模型需要考虑到新数据的提供。你需要在有新数据时明确触发模型重新评估。

撰写回答