    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Raspberry Pi Linux User Mode GPIO in C++ (Part 2)</title>
        <link>https://members.accu.org/index.php/articles/2148</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 27, #4 - September2015</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c353/">274</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-353/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+353/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Raspberry Pi Linux User Mode GPIO in C++ (Part 2)</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 06 September 2015 07:14:58 +01:00 or Sun, 06 September 2015 07:14:58 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Ralph McArdell continues developing a C++ library for Raspberry Pi expansions.
</p>
<p><strong>Body:</strong>&nbsp;<p>Previously <a href="#[1]">[1]</a> I described the initial stage of developing a library called <code>rpi-peripherals</code> <a href="#[2]">[2]</a> to access general purpose input output (GPIO) on a Raspberry Pi running Raspbian Linux in C++ from user land â€“ that is there are no kernel mode parts to the library. The library was built on memory mapping the physical memory locations of the Raspberry Piâ€™s BCM2835 processorâ€™s peripheralsâ€™ control registers using the <code>dev/mem</code> device accessed via an RAII (resource acquisition is initialisation <a href="#[3]">[3]</a>) resource managing class template called <code>phymem_ptr</code>.</p>

<p>Part 1 ended having described support for reading and writing single bit Boolean values representing the high/low voltage state of an associated GPIO pin in the forms of the <code>ipin</code> and <code>opin</code> types. Along the way we met various other entities such as the <code>pin_id</code> type representing the value of a BCM2835 GPIO pin, and the aforementioned <code>phymem_ptr</code> template.</p>

<p>This second instalment continues by describing adding support for some other IO functions and the challenges they presented.</p>

<h2>But firstâ€¦</h2>

<p>One thing the <code>ipin</code> type does not support is waiting for a change of state to its associated GPIO pin before returning from a <code>get</code> operation. I really needed to address this as it was the very thing that started me on the road to writing my original Python Raspberry Pi GPIO library <a href="#[4]">[4]</a> <a href="#[5]">[5]</a>.</p>

<p>In the Python GPIO library the need for a blocking read was specified in the call to an <code>open</code> function and a suitable object would be returned that had a <code>read</code> operation that would wait until the specified edge event (rising, falling or either) occurred.</p>

<p>As mentioned the <code>rpi-peripherals</code> library directly accesses peripheralsâ€™ registers by memory mapping them curtesy of the <code>phymem_ptr</code> class template. The only readily available way to receive GPIO pin edge event notifications in user space is via the <code>/sys/classes/gpio</code> pseudo file system â€“ as used by my Python library.</p>

<p> I did not like the idea of mixing GPIO access methods in <code>ipin</code> or some related class so I took a different approach. Instead a totally separate class called <code>pin_edge_event</code> encapsulates handling pin edge events via <code>/sys/classes/gpio</code>. In order to work with <code>/sys/classes/gpio</code> the GPIO pinâ€™s number is required and the pin should be exported <a href="#[4]">[4]</a> <a href="#[6]">[6]</a> and, of course, set up for input. As it happens an <code>ipin</code> instance, using the <code>pin_export_allocator</code> type to control access to GPIO pins between processes, just happens to fulfil all these criteria. Hence a <code>pin_edge_event</code> is constructed from an existing <code>ipin</code> instance together with an indication of which edge events are of interest:</p>

<pre class="programlisting">
  ipin in_pin{pin_id{23}};
  pin_edge_event pin_evt{in_pin,
    pin_edge_event::rising};</pre>

<p>On construction the pinâ€™s associated <code>/sys/classes/gpio</code> edge event file is opened. The pin is marked as having an associated <code>pin_edge_event</code> object as I thought it too confusing to allow more than one per <code>ipin</code> at a time. On destruction the pin is effectively closed for edge events by passing the file descriptor obtained during the open process to the Linux <code>close</code> function and the pin marked as not having an associated <code>pin_edge_event</code> object.</p>

<p>The implementation of <code>pin_edge_event</code> revolves around a call to <code>pselect</code> <a href="#[7]">[7]</a> â€“ chosen over <code>select</code> for the fairly flimsy reason that it allows timeout resolution in nanoseconds rather than microseconds. The <code>pin_edge_event</code> interface allows waiting in various ways for an event to be signalled, from waiting indefinitely for an event to just checking to see if an event has been signalled:</p>

