matlab windows to python raspberry pi communication

16 views (last 30 days)
I'm working on a project in whiich i need to send data between a matlab code running on my windows pc to a python 3.6 code running on raspberry pi 3b+.
the data is very small, a single character which need to be sent once every few seconds.
i was planning to use serial communication between the two devices via a usb to TTL coverter [ connected to GPIO pins on raspberry pi].
i was wondering if the serial communication format used in matlab and python[ pyserial] is compatabile and whether they can directly communicate without any modifications. can i get some samples codes on how to achieve this sort of cross language communication.
based on the input from the matlab code the rpi performs some actions.
are there any other better alternatives for the said purpose, and can i get some links or sample codes for the same

Answers (1)

Joshua O'Reilly
Joshua O'Reilly on 30 Jul 2019
Yep, you can! I've attached a quick program I'm using that sends data with MATLAB and receives with Python. Currently, it sends 3 bytes (with 2 header bytes), while the received creates an array out of the received bytes after the header, up until a timeout is reached (this is because I haven't decided how long I'd like my full message to be yet).
serial_sender.m (MATLAB)
The file to send a message is in the zip named serial_sender.m
comport = 'COM3'
s = serial(comport);
s.BaudRate = 57600;
headerToSend = uint8([5 5]);
packetToSend = uint8([1 2 3]);
dataToSend = [headerToSend packetToSend];
disp('Data sent is: ')
catch ME
end (Python)
See inside the attached zip (Mathworks doesn't let you upload Python files directly) . I added a few comments to hopefully clarify what is happening and make it easier for you to adopt. I also added a super simple "template" file called to give a less detailed look at receiving serial messages using Python.
serial_receiver.m (MATLAB) and Python Sender
I write a MATLAB script to receive serial messages (same format as those that are being send by the other script), named I don't have a python serial sender, but it should be simple to find a tutorial or two.
Changes I'd Recommend
You would need to change the data type in the line
new_dat = struct.unpack("b",buffer)
From "b" to "B", depending if your character is unsigned or not.
Lemme know if you have any questions :)


Find more on MATLAB Support Package for Raspberry Pi Hardware in Help Center and File Exchange




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!