Colin Walls has over thirty years experience in the electronics industry, largely dedicated to embedded software. A frequent presenter at conferences and seminars and author of numerous technical articles and two books on embedded software, Colin is an embedded software technologist with Mentor … More »
Write-only ports in C++
June 18th, 2018 by Colin Walls
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:
This needs the 4 member functions defined too [but I will skip the destructor for the moment]:
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:
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 …