<pre class="programlisting">
  pin_evt.wait();
  assert(pin_evt.signalled());</pre>

<p>In between, in the style of certain C++11 library APIs, there are <code>wait_for</code> and <code>wait_until</code> member function templates to wait for a specific amount of time or wait until a specific absolute time for an event to be signalled. They are templates as they use <code>std::chrono::duration</code> and <code>std::chrono::time_point</code> specialisations for their time parameters:</p>

<pre class="programlisting">
  auto wait_duration(std::chrono::milliseconds{
    100U});
  bool edge_event_signalled{
    pin_evt.wait_for(wait_duration)};
  ...
  auto now(std::chrono::system_clock::now());
  auto wait_time(now+wait_duration);
  edge_event_signalled =
    pin_evt.wait_until(wait_time);</pre>

<p>As can be seen from the example usage the <code>signalled</code>, <code>wait_for</code> and <code>wait_until</code> operations return a <code>bool</code> value which is <code>true</code> if an event was signalled. The <code>wait</code> operation does not return a value as it waits indefinitely for an event: if it returns then there was an event.</p>

<p>The final operation supported by <code>pin_edge_event</code> is the <code>clear</code> operation which needs to be performed after an edge event has been signalled. This has to do with how <code>/sys/classes/gpio</code> edge event handling works in that the value of the input pin the event occurred on needs to be read from the relevant file before another event can be waited on. Another <code>/sys/classes/gpio</code> edge event handling quirk is that a <code>pin_edge_event</code> object is initially in the signalled state:</p>

<pre class="programlisting">
  ipin in_pin{pin_id{23}};
  pin_edge_event pin_evt{
    in_pin,pin_edge_event::rising};
  assert(pin_evt.signalled());
  pin_evt.clear();
  assert(!pin_evt.signalled());</pre>

<h2>The time has come</h2>

<p>Having sorted out single pin GPIO support the time had finally arrived to look at some of the other peripheral functions available. I thought that adding support for pulse width modulation (PWM) allowing me to make use of the motor controller on the Gertboard would be an interesting next step. But as â€˜pulse width modulationâ€™ hints at, regular pulses are required which implies the use of a clock. In the case of the BCM2835 the PWM controller uses a separate but dedicated clock that has the same programming interface as the general purpose clocks that can be connected to GPIO pins. So in order to support PWM I would first have to provide support for clocks.</p>

<p>Like GPIO, clocks are controlled by a set of registers based at a specific physical address. Each clock is controlled by the clock manager peripheral and has its own set of two registers at an offset from this base address. Frustratingly the BCM2835 ARM Peripherals document <a href="#[8]">[8]</a> only gives the base address for the clock manager and the offsets from it for the three general purpose clocksâ€™ register sets, not for clocks associated with other peripherals such as the PWM clock â€“ although mention is made that the PWM clock is designated <code>clk_pwm</code>. I had to refer back to the provided Gertboard C code to locate the required offset value.</p>

<p>As with GPIO I started with the clock registers layout. Each clock controlled by the clock manager has the same register structure so I split the implementation into two structures: one describing a single clock, which I called a <code>clock_record</code> and the main <code>clock_registers</code> structure which contained a <code>clock_record</code> member for each supported clock carefully placed so that it was at the correct offset from the start of a structure instance â€“ and yes there is a test to check they are at the expected offsets.</p>

<p>Like <code>gpio_registers</code> I provided member functions to get or set the individual fields within a clockâ€™s registers. In the case of <code>clock_registers</code> which clock to operate on needs to be specified implying passing some sort of identifier. The easiest solution turned out to be to define the <code>clock_id</code> as a type alias for a pointer to <code>clock_record</code> member of <code>clock_registers</code>:</p>

<pre class="programlisting">
  typedef clock_record clock_registers::* clock_id;</pre>

<p>Each member function of <code>clock_registers</code> takes a <code>clock_id</code> as a parameter and uses it to pass on the call to the identified <code>clock_record</code> member:</p>

