MBED GPIO appears very simple on the surface, first create a DigitalOut object with a constructor, argument being the preferred pin. Thenafter, simply treat the instance like a variable. looking at the .h implementation, looks like the “&operator= (int value)” which is kind of cool.
but how can I use GPIO inside of a class? Such that in main where the instance of said class is defined, the constructor will accept PinName and will toggle the GPIO as the library needs to. what is the “right” way to do this? do I have to play to implement some pointer magic? sorry I’m a bit rusty on my C++, haven’t touched it since college.
Take the following example:
#include "mbed.h"
#ifndef wait_ms
#define wait_ms(i) thread_sleep_for(i);
#endif
static BufferedSerial pc(PA_9, PA_10, 115200);
// connect serial_port to the output stream of printf (console)
FileHandle *mbed::mbed_override_console(int fd) { return &pc; }
class Foop {
public:
DigitalOut _a;
Foop(PinName name) {
_a(name);
}
void ledHigh() {
_a = 1;
}
void ledLow() {
_a = 0;
}
};
int main() {
Foop led1(LED1);
while (true) {
led1.ledHigh();
wait_ms(100);
led1.ledLow();
wait_ms(100);
printf("blinky example running on Mbed OS %d.%d.%d.\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
}
}
This was my initial idea, but the problem is there is no default constructor defined for DigtalOut class. So then my next idea was to play some shenanigans with pointers like this:
class Foop {
public:
DigitalOut *a;
Foop( DigitalOut * ptr ) {
a = ptr;
}
void ledHigh(){
(*a)=1;
}
void ledLow(){
(*a)=0;
}
};
int main() {
DigitalOut ledpin(LED1);
Foop led1( &ledpin );
while (true) {
led1.ledHigh();
wait_ms(50);
led1.ledLow();
wait_ms(50);
printf(" blinky example running on Mbed OS %d.%d.%d.\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
}
}
This does work, and does so by passing a DigitalOut pointer to the class, which manipulates it. This way I can choose the pin to use within main.cpp. and have the library work with any pin. However this seems like the wrong way to do it. Is there a way set it up so that I just pass the pinName into it directly rather than define it in main separately? what’s the right way to do this?
How efficient is this method compared to Arduino digitalWrite? (which is notoriously slow given it has to convert an abstract pin name to port and register and mask) why does the assignment return *this? Is it to do with the fancy implementation that allows me to treat it like a variable?