xreef / PCF8574_library

PCF8574 library. i2c digital expander for Arduino, Raspberry Pi Pico and rp2040 boards, esp32, SMT32 and ESP8266. Can read write digital values with only 2 wire. Very simple to use and encoder support.
Other
216 stars 62 forks source link

No constructor for "only declaring" available #49

Closed alve89 closed 3 years ago

alve89 commented 3 years ago

Hey!

I'd like to use this library for an project where I need to have the PCF8574 object as a attribute / property of a class, so something like

class myClass {
  public:
    PCF8574* getMyPCF();
    void setMyPCF();

  private:
    PCF8574 myPCF;
};

Unfortunately something like this would throw an error because there's no "empty" constructor for the PCF8574 library available. I want to be able to set the address of the myPCF object afterwards. Is there a way to do that without changing the librarys code? Otherwise I could start a pull request adding something like setAddress(uint8_t addr)...

xreef commented 3 years ago

Hi alve89, use void* pointer. Bye Renzo

alve89 commented 3 years ago

Thanks for your very quick reply! I just tried a bit with this but still I don't see how to store the PCF8574 object as a property in a myClass object and "change" its address afterwards...? So my problem is the line PCF8574 myPCF; in my first post.

xreef commented 3 years ago

If you don't want to instantiate the object you have to use a pointer. ` class myClass { public: PCF8574* getMyPCF(); void setMyPCF();

private: PCF8574* myPCF; }; `

But I think it's better if you declare first like in this example.

Bye Renzo

alve89 commented 3 years ago

I understand that. The problem with only having the pointer is, that I would need to instantiate the object somewhere else (e.g. in global scope) but I don't want the user to instantiate it by himself, I want to provide an interface (get / set methods), so I thought of instantiating the object in the myClass object and use it with the getMyPCF() method. The example you provided does exactly what I don't want: Declaring / defining the objects in global scope and use them in setup() (and loop()).

alve89 commented 3 years ago

I just changed the library by the following things:

  1. PCF8574.h: Adding default value for _address
  2. PCF8574.h: Adding void setAddress(uint8_t address); and void setI2CPins(uint8_t sda, uint8_t scl);
  3. PCF8574.cpp: Adding the definitions of the declarations above

If you find this helpful, feel free to use it. Beside this issue I think these changes can be helpful. If you see another way to solve this issue, I'm looking forward to your response!

PCF8574_library_emptyConstructor.zip

@xreef I just noticed an error in my code, I forgot the &Wire line - I added it and it's working properly now!