<pre class="programlisting">
  clock_registers
  {
    ...
    clock_src get_source(clock_id clk) 
      volatile const
    {
      return (this-&gt;*clk).get_source();
    }
    ...
  };</pre>

<p>The specific clock ids were then defined as global <code>constexpr clock_id</code> instances initialised to the relevant <code>clock_record</code> memberâ€™s â€˜addressâ€™ value, for example:</p>

<pre class="programlisting">
  constexpr clock_id pwm_clk_id
    {&amp;clock_registers::pwm_clk};</pre>

<h2>Frequent division diversions</h2>

<p>You would think the interface to a clock would be simple: specify the required frequency and provide operations to start, stop and possibly query the frequency and the running state. This is the sort of interface I wanted the public library clock support to provide.</p>

<p>However, at the lower levels it turns out to be not so simple. First you have to supply the clock with a source of oscillation at a fixed frequency â€“ the Raspberry Pi has a 19.2 MHz oscillator that can be used as an external (to the BCM2835) clock source which seems the easiest to use. Next it needs to be divided down to the required frequency. </p>

<p>Dividing down the clock source is more complex than just supplying an integer divider. Most required frequencies will have no integer divisor that produces an exact match. For example if the clock source oscillates at 1 MHz and we require a 134 KHz clock then the best we can do is divide by 8, yielding a frequency of 125 KHz, or by 7, yielding a frequency of around 143 KHz. So in addition to integer division the clocks provide something called MASH filtering (MASH it appears stands for Multi-stAge noise Shaping) â€“ about which I know very little other than the information provided in the BCM2835 clock peripheral documentation. When using one of the three MASH filtering modes a fractional division value is used in addition to the integer division value. The result is that the actual clock frequency varies slightly between a minimum and maximum value, but the average frequency should be very close to that requested. The down side is that the MASH filtering modes introduce a bunch of constraints on maximum frequency and minimum integer divider value.</p>

<p>I wanted to work in terms of frequency rather than modes and divisor values. Providing a frequency type would allow the use of frequency units such hertz, kilohertz and megahertz. Thinking about this I noted that the inverse of frequency â€“ or cycles per second â€“ is a duration value â€“ seconds per cycle. The standard library has the <code>std::chrono::duration</code> class template along with type aliases for specialisations representing various common time units such as microseconds and hours. I felt there should be some way to use <code>std::chrono::duration</code> to represent frequency. However, a solution was not immediate forthcoming so to keep moving forward and not get distracted further I effectively copied the required parts of the <code>std::chrono::duration</code> class template as my libraryâ€™s <code>frequency</code> class template. The implementation was so similar that, in a somewhat hacked manner, when I produced a <code>frequency_cast</code> function template to cast between different frequency specialisation types, it was implemented in terms of <code>std::chrono::duration_cast</code> and <code>std::chrono::duration</code> â€“ I had reached the end of my patience on these diversions! Completing the support for frequency I added a bunch of <code>frequency</code> specialisation type aliases for common frequency units: hertz, kilohertz and megahertz.</p>

<p>In addition to the frequency support I also added enumeration and simple class types and constant definitions to help with specifying a clock including a constant definition for the Raspberry Piâ€™s 19.2 MHz oscillator. These all live in the <span class="filename">clockdefs.h</span> library public header.</p>

<p>I created the <code>clock_parameters</code> class to aid bridging between frequencies and clock modes and divisors. Instances are created from a clock source and frequency (external clock source at 19,200,000 Hz for the Raspberry Piâ€™s 19.2 MHz external clock for example) along with the desired clock frequency specification combining the desired (average) frequency and an enumeration value specifying the level of MASH filtering required:  maximum, medium, minimum or none â€“ where none means use only an integer divisor.</p>

<p>During construction, after some basic parameter value checks, possibly repeated attempts are made to try to obtain a valid frequency value starting with the filter mode requested in the constructor parameters and falling back to lower levels if the maximum frequency produced is too high. If the frequency value exceeds even the substantially higher value allowed the finally attempted integer only division mode a <code>std::range_error</code> is thrown. A <code>std::range_error</code> will also be thrown if the integer divisor is too small for the selected filter mode.</p>

