Thought Leadership

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:

class write_only_port
{
unsigned shadow;
volatile unsigned* address;
public:
write_only_port(unsigned);
~write_only_port();
void operator|=(unsigned);
void operator&=(unsigned);
};

 

This needs the 4 member functions defined too [but I will skip the destructor for the moment]:

write_only_port::write_only_port(unsigned port)
{
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:

main()
{
write_only_port myport(0x10000);
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 …

Colin Walls

I have 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, I am a member of the marketing team of the Mentor Graphics Embedded Systems Division, and am based in the UK. Away from work, I have a wide range of interests including photography and trying to point my two daughters in the right direction in life. Learn more about Colin, including his go-to karaoke song and the best parts of being British: http://go.mentor.com/3_acv

More from this author

This article first appeared on the Siemens Digital Industries Software blog at https://blogs.sw.siemens.com/embedded-software/2013/01/28/write-only-ports-in-c/