Write-only ports in C++
I recently wrote about write-only ports and discussed how they worked and the challenges presented to software developers who need to program them. The solutions proposed were quite straightforward, but the challenge remained to ensure that all the code utilizing the ports complied with the requirements.
I commented at the time that there are several ways to mandate the correct handing of write-only ports, but an approach that interested me was the use of C++ …
In C++, the power of object oriented programming can be very useful for embedded developers. Complex, hard to understand code may be hidden inside objects, which can then be used safely by applications programmers. In this case, I am going to create a class [in effect, a new data type] called write_only_port which deals with all the necessary usage of a shadow copy of the port data. Here is my first shot at it:
volatile unsigned* address;
This needs the 4 member functions defined too [but I will skip the destructor for the moment]:
address = (unsigned*) port;
shadow = 0;
*address = 0;
void write_only_port::operator|=(unsigned val)
shadow |= val;
*address = shadow;
void write_only_port::operator&=(unsigned val)
shadow &= val;
*address = shadow;
This enables write_only_port objects to be created and assigned an address [and initialized to 0]. The applications programmer then has [only] the |= and &= operators available, which are quite sufficient to set and clear bits. Application code using this class may look like this:
myport |= 0x30;
myport &= ~7;
This sets bits 4 and 5 and clears bits 0, 1 and 2. The applications programmer needs to have no knowledge of how a write only port works, but can use them safely.
The next job would be to make the member functions reentrant, but I will save that for another day …
Posted January 28th, 2013, by Colin Walls
- The Repair Café
- IoT keynote, software support and more …
- Go bike!
- Embedded software video blogging – are you interested?
- Six of the best: my photographs
- Testing RTOS API code