Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 3 of 3

Thread: Serial port access from library

  1. #1
    Junior Member
    Join Date
    Mar 2019
    Posts
    10

    Serial port access from library

    I need to write an arduino library that can be instanciated multiple times, with different hardware serial ports as targets.

    I've seen that libraries that are receive-only like TinyGPS go around the complexity by letting you handle the serial port in your main sketch and just expect you to push received chars to it. Mine however need to both read and write to the port, so that approach doesn't work, or it would be somewhat dirty to implement a function to get any pending bytes form the library and send them in the main sketch.

    What would be the correct way to tell the port I want to use to the constructor of the class in my library?

  2. #2
    Senior Member PaulStoffregen's Avatar
    Join Date
    Nov 2012
    Posts
    20,681
    Recommend you follow Firmata's example.

    https://github.com/firmata/arduino/b...rmata.cpp#L128

    Create a begin() function that takes a Stream or HardwareSerial reference, then store it as a Stream pointer for use by the rest of the library.

    Avoid code in your constructor which deals with other classes. While that usually works with Teensy, because we use constexpr constructors, it tends to go quite badly on many other boards if you hit the "c++ static initialization order fiasco".

    Also generally recommend using constexpr on your constructor, if your design can work within the limits constexpr imposes. Those limits *really* help the compiler to optimize programs which use your library.

  3. #3
    Junior Member
    Join Date
    Mar 2019
    Posts
    10
    Thanks, will look into it! The constexpr part is a bit above my head at this point though...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •