Connecting to USB device with serialport vs. serial command

조회 수: 8 (최근 30일)
Daemonic
Daemonic 2023년 1월 26일
댓글: Daemonic 2023년 1월 28일
I have a TrueRNG usb random number generator that I can connect to and read data from using the serial command. However, serial is being replaced by serialport but I am having difficulty reading from the device using the new configuration method. I am assuming I am making a mistake in how the communication settings are configured. Below are my steps for each method. I'd really appreciate any help in figuring out what I'm doing wrong with the serialport method.
I'm running Matlab R2022a.
Old Method which currenlty works got get data.
Device = ls('/dev/cu.usb*');
spaces = find(isspace(Device));
Device(spaces) = [];
RNGobj=serial(Device);
RNGobj.BaudRate=460800;
RNGobj.Terminator='CR';
RNGobj.ByteOrder='bigEndian';
RNGobj.InputBufferSize=2^18;
RNGobj.BytesAvailableFcnMode='byte';
RNGobj.BytesAvailableFcnCount=2^10;
fopen(RNGobj);
fread(RNGobj, 1, 'int8')
% Returns a random number.
ans = -79
This produces a random number (EX: -79)
New method using serialport which produces an error
% attempt to replicate the above with serialport
Device = ls('/dev/cu.usb*');
spaces = find(isspace(Device));
Device(spaces) = [];
RNGobj=serialport(Device, 460800, "ByteOrder", "big-Endian");
configureTerminator(RNGobj,"CR");
RNGobj.InputBufferSize=2^18;
configureCallback(RNGobj,"byte",2^10,@BytesAvailableFcn)
fopen(RNGobj)
fread(RNGobj, 1, 'int8')
% Returns an empty value
ans = [];
Running the above produces an empty value [] and the warning below:
Warning: The specified amount of data was not returned within the Timeout period for 'read'.
'serialport' unable to read any data. For more information on possible reasons, see serialport Read Warnings.

답변 (1개)

Walter Roberson
Walter Roberson 2023년 1월 26일
serialport does not have any fopen() or fread() . It automatically opens the port when you create the object, and it uses read() or readline()
Also I recommend that you use serialportlist instead of ls() like that.
Your read from the port should really be within the BytesAvailableFcn -- at which point it would be dealing with data already in the buffer.
In a case such as this where you are wanting to read bytes outside of the callback, you should probably not be configuring a callback.
  댓글 수: 5
Walter Roberson
Walter Roberson 2023년 1월 27일
Interesting. I would suggest experimenting with setDTR
Daemonic
Daemonic 2023년 1월 28일
Thanks for the tip... unfortunately - no dice. I also tried connecting using the Instrument Toolbox which works great. Unfortunately, the toolbox utilizes the old method of creating a serial object.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Serial and USB Communication에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by