Connecting to USB device with serialport vs. serial command
7 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
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()
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!