<p>If no exception is thrown during construction then the various parameters can be queried via non-modifying accessor member functions.</p>

<h2>Now there are two</h2>

<p>The purpose of the <code>clock_registers</code> class is for a volatile instance to be mapped to the clock peripheralsâ€™ register block using a <code>phymem_ptr&lt;volatile clock_registers&gt;</code> instance. Some ability to detect trying to use the same clock peripheral multiple times would also be useful. So, as with the <code>ipin</code> and <code>opin</code> types and the <code>gpio_ctrl</code> singleton, a singleton type was created combining a <code>phymem_ptr&lt;volatile clock_registers&gt;</code> instance with simple in-process clock-in-use allocation provided by the <code>simple_allocator</code> class template, specialised on the number of things available to allocate (in this case the 4 clocks: pwm_clk and gpclk 0, 1 and 2) and based around a <code>std::bitset</code>. Only in-process allocation management was provided because I could not see any straight forward way to provide an open inter-process allocation management scheme for clocks or other peripherals.</p>

<p>Setting up a GPIO pin for use as one of the three general purpose clocks not only requires access to the <code>clock_ctrl</code> instance but also to the <code>gpio_ctrl</code> instance so as to allocate the pin and set the correct alternate function for it. This would of course apply to any other peripherals supported by the library. When the only thing that needed to access the main GPIO registers were the <code>ipin</code> and <code>opin</code> types then <code>gpio_ctrl</code> could be left internal to the <span class="filename">pin.cpp</span> implementation file. But now there were two â€“ the <code>ipin</code>/<code>opin</code> code in <span clsss="filename">pin.cpp</span> and the <code>clock_pin</code> code in <span clsss="filename">clock_pin.cpp</span> â€“ some changes would be required. </p>

<p>As a bout of refactoring was inevitable it seemed prudent to decide on some conventions. First the library facilities were divided into the public API parts and library internal parts with the internal parts being placed in a nested <code>internal</code> namespace. Next, those headers required for using the public API were moved from the project <span clsss="filename">src</span> directory to the project <span clsss="filename">include</span> directory. This was always going to happen â€“ it was just a matter of what and when. Finally, the <code>gpio_ctrl</code> code was moved out of <span clsss="filename">pin.cpp</span> and into its own library internal files <span clsss="filename">gpio_ctrl.h</span> and <span clsss="filename">gpio_ctrl.cpp</span>. A similarly named type and implementation file-pair were created for the clock peripherals: <code>clock_ctrl</code> in files <span clsss="filename">clock_ctrl.h</span> and <span clsss="filename">clock_ctrl.cpp</span>.</p>

<p>This leads to a basic pattern: for a peripheral <em>p</em> there would be a <em>p</em><span clsss="filename">_registers.h</span> header file containing a <em>p</em><code>_registers</code> class usually together with supporting entities that mapped <em>p</em>â€™s register structure and associated values to C++ entities. This would be used, qualified <code>volatile</code>, to specialise a <code>phymem_ptr</code> mapped to the peripheralâ€™s registersâ€™ physical memory block start address along with some sort of in-use tracking in a <em>p</em><code>_ctrl</code> singleton type implemented in <em>p</em><span clsss="filename">_ctrl.h</span> and <em>p</em><span clsss="filename">_ctrl.cpp</span>. The <em>p</em><code>_registers</code> and <em>p</em><code>_ctrl</code> types (and source files) are internal to the library. The public API would be presented by a type <em>p</em><code>_pin</code> with <em>p</em><span clsss="filename">_pin.h</span> being placed in the project <span clsss="filename">include</span> directory. Along the way there may be ancillary items which would often be internal to the library (such as <code>phymem_ptr</code> or the <code>/sys/classes/gpio</code> support in <span clsss="filename">sysfs.h</span> and <span clsss="filename">sysfs.cpp</span>) but sometimes â€“ as with <code>pin_id</code> and those entities placed in the <span clsss="filename">clockdefs.h</span> header â€“ would be part of the public API. Figure 1 shows the pattern as a UML class diagram; <code>ipin</code> and <code>opin</code> are included to show they only access <code>gpio_ctrl</code> while other peripherals additionally access their own <em>p</em><code>_ctrl</code> type.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/cvu27-4/McArdell/McArdell-01.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 1</td>
	</tr>
