Commit 7df36585 authored by Christian Busse's avatar Christian Busse
Browse files

add matlab example

parent 59f11aff
%% Example Sensor Streaming
% in a Python Script executed via MATLAB a TCP socket is opened to send
% dummy sensor values, which are received via the MATLAB TCP client and
% then plotted in a figure.
% see also: https://de.mathworks.com/matlabcentral/answers/153867-running-python-script-in-matlab
% commandStr = 'python /Users/myName/pathToScript/filename.py arg' ;
% Note: Don't click into the black cmd terminal window, otherwise the program might be
% paused (press enter to continue).
clc
clearvars
close all
%%
IP = 'localhost';
PORT = 5555;
myCyan = 1/255*[47 154 166];
%% Executing the Python script via system shell
pyscript = 'example_sensor_streaming.py';
cmd = ['python ', pyscript, ' &']; % the '&' is important -> shell-script is executed in the background so that the MATLAB script can continue
system(cmd);
pause(.5) %give a little time to set up the connection
%% Connecting to socket
tcp_socket = tcpclient(IP, PORT,'ConnectTimeout',5,'Timeout',5);
%% Setup Figure
f = figure('Name','Dummy Sensor');
hold on
grid on
pLine = animatedline;
% format line
pLine.Marker = '.';
pLine.MarkerSize = 16;
pLine.LineWidth = 1;
pLine.Color = myCyan;
xlabel('Time (s)')
ylabel('Temperature (deg)')
%% Plot incoming data
while 1
msg=readline(tcp_socket);
disp(msg);
data = double(strsplit(msg,','));
t = data(1);
val = data(2);
addpoints(pLine, t, val)
drawnow
title(strcat("Value: ",num2str(val)));
end
\ No newline at end of file
from math import cos, pi, sin
import time
import socket
IP = "localhost"
PORT = 5555
server_addr = (IP, PORT)
print("Server IP: " + IP + " Server PORT: " + str(PORT))
matlab_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
matlab_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
matlab_socket.bind(server_addr)
matlab_socket.listen(1)
print("Waiting for client connection!")
(client_socket, address) = matlab_socket.accept()
client_socket.setblocking(False) # socket.recv() will not freeze the script while waiting for data
print("Connection from" + str(address) + "has been established!")
t = 0
dt = 1/20
freq = .1
while True:
try:
val = cos(2*pi*freq*t)
msg = "{:.2f},".format(t)
msg += "{:.3f}\n".format(val)
client_socket.send(msg.encode())
print(msg, end='')
time.sleep(dt)
t = t + dt
except KeyboardInterrupt:
matlab_socket.close()
break
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment