Global serial port class



  • Hi,

    I developed a class to communicate with an external device through RS485 serial port.
    In this class I built two private structs of parameters, where the external device writes and reads data. I built some member functions to read and modify these structs.

    I'd like to call these member functions from any point of my software. Is it possible to do this?

    Many thanks for your support.

    Best Regards,

    Chobin


  • Moderators

    @Chobin Sure, it is.
    You just need the instance of that class where you want to call those methods. There are different ways to get the instance. One is singleton pattern, but you should avoid it. Other way is to provide a pointer to all other classes which needs access to it.



  • Hi,

    thank you for your replay.

    Is it a good way to define my mathods as static?

    For example:
    @
    class serialPort {
    public:
    serialPort(QObject *parent = nullptr);
    static void WriteSerialPortBuff(quint16 dataNum);
    }

    //I call the method as follow from other classes
    serialPort::WriteSerialPortBuff(5);
    @

    What do you think about it?

    Many Thanks.

    Best Regards,

    Chobin



  • @Chobin said in Global serial port class:

    Hi,

    thank you for your replay.

    Is it a good way to define my mathods as static?

    For example:
    @
    class serialPort {
    public:
    serialPort(QObject *parent = nullptr);
    static void WriteSerialPortBuff(quint16 dataNum);
    }

    //I call the method as follow from other classes
    serialPort::WriteSerialPortBuff(5);
    @

    What do you think about it?

    Many Thanks.

    Best Regards,

    Chobin

    Hi

    I think that it is only a good way if you want to have just one serialPort for whole your application project

    But if one day you will have a device with two serial ports static method will be not a good way , because this will mean that for each instance of serialPort the writeSerialPortBuff will produce the exactly same result ,

    Therefore for me it is not a good way to have such method as a static method,

    But maybe is there any other opinions?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.