</table>


<h2>Can you do this?</h2>

<p>The <code>clock_pin</code> class provides the libraryâ€™s public support for general purpose clock functions on GPIO pins and unsurprisingly requires a <code>pin_id</code> specifying which GPIO pin to use. Wherein lies a problem. Unlike general input and output which all GPIO pins can perform, alternative functions â€“ such as a general purpose clock (gpclk) function â€“ can only be performed by a few, sometimes only one, pin. Which alternate functions a pin can perform is given in a table in the BCM2835 ARM Peripherals document.</p>

<p>On the other hand no pin supports more than one clock peripheral so if a pin supports one of the general purpose clocks then the pin number uniquely defines which general purpose clock (0, 1 or 2).</p>

<p>To help check if a pin supports a given peripheral function and which of the six alternate pin functions it is supported by I created the <code>gpio_alt_fns</code> module that provides a set of overloaded <code>select</code> query functions that select data from a statically initialised 2 dimensional array that defines the alternate functions each pin supports. The values are enumeration values taken from another table in the BCM2835 ARM Peripherals document that names the peripheral functions. </p>

<p>This allows questions such as which alternate function for pin <em>p</em> supports peripheral function <em>f</em> or which, if any, of a set of peripheral functions <em>fs</em> does pin <em>p</em> support? The <code>select</code> functions return a <code>result_set</code> object that has a partial STL container like interface allowing access via iterators, <code>operator[]</code> and <code>at</code> and can be queried for <code>size</code> and being <code>empty</code>. The items in the result set are of a simple descriptor type specifying the pin, the special peripheral function and the alternative pin function it is supported on.</p>

<p>During the development of the <code>gpio_alt_fns</code> module I found that I had prefixed almost all identifiers with <code>pin_alt_fn_</code>. This seemed silly so I gave in and placed the whole lot in its own <code>pin_alt_fn</code> nested namespace. </p>

<h2>Easy time?</h2>

<p>So how easy is it to use a GPIO pin as a general purpose clock?</p>

<p>Like <code>ipin</code> and <code>opin</code>, <code>clock_pin</code> uses RAII to manage the GPIO pin and general purpose clock resources. The most complicated operation is creating a <code>clock_pin</code> instance. Once successfully created the object can be used to easily start, stop and query whether the clock is running as well as obtain the values for the minimum, maximum and average frequencies the clock is using.</p>

<p>To create a clock the <code>clock_pin</code> constructor needs to be passed three things: the <code>pin_id</code> of the GPIO pin to use as a clock â€“ which should support such a function of course, a clock source (passing <code>rpi_oscillator</code> defined in <span clsss="filename">clockdefs.h</span> is the easiest option), and finally a <code>clock_frequency</code> object specifying the desired clock frequency and the filter mode to apply. The <code>clock_frequency</code> type is defined in <span clsss="filename">clockdefs.h</span>.</p>

<p>For example we could create a 600 KHz clock with no MASH filtering (that is, using only integer division) like so:</p>

<pre class="programlisting">
  clock_pin clk{
    gpio_gclk, rpi_oscillator,
    clock_frequency{kilohertz{600},
    clock_filter::none}
  };</pre>
  
<p>Note that <code>gpio_gclk</code> is defined in <span clsss="filename">pin_id.h</span> and yields a <code>pin_id</code> for GPIO pin 4, which supports gpclk0 as alternate function 0 and is available on pin 7 of the Raspberry Pi P1 connector. During construction all values are checked, with exceptions thrown in case of problems, and the GPIO pin and clock allocated and setup. The clock and pin are of course released during destruction, after ensuring the clock is stopped.</p>

<p>To check what frequencies are being used the <code>frequency_avg</code>, <code>frequency_min</code> and <code>frequency_max</code> member functions can be called. In this case we would expect a 600 KHz value for all three frequency values as only integer division of the clock source was applied and, as it happens, 600 KHz divides wholly into 19.2 MHz:</p>

