How to setup serial port in base workspace and access from function workspace?

3 views (last 30 days)
Hello,
I would like to setup a serial port via s = serialport(port,baudrate) in the base workspace (initialization file) since serial port setup wont change during the life of the connection this really only needs to run once. However, I would like to call the serial port object from other function/functions workspace/workspaces. What are best practices to achieve this or is this even an acceptable practice at all?
Thank you,
Wess

Answers (1)

dpb
dpb on 3 Aug 2023
Simply pass the returned serial port object to the function(s) where it's needed.
Best factorization would probably be to write a little function to call to do the initialization as well rather than just a bunch of constants buried inline in code; gives you the flexibility to change parameters if/when needed.
  31 Comments
dpb
dpb on 8 Aug 2023
"you might be able to use textscan but for that kind of work it would also be common to use text manipulation to extract the pieces and convert them as needed, as that would tend to have lower overhead than using textscan()"
I hadn't thought necessarily of the former; wonder how the new(ish) extract() and patterns stuff might stack up. I've begun using them a fair amount for convenience, but not for anything that has an performance impact that would show; purely for convenience in writing some pattern matching.
Personally, I'd not think of textscan first, either, but would tend to drop straight down to sscanf for such low-level work.
But, there's the other end of starting with the highest level there is and then only worry about performance/optimization if/when that is shown to not be fast enough.
Walter Roberson
Walter Roberson on 8 Aug 2023
Early on, I tested the pattern-based routines, and at least at that time they were much slower than regexp() . But that might have changed.

Sign in to comment.

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!