Search code examples
c++classarduinolibraries

Creating object(s) within a Class


I have this problem:

Problem:

  • I am trying to create a library (ard33WiFi) that manages and handles a couple of other libraries (WiFiServer library for example)
  • I need to create the server object that I then use in functions in my Library (ard33WiFi):

WiFiServer myServer(iPort);

  • The problem is that when I call myServer in the members of the class I get:

'myServer' was not declared in this scope

Where/how do I declare myServer so that is becomes available to the entire class (ard33WiFi)? I have taken out any decleration because whatever I was trying was wrong. I have pasted a skeleton code below.

// HEADER FILE (.h)
// ----------------------------------------------------------------------------------------------
#ifndef Ard33WiFi_h
#define Ard33WiFi_h

#include <WiFiNINA.h>
#include <WiFiUdp.h>

class ard33WiFi{
  public:
    ard33WiFi(int iPort)

    void someFunction();
    void serverBegin();

  private:
    int _iPort;

};
#endif

// ----------------------------------------------------------------------------------------------
// C++ FILE (.cpp)
// -----------------------------------------------------------------------------------------------
#include <Ard33Wifi.h>

ard33WiFi::ard33WiFi(int iPort){
  _iPort = iPort;
}
void ard33WiFi::someFunction(){
  // code here required to prepare the server for initializing
  // but ultimately not relevant to the question
}
void ard33WiFi::serverBegin(){
  myServer.begin();
  Serial.println("Server Online");
}

I run into the same problem with the UDP library as I need to call the UDP object in various functions to do UDP things.

Any help would be greatly appreciated.


Solution

  • I suppose you are using this:

    https://www.arduino.cc/en/Reference/WiFiServer

    I can see that you are not declaring the myServer in your class; that I guess is the error in your code. If I am not wrong, it should be something like this:

    #ifndef Ard33WiFi_h
    #define Ard33WiFi_h
    
    #include <WiFiNINA.h>
    #include <WiFiUdp.h>
    #include <WiFi.h>  // Not sure if you have to append this include
    
    class ard33WiFi{
      public:
        ard33WiFi(int iPort)
    
        void someFunction();
        void serverBegin();
    
      private:
        int _iPort;
        WiFiServer myServer;
    
    };
    #endif
    

    The implementation, you would need to initialise the instance:

    #include <Ard33Wifi.h>
    
    ard33WiFi::ard33WiFi(int iPort):myServer(iPort), _iPort(iPort) {
    }
    
    void ard33WiFi::someFunction(){
      // code here required to prepare the server for initializing
      // but ultimately not relevant to the question
    }
    void ard33WiFi::serverBegin(){
      myServer.begin();
      Serial.println("Server Online");
    }