<pre class="programlisting">
  assert(clk.frequency_min()==hertz{600000U});
  assert(clk.frequency_avg()==hertz{600000U});
  assert(clk.frequency_max()==hertz{600000U});
<p>We can check if the clock is running â€“ which just after construction it should not be:</p>
  assert(!clk.is_running());
<p>And of course we can start and stop the clock:</p>
  clk.start();
  ...
  clk.stop();</pre>
  
<p>The output of gpclk0 running at 600 KHz can be observed by connecting GPIO pin 4 to the input of an oscilloscope as shown in Figure 2 â€“ in which the time-base used is 1 ÂµS per division.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/cvu27-4/McArdell/McArdell-02.jpg" /></td>
	</tr>
	<tr>
		<td class="title">Figure 2</td>
	</tr>
</table>

<h2>After clocking up all those distractionsâ€¦</h2>

<p>Having provided support for clk_pwm and the general purpose clocks and refactored the library, I could return to pulse width modulation. PWM <a href="McArdell.xml#[M9]">[9]</a> allows control of power to devices such as motors by varying the ratio of high to low time per clock cycle (the duty cycle). You will notice in the clock trace shown in Figure 2 that these are equal, a ratio of 0.5: during each cycle the clock pulse is high for half the time and low for the other half of the time. PWM allows this ratio to be varied dynamically.</p>

<p>The BCM2835 has a single PWM controller that supports two channels that are referred to as PWM0 and PWM1 (as denoted by pin alternate functions) or channels 1 and 2 (as denoted by the PWM controllerâ€™s register descriptions), where channel 1 maps onto PWM0 and channel 2 to PWM1. Each channel can be used in either PWM mode or serialiser mode in which buffered data is written serially to the PWM channelâ€™s GPIO pin. I included support for serialiser mode in the <code>pwm_registers</code> class implementation for completeness but do not provide support in the <code>pwm_pin</code> class. There are two PWM channels associated with the PWM controller but only one clock â€“ clk_pwm â€“ thus the clock settings used for clk_pwm apply to both PWM channels.</p>

<p>As it happens both PWM channels are used by the Raspberry Pi for stereo audio â€“ using one PWM channel per audio channel. PWM0 can also be accessed for other purposes on GPIO pin 18 via pin 12 of the P1 connector. Of course using PWM for other things will most likely mess up the Raspberry Piâ€™s audio output.</p>

<p>The PWM peripheral has modes of usage I decided not to support: serialiser mode for a start. Other were DMA (direct memory access â€“ an intriguing possibility â€“ maybe one day) and FIFO buffering. I also decided to set certain other options to fixed values such as not to use inverted polarity and to only use the standard PWM sub-mode (the alternative so-called MS mode seemed like a half-way house between serialiser mode and standard PWM mode). Again, support was available in <code>pwm_registers</code> but not used by <code>pwm_pin</code> â€“ other than to set the fixed feature values â€“ generally to off (<code>false</code>).</p>

<p>Like the clock peripherals there are multiple (well, two) PWM channels so the member functions of <code>pwm_registers</code> mostly require a parameter to specify the channel (the exception being those functions relating shared resources such as DMA or the FIFO buffer). Unlike the clock peripherals there is no repeated register structure: some registers contain sections for each channel while others relate to one channel or the other. Hence a <code>pwm_registers</code> auxiliary enumerated type <code>pwm_channel</code> is used as a channel identifier and the enumerated values used to select either the required register or the required part of a register.</p>

<p>The two attributes that did need to be user-set for each channel were the range and the data. Together these are used to define the duty cycle ratio of the PWM output. The range value defines the number of bits over which the duty cycle high/low ratio waveform is spread and repeated. The data value defines how many of the bits of the range will be high and the algorithm used by the PWM controller will try to spread these out as evenly as possible. Taking the example from the BCM2835 ARM Peripherals documentâ€™s PWM section, if 4 bits of a range of 8 (a ratio of 4/8 or 0.5) are to be high then the pattern would be:</p>

<pre class="programlisting">
  1 0 1 0 1 0 1 0
