sending data from raspberry pi (python) to matlab or simulink over TCP/IP
17 次查看(过去 30 天)
显示 更早的评论
Hello, I am trying to send random-data from raspberry pi (python script) to Matlab or simulink. The objective is to monitor the real time data from raspberry pi in simulink or matlab.
1) I have used !ping in matlab to connect raspberry pi
2) I wanted to use TCP/IP connection but i can't receive the data this is my code in raspberry pi :
import socket
import numpy as np
import encodings
from time import sleep
import random
#import json
from random import uniform
import datetime
connflag = True
HOST = '192.168.0.128' # Standard loopback interface address (localhost)
PORT = 46384 # Port to listen on (non-privileged ports are > 1023)
def my_server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print("Server Started waiting for client to connect ")
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
sleep(5)
if connflag == True:
timestamp = datetime.datetime.now()
tempreading = uniform(20.0,25.0) # Generating Temperature Readings
message = '{"timestamp":'+'"'+str(timestamp)+'",'+'"temperature":'+str(tempreading)+'}'
print("msg sent: temperature " + "%.2f" % tempreading ) # Print sent temperature msg on console
try:
s.sendall(message.encode())
except BrokenPipeError:
print("Error: Connection to the remote end has been lost") # Handle the error as needed
else:
print("waiting for connection...")
if __name__ == '__main__':
while 1:
my_server()
3) For matlab to receive the data, i used this code but it seems that it doesn't work well.
% Define the host and port information
HOST = '192.168.0.128';
PORT = 46384;
% Define the process_data_from_server function
function [x_temperature, y_humidity] = process_data_from_server(data)
parts = strsplit(data, ",");
x_temperature = parts{1};
y_humidity = parts{2};
end
% Define the my_client function
function my_client()
t = timer('TimerFcn', 'my_client', 'Period', 11, 'ExecutionMode', 'fixedRate');
start(t);
% Create a TCP socket
s = tcpip(HOST, PORT, 'NetworkRole', 'Client');
% Open the socket connection
fopen(s);
% Send the input command to the server
my = input("Enter command ");
fwrite(s, my, 'char');
% Receive the data from the server
data = fread(s, s.BytesAvailable, 'char');
data = char(data');
% Process the data and print the results
[x_temperature, y_humidity] = process_data_from_server(data);
fprintf("Temperature %s\n", x_temperature);
fprintf("Humidity %s\n", y_humidity);
% Close the socket connection
fclose(s);
stop(t);
delete(t);
pause(5);
end
% Call the my_client function in a loop
while 1
my_client();
end
I think there is a problem with matlab code because i'm not good in matlab i don't know how to change it to be able to get the data from raspberry pi.
Thank you for your help ;)
0 个评论
采纳的回答
Smit
2023-2-9
Hi,
I understand your server program is running on Raspberry Pi and client program is running on MATLAB and you are facing issues with your code.
Looking at your code, I think you will have to make multiple changes which are as follows: -
1) You say that you are connecting to Raspberry Pi using the “!ping” command in MATLAB.
However, “!” before a command implies that the OS is going to run the command. Secondly, “ping” is used to test connections and not actually make connections.
2) In the section of the code
% Receive the data from the server
data = fread(s, s.BytesAvailable, 'char');
% In the following line you have a stray single quote at the end
data = char(data');
You need to remove the stray single quote.
3) You need to pass “HOST” and “PORT” to the function. You can do so in the following manner
function my_client(HOST, PORT)
You will have to call the function with these arguments as well
my_client(HOST, PORT);
4) In MATLAB scripts, your function definitions should reside at the end. So, you will need to move the following section of the code
% Call the my_client function in a loop
while 1
my_client();
end
Before the function definition.
Hope this helps!
2 个评论
AdiKaba
2023-3-21
Hello Fatemh,
I am doing simiar. Do I mind posting the MATLAB portion of the code that worked for you.
Thank you!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 MATLAB Support Package for Raspberry Pi Hardware 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!