MATLAB Answers

matlab windows to python raspberry pi communication

26 views (last 30 days)
revanth chowdary
revanth chowdary on 5 Mar 2019
Commented: Joshua O'Reilly on 15 Aug 2019
hi,
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
Thanks

  0 Comments

Sign in to comment.

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;
try
fopen(s);
headerToSend = uint8([5 5]);
packetToSend = uint8([1 2 3]);
dataToSend = [headerToSend packetToSend];
fwrite(s,dataToSend);
disp('Data sent is: ')
disp(dataToSend)
fclose(s);
delete(s);
catch ME
disp(ME.message)
end
serial_reader.py (Python)
See serial_reader.py 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 serial_reader_template.py 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 serial_receiver.py. 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 :)

Products


Release

R2018a