<p>Rather than:</p>
  1 1 1 1 0 0 0 0</pre>
  
<p>Or:</p>

<pre class="programlisting">
  1 1 0 0 1 1 0 0</pre>
  
<p>Each bit of the range would be used to set the high/low state of the associated GPIO pin changing from one bitâ€™s state to the next on each clock â€˜tickâ€™, as provided by clk_pwm which should run at a reasonably high frequency â€“ it is set to a default of 100 MHz by the hardware. </p>

<p>The handling of clk_pwm is split between <code>pwm_pin</code> and <code>pwm_ctrl</code>. The <code>pwm_pin</code> class provides static member functions to work with clk_pwm with the <code>pwm_pin::set_clock</code> member function performing a similar function to the constructor of <code>clock_pin</code>, but does not require a <code>pin_id</code> value as clk_pwm is never mapped to a GPIO pin. The other three functions provided are:</p>

<ul>
	<li><code>pwm_pin::clock_frequency_min</code></li>
	<li><code>pwm_pin::clock_frequency_avg</code></li>
	<li><code>pwm_pin::clock_frequency_max</code></li>
</ul>

<p>They return the values for the frequencies used by pwm_clk in the same fashion as:</p>

<ul>
	<li><code>clock_pin::frequency_min</code></li>
	<li><code>clock_pin::frequency_avg</code></li>
	<li><code>clock_pin::frequency_max</code></li>
</ul>

<p>The low level details of setting up the clock that require access to <code>clock_ctrl</code> are delegated to <code>pwm_ctrl::set_clock</code> â€“ an additional piece of functionality for the <code>pwm_ctrl</code> singleton type in addition to the <code>phymem_ptr&lt;volatile pwm_registers&gt;</code> and <code>simple_allocator</code> specialisation for the two PWM channels.</p>

<p>Setting pwm_clk up in the same fashion as the <code>clock_pin</code> usage example would look like so:</p>

<pre class="programlisting">
  pwm_pin::set_clock(rpi_oscillator,
    clock_frequency{kilohertz{600},
    clock_filter::none });</pre>
	
<p>which has the same parameters as the <code>clock_pin</code> object construction example less the initial <code>pin_id</code> parameter.</p>

<p>Where a <code>pin_id</code> is required â€“ unsurprisingly â€“ is in the construction of <code>pwm_pin</code> instances to specify which pin we want PWM output on. Details of which PWM channel (if any) and which alternate function of the GPIO pin is used for the PWM function being asked of a <code>pin_alt_fn::select </code>function. The other <code>pwm_pin</code> constructor parameter is an unsigned integer range value, defaulting to a value of 2400 â€“ a fairly long range value which is divisible by quite a few values. Hence the only value needed to construct a <code>pwm_pin</code> object is a <code>pin_id</code>:</p>

<pre class="programlisting">
  pwm_pin pwm{gpio_gen1};</pre>
  
<p>where <code>gpio_gen1</code> yields a <code>pin_id</code> value for GPIO pin 18 available on pin 12 of the Raspberry Pi P1 connector. </p>

<p>Now we have a <code>pwm_pin</code> object we can start and stop the PWM output, check whether it is running or not and set the ratio. The first three are simple to use and to implement:</p>

<pre class="programlisting">
  assert(!pwm.is_running());
  pwm.start();
  ...
  assert(pwm.is_running());
  ...
  pwm.stop();
  ...
  assert(!pwm.is_running());</pre>
  
<p>The <code>set_ratio</code> operation, although easy to use is more interesting in its implementation. There are two forms, one that takes a <code>double</code> floating point value and another that takes a <code>pwm_ratio</code> value. </p>

<p>Before getting into <code>pwm_ratio</code> letâ€™s first look at the overload taking a <code>double</code>. The value should be in the range [0.0, 1.0], with values outside this range throwing a <code>std::out_of_range exception</code>. The value is used to calculate the proportion of the range value to set for the PWM channelâ€™s data register value with a value of 0.0 producing low values for the whole range, and a value of 1.0 all high values. For example the output could be set to be high for a quarter of the time like so:</p>

<pre class="programlisting">
  pwm.set_ratio(0.25);</pre>
  
