to better understand serial port communication, I am trying to write some sample code, where Matlab has a loop running, which continously sends data to a serial port, while a Python script running on the same windows machine listens to this port, then receives and prints any received data.
In Matlab, I have written a simple loop, which sends 99 test signals to Port COM1,
% Setup a serial port and open it
tep=serial("COM1", "Baudrate", 9600);
fopen(tep);
% this loop is supposed to send a number to a serial port repeatedly
n = 1; % counter variable
while n < 100
fprintf(tep,"50"); % Send data to serial port
n = n + 1; % Counter variable
pause(0.5) % Sleep to make this loop run for a total of 50s0
fprintf('run'); % Test output within matlab to check, whether it runs
end
% finally close the serial port
fclose(tep);
as far as I can tell, this Matlab part works, as it prints "run" every hald second.
The Python listener:
import serial
import time
# set up the serial line same as in Matlab
ser = serial.Serial('COM1', 9600)
time.sleep(2)
# Read and record the data
data =[] # empty list to store the data
for i in range(50):
b = ser.readline() # read a byte string
string_n = b.decode() # decode byte string into Unicode
string = string_n.rstrip() # remove \n and \r
flt = float(string) # convert string to float
print(flt)
data.append(flt) # add to the end of data list
time.sleep(0.1) # wait (sleep) 0.1 seconds
ser.close()
# show the data
for line in data:
print(line)
Running the script in Python results in the following error:
serial.serialutil.SerialException: could not open port 'COM1': PermissionError(13, 'Zugriff verweigert', None, 5)
Obviously the port is already in use by Matlab, as it sends information to it, but I don't understand, why that is a problem. Shouldn't it be fine, for one program to send data to it and for another to receive data from it?
Kind regards.