Assigning Ports Within Class Object Creation

Hi. I have a class that incorporates port manipulation. I want to be able to create multiple objects within a project using the same class, but be able to assign the port at the point of object creation.

So to create my object, I’m looking for something along the lines of...

MyClass MyObject1(PORTx)

But I’m not sure what data type I can assign to port to then use within the class object to assign a port of my manipulation steps, if that makes sense?!?

For MyObject 1, I might want to call PORTB, but in MyObject 2 it might be PORTD...

Any ideas how best to pass the port name into the class object effectively?

All of the stuff within the class I’m sorted on in terms of what happens to the port within the class functions, but just getting the port name into the object is the bit I’m struggling with.

TIA

Then definition of PORTB, etc is in "iom328p.h". Look for it in your Arduino installation.

If you want your class to be able to manipulate ports, you need to pass them a reference or pointer to the port, not pass them by value.

Fortunately, C++ has ways for you code to deduce types without having to manually look them up, and you can even give types names just like variables with the typedef feature. Observe:

typedef decltype(&PORTB) PortPointer;

void setup() {
  // put your setup code here, to run once:
  PortPointer p = &PORTC;
  *p = 0xCC; // access the port through the pointer variable and assign it a new value.
}

void loop() {
  // put your main code here, to run repeatedly:

}

&PORTB is the way you would normally assign the address of the port to a pointer variable.

decltype() deduces the type of whatever value is in it's parentheses, in this case the type is a pointer to a port variable (volatile unsigned char* for most AVR registers).

Finally, the typedef A B construct makes the B name a synonym for the type defined in the A expression. You can use this new name just like any other type name, as show in the expression I put in the setup() function.

That's magic, thank you!
Working a treat!

Love this forum - always someone willing to help!

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.