<p>I thought it would be nice to be able to express setting the ratio as a ratio. So <span clsss="filename">pwm_pin.h</span>
 includes a <code>pwm_ratio</code> class template, specialised by an integer type and a <code>std::ratio</code> specialisation (or similar type). Instances of specialisations of <code>pwm_ratio</code> hold a count value of the template integer parameter type, and define <code>static constexpr</code> values <code>num</code> (numerator) and <code>den</code> (denominator) equal to those values of the <code>std::ratio</code> specialisation template parameter type. For example for 0.3 count could be 3 with <code>num</code> and <code>den</code> set from a  <code>std::ratio</code> with <code>num</code> 1 and <code>den</code> 10 as per <code>std::deci</code>, or maybe count is 30 with <code>num</code> and <code>den</code> from a <code>std::ratio</code> with <code>num</code> 1 and <code>den</code> 100 as per <code>std::centi</code>. I also defined a set of type aliases for <code>pwm_ratio</code> specialisations for ratios as numbers of tenths (<code>pwm_tenths</code>), hundredths (<code>pwm_hundredths</code>), thousandths (<code>pwm_thousandths</code>) and millionths (<code>pwm_millionths</code>).</p>
 
<p>The other form of the <code>set_ratio</code> operation is a member function template that takes a <code>pwm_ratio</code> specialisation, and hence requires the same template parameters as <code>pwm_ratio</code>. Using a ratio to set the PWM output to be high 25% of the time would look like this:</p>

<pre class="programlisting">
  pwm.set_ratio(pwm_hundredths(25));</pre>
  
<p>Figure 3 shows the output of PWM0 using a 600 KHz clock, range of 2400 and a high ratio of 25% as observed by connecting GPIO pin 18 to the input of an oscilloscope this time using a time-base of is 2 ÂµS per division.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/cvu27-4/McArdell/McArdell-03.jpg" /></td>
	</tr>
	<tr>
		<td class="title">Figure 3</td>
	</tr>
</table>

<h2>References</h2>

<p class="bibliomixed"><a id="[1]"></a>[1]	Raspberry Pi Linux User Mode GPIO in C++ â€“ Part 1, <em>CVu</em>, Volume 27 Issue 2, May 2015</p>

<p class="bibliomixed"><a id="[2]"></a>[2]	dibase-rpi-peripherals library project:<a href="https://github.com/ralph-mcardell/dibase-rpi-peripherals">https://github.com/ralph-mcardell/dibase-rpi-peripherals</a></p>

<p class="bibliomixed"><a id="[3]"></a>[3]	See for example:<a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization">http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization</a></p>

<p class="bibliomixed"><a id="[4]"></a>[4]	Raspberry Pi Linux User Mode GPIO in Python, <em>CVu</em>, Volume 27 Issue 1, March 2015</p>

<p class="bibliomixed"><a id="[5]"></a>[5]	dibase-rpi-python library project:<a href="https://github.com/ralph-mcardell/dibase-rpi-python">https://github.com/ralph-mcardell/dibase-rpi-python</a></p>

<p class="bibliomixed"><a id="[6]"></a>[6]	Documentation/gpio.txt in the Linux kernel tree, as located at: <a href="https://github.com/raspberrypi/linux/blob/rpi-3.2.27/Documentation/gpio.txt">https://github.com/raspberrypi/linux/blob/rpi-3.2.27/Documentation/gpio.txt</a></p>

<p class="bibliomixed"><a id="[7]"></a>[7]	pselect man page, for example at: <a href="http://linux.die.net/man/2/pselect">http://linux.die.net/man/2/pselect</a> </p>

<p class="bibliomixed"><a id="[8]"></a>[8]	BCM2835 ARM Peripherals:<a href="http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">http://www.raspberrypi.org/wp-content/uploads/2012/02/BCM2835-ARM-Peripherals.pdf</a></p>

<p class="bibliomixed"><a id="[9]"></a>[9]	Pulse width modulation:<a href="https://en.wikipedia.org/wiki/Pulse-width_modulation">https://en.wikipedia.org/wiki/Pulse-width_modulation</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
