Report
1 week, 1 day ago.

How to share pins in a class?

I'm trying build a library that sets two objects on the same pins, at least I think that's how to describe what I'm trying to do. Its all working in a one big main.cpp, but now I need to do the same in a library. The problem is setting esp and esp2 on the same pins.

Normally I can work this out by looking at examples but can't find anything like this.

It's a simple two file library, ESP8266.CPP and EAP8266.h.

This is what I have but clearly its not working.

..

// from main.ccp existing working program not using a library
//  Serial esp(D8,D2,230400);   // tx, rx, baudrate 
//  Serial esp2(D8,D2,230400);  // tx, rx, baudrate 

// I want to set just one object here:
// Serial esp(D8,D2,230400);   // tx, rx, baudrate 




// this is my ESP8266.cpp
ESP8266::ESP8266(PinName tx, PinName rx, uint32_t _baud) : esp(tx, rx), esp2(tx, rx)
{    
    esp.baud(_baud);    
    esp2.baud(_baud);
    
    timeout=5000;
    debugOn=debug;        
}

    //........ rest of code




// this is my ESP8266.h
class ESP8266
{
public:

    ESP8266(PinName tx, PinName rx, uint32_t baud);
    
    //......... rest of code
    
    
private:

    RawSerial esp;
    RawSerial esp2;

..

Can anyone help please :)

Comment on this question

1 Answer

1 week ago.

It looks like you have a serial port and you want two ESP8266 objects to have access to it? Most straightforward way is to create the RawSerial object at top level along with both ESP8266 objects and pass a Reference to RawSerial object into ctor of each ESP object. Something like this:

// main.cpp
RawSerial serial(D8, D2, 230400);
ESP8266 esp1(serial);
ESP8266 esp2(serial);


// ESP8266.h
class ESP8266 {
public:
 
    ESP8266(RawSerial& serial) :
        serial_(serial) {

        serial_.printf("Print stuff\n");
   }
      
private:
    RawSerial& serial_;
}; 


To post an answer, please log in.