<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Richard Youngkin on Medium]]></title>
        <description><![CDATA[Stories by Richard Youngkin on Medium]]></description>
        <link>https://medium.com/@RichYoungkin?source=rss-80d16197df23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EGwgQ_yH6iGong-1CUjY3g.jpeg</url>
            <title>Stories by Richard Youngkin on Medium</title>
            <link>https://medium.com/@RichYoungkin?source=rss-80d16197df23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:24:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@RichYoungkin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Raspberry Pi GPIO — Using SPI to display arbitrary patterns on a MAX7219 Dot Matrix Display Module]]></title>
            <link>https://medium.com/better-programming/raspberry-pi-gpio-using-spi-to-display-arbitrary-patterns-on-a-max7219-dot-matrix-display-module-34a269f35c60?source=rss-80d16197df23------2</link>
            <guid isPermaLink="false">https://medium.com/p/34a269f35c60</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[makers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Richard Youngkin]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 15:06:05 GMT</pubDate>
            <atom:updated>2022-04-27T21:54:19.280Z</atom:updated>
            <content:encoded><![CDATA[<h3>Raspberry Pi GPIO — Using SPI to display arbitrary patterns on a MAX7219 Dot Matrix Display Module</h3><h4>Learn how to use SPI peripherals on a Raspberry Pi</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGB8U41I51ESkddsuPuxAw.png" /><figcaption>Image Credit: <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.6_led_dot_matrix_c.html">Sunfounder</a></figcaption></figure><h3>Overview</h3><p>This is the seventh article in a series that explores <a href="https://youngkin.github.io/categories/gpio/">GPIO programming on a Raspberry Pi</a>. It describes how to control Serial Peripheral Interface (SPI) peripherals such as the <a href="https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf">MAX7219 LED Dot Matrix Display Module</a>.</p><p>There are 2 approaches to reading this article. The first is to focus only on the SPI and dot matrix display aspects of the article by skipping the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#controlling-the-max7219---direct-interaction-with-the-bcm2835">Controlling the MAX7219 — direct interaction with the BCM2835</a> section. The second approach involves also learning how to control SPI peripherals by directly accessing the SPI register set instead of using a 3rd party library. This requires reading the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#controlling-the-max7219---direct-interaction-with-the-bcm2835">Controlling the MAX7219 — direct interaction with the BCM2835</a> section.</p><p>If the second approach is taken, then the <a href="https://youngkin.github.io/post/gpioprogramming/">Raspberry Pi GPIO — Introduction To Programming Broadcom BCM2835 ARM Peripherals</a> article should be considered a prerequisite of this article. That article introduces key techniques for directly controlling peripherals connected to the BCM2835, or more generally, the GPIO interface on the Raspberry Pi. Those key concepts include:</p><ul><li>BCM2835 I/O functions</li><li>BCM2835 addressing</li><li>Using BCM2835 registers</li></ul><p>If all you’re interested in is learning SPI without learning the details of programming the BCM2835 then the first approach is best.</p><p>The following topics will be covered:</p><ol><li><strong>Prerequisites</strong> — describes the hardware and software libraries you’ll need for this article.</li><li><strong>Overview of the Serial Peripheral Interface (SPI)</strong> — provides an introduction to the SPI protocol and the MAX7219 Dot Matrix Display Module.</li><li><strong>Using the BCM2835 board to control the MAX7219 Dot Matrix Display Module</strong> — provides the details, including code, for controlling the MAX7219. It also includes a subsection that describes directly interacting with the SPI register set on the BCM2835.</li><li><strong>Summary</strong> — summarizes the important concepts covered in this article.</li><li><strong>References</strong> — provides a list of references I found helpful and some that were used in the creation of this article.</li></ol><h3>Prerequisites</h3><p>If you don’t have one, you’ll need a Raspberry Pi. I used a Raspberry Pi 3B+ with the ‘stretch’ or later version of the Raspbian OS. The BCM2835 library referenced below supports Raspberry Pi models 1 through 4.</p><p>Next you’ll need is a <a href="https://www.amazon.com/dp/B082KBF7MM/ref=sspa_dk_detail_4?psc=1&amp;pd_rd_i=B082KBF7MM&amp;pd_rd_w=1tGTV&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=fX8JB&amp;pf_rd_r=44DE0RS1E9FD42RBYC7R&amp;pd_rd_r=47cbdc7f-7834-455f-9429-ef74a438bd45&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFVVkdZVUZRNUw3ODkmZW5jcnlwdGVkSWQ9QTA4MzI4MzYyU0VLNzBJM0cxRUVMJmVuY3J5cHRlZEFkSWQ9QTA0Mjk1NTMzSzNSWlNFUjU0NURBJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">breadboard</a>, some <a href="https://www.amazon.com/dp/B08HZ26ZLF/ref=syn_sd_onsite_desktop_19?psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUExRFpLWElCRjg1MUNMJmVuY3J5cHRlZElkPUEwMjMyMTE1M01aOFE3U1BQS09YSiZlbmNyeXB0ZWRBZElkPUEwODE5NTMxMktEMTlZRjEyQjBJNiZ3aWRnZXROYW1lPXNkX29uc2l0ZV9kZXNrdG9wJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">jumper wires</a>, and a <a href="https://www.amazon.com/dp/B07VM6HXN5/ref=sspa_dk_detail_5?pf_rd_p=0c758152-61cd-452f-97a6-17f070f654b8&amp;pd_rd_wg=wF4pR&amp;pf_rd_r=8MBD40495EV7X8RR61NP&amp;pd_rd_w=A5eiC&amp;pd_rd_r=281b8d49-a176-4535-bc99-bd6108f5bc24&amp;s=toys-and-games&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUE1NDJPSEtMOFRCWjImZW5jcnlwdGVkSWQ9QTA4MTEwODgyN0lZRFdWVkhIOFRaJmVuY3J5cHRlZEFkSWQ9QTA4NzU0NjYyQkE5UTNXTzM3SjIwJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ&amp;th=1">MAX7219 Dot Matrix Display</a>. You should also consider getting a <a href="https://www.amazon.com/dp/B082PRVRYR/ref=sspa_dk_detail_2?psc=1&amp;pd_rd_i=B082PRVRYR&amp;pd_rd_w=8mKhr&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=e9psa&amp;pf_rd_r=S09F37DF2G5FW8B8GX4B&amp;pd_rd_r=c065c120-e60b-45e9-b93b-f581f048cf46&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFCMzhUQ09COFI2VlMmZW5jcnlwdGVkSWQ9QTA5NjU2ODUxRDkxNEYwSTYwV09KJmVuY3J5cHRlZEFkSWQ9QTAxOTg1MTUyRUhEUlc2VzQ2VDQ4JndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">40 pin female to female with a T-Type adapter</a> to attach the GPIO outputs to the breadboard. You can use only jumper wires, but the adapter will make things easier and will help prevent damage to the GPIO pins on the Raspberry Pi. If you elect not to buy the 40 pin cable with T-Type adapter you’ll need to buy <a href="https://www.amazon.com/SinLoon-Breadboard-Arduino-Circuit-40-Pack/dp/B08M3QLL3Q/ref=pd_sbs_7/143-0445142-7950409?pd_rd_w=sVLrc&amp;pf_rd_p=8b76d7a7-ab83-4ddc-a92d-e3e33bfdbf03&amp;pf_rd_r=CDM5TGJT03VKF0ZFB577&amp;pd_rd_r=8e58fd82-8503-41cf-b8f2-c78eaeb78d25&amp;pd_rd_wg=tT1U0&amp;pd_rd_i=B08M3QLL3Q&amp;psc=1">male-to-female jumper wires</a>. However, a full electronics kit for a Raspberry Pi doesn’t cost much more than these 4 components. I recommend buying the <a href="https://www.amazon.com/gp/product/B09BMVT4CB/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&amp;psc=1">Sunfounder Raspberry Pi Ultimate Starter Kit</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r2Jg7oGOPLPhTkMH.png" /></figure><p><em>Sunfounder Ultimate Starter/Raphael kit</em></p><p>You will need some basic C programming knowledge as well as familiarity with logging on to a Raspberry Pi terminal, or into the desktop GUI that comes with some OS versions. Depending on the approach you take, you may need to connect a keyboard and monitor to the Raspberry Pi. I simply SSH into the Pi. You’ll also need familiarity with how to use an editor like Vi or nano. And you’ll need basic familiarity with the Linux command line.</p><p>Finally, you’ll need to clone or fork <a href="https://github.com/youngkin/gpio">my GPIO repository</a> as it contains underlying library code used to access GPIO capabilities on the BCM2835. As mentioned in other sections, this library code is based on the <a href="http://www.airspayce.com/mikem/bcm2835/index.html">BCM2835 C library</a> developed by Mike McCauley.</p><h3>SPI (Serial Peripheral Interface) Overview</h3><p>SPI is used to send data serially to a peripheral that can accept or requires data in parallel. This is helpful because a relatively large set of parallel inputs can be written to using just 3 GPIO pins, excluding the power (VCC) and ground (GND) pins. If SPI wasn’t used, one GPIO pin would be required for each parallel input. This could easily be prohibitive since pins are a limited resource. Let’s see how this works with an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/0*v-uoijC1PM0c48SO.jpg" /><figcaption><em>Image credit: Author</em></figcaption></figure><p>The diagram above shows the MAX7219 LED Dot Matrix Display. It’s commonly used to display display arbitrary shapes such as letters, numbers, and smiley faces. In addition to the MAX7219, SPI can be used to control a variety of peripherals to display images, take input from touchscreens, and interact with various sensors. <a href="https://en.wikipedia.org/wiki/Serial_Peripheral_Interface">Wikipedia has a good article</a> describing SPI in more detail.</p><p>The MAX7219 controls an 8x8 matrix of LEDs. Controlling an LED requires 1 pin excluding power or ground. An 8x8 LED matrix has 64 LEDs. This number is well in excess of the 26 or 40 GPIO pins available on a standard Raspberry Pis. As explained below, utilizing SPI requires considerably fewer GPIO pins.</p><p>The MAX7219 has the following input pins:</p><ol><li>DIN — this is the serial data input pin.</li><li>CS — This is commonly called a chip select (CS) or chip enable (CE) pin, or occasionally slave select (SS).</li><li>CLK — This pin connects to a clock pin on the Raspberry Pi that synchronizes data transfers between the Raspberry Pi and the MAX7219.</li></ol><p>There are 2 more pins that aren’t used to control the MAX7219.</p><ol><li>VCC — This is the power-in pin. It connects to a power source on the Raspberry Pi, usually a 5 volt source.</li><li>GND — This is the ground pin. It connects to a ground pin of the Raspberry Pi.</li></ol><p>A minimum of 3 GPIO pins are required to connect from the Raspberry Pi to the MAX7219, specifically to the DIN, CS, and CLK pins. A Raspberry Pi can control all 64 LEDs in a cost efficient (pin-wise) manner using only these three pins. The usual approach is to use the SPI specific Raspberry Pi pins that can drive the DIN, CS, and CLK pins. These 3 pins are named:</p><ol><li>(SPI)MOSI — This stands for Master Out Slave In. The MOSI pin will be connected to the MAX7219 DIN pin and is used to send a serial data signal to the MAX7219 (or any SPI peripheral).</li><li>(SPI)SCLK — This stands for SPI Clock. This pin will be connected to the MAX7219 CLK pin. It is used as the source of the clock signal used to synchronize the data transfer between the BCM2835 and the MAX7219 (or any SPI peripheral). The data transfer will occur when both the MOSI pin and the SCLK pin are set to HIGH.</li><li>(SPI)CS or (SPI)CE — These stands for Chip Select or Chip Enable. In either case, setting the pin to LOW directs the MAX7219 to accept data as described in the previous bullet.</li></ol><blockquote>I reluctantly use the terms “master” and “slave”. However these terms are used in all of the documents I’ve read on SPI. I’ll continue to use them in order to avoid confusion.</blockquote><p>The SPI capability on the Raspberry Pi may require as many as 5 GPIO pins. The 2 additional pins are:</p><ol><li>(SPI)MISO — This stands for Master In Slave Out. This pin allows for the MAX7219 (or any SPI peripheral) to send data back to the BCM2835.</li><li>(SPI)CS or (SPI)CE — This is a second chip select/chip enable pin. Having a second CS/CE pin allows the BCM2835 to control 2 SPI peripherals. As stated above, when the CS/CE pin is set to LOW the SPI peripheral will accept data from the BCM2835. So by setting one of the CS/CE pins to HIGH and the other to LOW we can control which slave can receive and send data.</li></ol><p>The article <a href="https://adikedia.com/2016/08/10/using-multiple-spi-slave-devices-with-wiringpi/">Using Multiple SPI Slave Devices with the Raspberry Pi</a> provides more information about how the 2 CE/CS pins are used. The following schematic illustrates how utilize 2 CE/CS pins:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*ey8BNroWU7kE9wOP.jpg" /><figcaption><em>Image credit: BCM2835 ARM Peripherals Guide</em></figcaption></figure><p>In the image above this schematic you may have noticed the 5 pins on the right-hand side of the MAX7219. These pins output the signals on the corresponding input pins to other MAX7219s. This allows more than two MAX7219s to be “chained” together to create larger displays, e.g., 128 LED or 256 LED displays. This process is called daisy-chaining. This can be done by connecting the output pins on the primary SPI peripheral to the corresponding input pins on the next peripheral in the chain. Daisy chaining can be used to display multiple characters on a logically larger LED matrix, or to create scrolling displays. This <a href="https://forum.arduino.cc/t/daisy-chaining-multiple-max7219-chips/3305">Arduino forum thread</a> provides a high level explanation about how to accomplish this. <a href="https://thesolaruniverse.wordpress.com/2016/05/10/news-ticker-with-three-max7219-8x8-dot-led-matrix-devices/">News ticker with three MAX7219 8×8 dot led matrix devices</a> is the best article I could find for implementing a specific project. However, it describes how to accomplish this with a Sketch (a way to write Python based code snippets), not C. Between these 2 sources there might be enough hints about how to accomplish this using C. I may write a future article that describes how to do this in C.</p><blockquote>It is possible to <a href="https://www.amazon.com/HiLetgo-MAX7219-Arduino-Microcontroller-Display/dp/B07FFV537V/ref=sr_1_9?crid=DWVTBTEX09G8&amp;keywords=8x64+led+matrix+module&amp;qid=1650744886&amp;sprefix=8x64+led+matrix+module%2Caps%2C117&amp;sr=8-9">purchase LED matrix modules that are larger than 8x8</a> which avoids having to manually daisy-chain multiple devices.</blockquote><p>The primary SPI interface on the BCM2835, SPI0, is implemented on GPIO pins 7–11. Pins 7 &amp; 8 are the 2 CE/CS pins available on the BCM2835. Pin 9 is MISO, 10 is MOSI, and 11 is the clock (SPICLK/SCLK). The BCM2835 has 2 auxilary SPI interfaces, SPI1 (AKA AUX_SPI0) and SPI2 (AKA AUX_SPI1). From the BCM2835 ARM Peripherals Guide, SPI1 is available on pins 16–21 and SPI2 on pins 35–39. These auxilary interfaces are available via the AUX I/O function.</p><p>The following diagram shows a GPIO extension board frequently used to connect the BCM2835 GPIO pins to a breadboard. The pins are labeled with their GPIO pin numbers or the I/O function (e.g., SPI) they support. Note the SPI pins are labeled on the board using the same terms as above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/0*7s_2SnecfjRJ2Kk8.jpg" /><figcaption>Image Credit: Sunfounder</figcaption></figure><p>The following is a timing diagram that shows the actual signals being sent to the MAX7219 dot matrix display. It’s a screenshot from the <a href="https://sigrok.org/wiki/PulseView">PulseView/sigrok logic analyzer</a> application. I used an inexpensive <a href="https://www.amazon.com/dp/B07K6HXDH1?psc=1&amp;ref=ppx_yo2ov_dt_b_product_details">logic analyzer device</a> to capture the signals displayed in PulseView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NQPU7BLaba1vT71y.jpg" /><figcaption><em>Image credit: Author</em></figcaption></figure><p><em>(To better see the image above, open it in a separate tab and zoom in on it)</em></p><p>This diagram shows the values for the first 3 rows of the LED matrix for the letter “Y”. Here’s how to interpret it:</p><ol><li>There are 5 rows/lines going across from left to right labeled CS0, MOSI, SCLK, MAX7219/SPI MOSI bits, and MAX7219/SPI MOSI data. The top three lines are the actual digital signals. Spikes indicate a HIGH signal. The bottom 2 lines are a SPI specific decoding from the 3 line signals above. MAX7219/SPI MOSI bits displays the bit values, 0 (LOW) or 1 (HIGH), associated with the signals above. MAX7219/SPI MOSI data represents the hexidecimal values for the bit values above.</li><li>CS0 is the chip select line. It’s hard to see, but at the far left of the diagram it starts out set to HIGH. It’s set to LOW where the vertical line appears. This indicates the data transmission to the SPI peripheral attached to CS0 is about to start. While this signal is set to LOW the following happens:</li><li>The SCLK line pulses between HIGH and LOW 16 times while CS0 is set to LOW. This is the timing signal that, when set to HIGH, indicates to the SPI peripheral to accept the current value on the MOSI line.</li><li>For the first 7 pulses of SCLK the MOSI line is set to LOW. Just prior to the 8th pulse the MOSI line is set to HIGH.</li><li>The MAX7219/SPI MOSI bits line shows the binary interpretation of the combination of the SCLK and MOSI lines. Consistent with the first 7 pulses of the SCLK line the MOSI line is interpreted as zeros (0). The 8th bit is interpreted as a 1. So the binary value of the 8 bits sent is 0000 0001.</li><li>The MAX7219/SPI MOSI data line shows the hexidecimal interpretation which is 0x1.</li></ol><p>The second 8 bits sent while the CS0 line is set to LOW are 0100 0001 which is the hex number 0x41.</p><p>The MAX7219 shift register is 16 bits wide. So each data transmission consists of 16 bits, which is what we see in the timing diagram above. 16 bits are transmitted while the CS0 line is set to LOW. For the MAX7219 the first 8 bits are the address of the register that will be set. The value used to populate this register is sent in the next 8 bits. So this first data transmission sets the the register located at offset 0x1 to the value 0x41. The register at offset 0x1 controls the first/top row of the dot matrix module. Notice that there are 8 LEDs in each row. Each LED corresponds to a bit in the binary value contained in the register. That value is 0x41, 0100 0001, which will cause the first row of the LED to look like this (-s are 0, *s are 1):</p><pre>-*-----*</pre><p>The next set of 8 bits is 0000 0010 which equates to 0x2. So the value in the 2nd 8 bits will be written to the register at offset 0x2, which corresponds to the 2nd row of 8 LEDS in the dot matrix display. The binary value of the next 8 bits is 0010 0010. The target register will be set to this value. After this transmission the first 2 rows of the LED matrix look like this:</p><pre>-*-----*<br>--*---*-</pre><p>And the next set of 16 bits have the values 0000 0011 and 0001 0100. The first 8 bits are the address of the target register. Which, following the pattern above, specifies the target register is at offset 0x3 which corresponds to the 3rd line of the LED matrix. After the second 8 bits are written to the register the LED matrix will look like this:</p><pre>-*-----*<br>--*---*-<br>---*-*--</pre><p>The next 5 sets of 16 bits, not shown in the diagram above, specify registers 0x4 through 0x7, corresponding to the remaining rows of the LED matrix. The values written to those registers, 0000 1000, result in the following pattern which represents the letter “Y”.</p><pre>-*-----*<br>--*---*-<br>---*-*--<br>----*---<br>----*---<br>----*---<br>----*---<br>----*---</pre><p>The next section will provide some additional details about the SPI protocol and how to program the MAX7219.</p><h3>Setup and Code</h3><p>The diagram below illustrates how to wire the breadboard to work with the MAX7219 LED dot matrix module example. If you’re unfamiliar with breadboards and breadboard diagrams this <a href="https://www.sciencebuddies.org/science-fair-projects/references/how-to-use-a-breadboard">breadboard tutorial</a> should be helpful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7f64P7s_-S9m3Xaz.png" /><figcaption><em>Image credit: Sunfounder</em></figcaption></figure><p>The yellow wire is connected to the SPIMOSI pin (GPIO pin 10) on the Raspberry Pi and the DIN pin on the MAX7219. The blue wire is connected to SPISCLK or SCLK (GPIO pin 11) on the Raspberry Pi and the CLK pin on the MAX7219. The green wire is connected to SPICE0 or CE0 (GPIO pin 8) on the Raspberry Pi and the CS pin on the MAX7219. The red and black wires are connected to 5 volt power/VCC and ground/GND respectively.</p><p>The next section will describe the main program that controls the MAX7219. The section following that describes the code that directly controls the I/O functions using the BCM2835 registers.</p><h3>Controlling the MAX7219 — main program</h3><p>I mentioned earlier that there are 2 approaches to reading this article. The first approach, the simplist, just involves reading this section. The next section, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#controlling-a-dot-matrix-display---interacting-with-the-bcm2835">Controlling a dot matrix display — interacting with the BCM2835</a>, is more advanced and may be skipped.</p><p>The code in this section and the next references functions prefixed by bcm_. All of these functions, with very minor changes, were taken from the <a href="https://www.airspayce.com/mikem/bcm2835/index.html">BCM2835 C Library</a> written by Mike McCauley. When using that library with this code simply substitute all instances of bcm_with bcm2835_. The bcm_ funcs were created so I could add explanatory comments and to make the BCM2835 code more easily accessible in this article. The bcm_ functions are described in more detail in the following section.</p><h4>Global variables</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a39edc0e0c10ffb4b9c52259700bb1d/href">https://medium.com/media/8a39edc0e0c10ffb4b9c52259700bb1d/href</a></iframe><p>This first code snippet shows how to create a character to be displayed on the MAX7219 dot matrix display module. The 2 dimensional matrix disp1 contains a set of rows, NUM_CHARS, each of which define a particular character to be displayed. Each column in the matrix, MATRIX_ROW, defines which LEDs in a single MAX7219 LED row to turn on in the dot matrix display module. The MAX7219 display module is an 8X8 array of LEDs. In the code snippet above the matrix contains 3 rows with 8 columns. The first cell at disp1[0][0] contains the hex value 0x3C. This defines which LEDs to turn on in the first row, of 8 rows, of the display module. 0x3C translates to 0011 1100. Each digit specifies which LED in the row will be turned on. 0x3C specifies that the middle 4 LEDs in the first row of 8 LED rows will be turned on. disp[0][1] contains the hex value 0x42 which converts to the binary number 0100 0010 which specifies that the 2nd and 7th LEDs in the second row of 8 LED rows will be turned on. The dot matrix display will look like this after these 2 cells are displayed:</p><pre>--****--<br>-*----*-</pre><p>LED cells with -s are turned off, cells with *s are turned on. Once all 8 cells from disp1[0][0] to disp1[0][7] are displayed the following character, a zero, will be displayed on the dot matrix module:</p><pre>--****--<br>-*----*-<br>-*----*-<br>-*----*-<br>-*----*-<br>-*----*-<br>-*----*-<br>--****--</pre><p>The remaining disp1 rows define the rest of the characters and shapes that will be displayed by the program.</p><p>The <a href="http://robojax.com/learn/arduino/8x8LED/">Sprint Generator for LED Matrix 8x8</a> is a tool that helps generate the hex numbers needed to cause an LED matrix to display a given shape.</p><h4>main()</h4><p>This next code snippet shows the code for the main function. Each of the significant lines will be explained below the snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c180155875807c1ca69d213fbea6a0c9/href">https://medium.com/media/c180155875807c1ca69d213fbea6a0c9/href</a></iframe><p><strong>Line 1</strong> explains that the GPIO pins are hardcoded. This is because the program is using the SPIO interface. The other 2 interfaces, SPI1and SPI2 are auxilary SPI interfaces. Section 2.3, page 20, of the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">The BCM2835 ARM Peripherals guide</a> states the following:</p><blockquote>The two universal SPI masters are secondary low throughput SPI interfaces. … The universal SPI master has been developed to work even with the most ‘non-standard’ SPI devices.</blockquote><p>Reading between the lines, ‘secondary’, low-throughput’ and ‘non-standard’ don’t seem to be attributes we want to work with. The <a href="https://www.airspayce.com/mikem/bcm2835/index.html">BCM2835</a> library, which is the basis for the code presented in this article, supports SPI0 as the primary interface. It has auxilary functions to support the SPI1 interface, and no functions to support SPI2. Given all this I elected to hard-code the SPI0 interface. Note, the BCM2835 ARM Peripherals guide specifies that GPIO pins 7-11 are dedicated to SPI0 when the ALT0 function is specified.</p><p><strong>Line 3</strong> defines a signal handler to provide graceful shutdown of the application if it is killed (e.g., ^C).</p><p><strong>Line 8</strong>, the call to <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init()</a>, initializes the the BCM2835. Among other things, it finds the appropriate memory offsets for the I/O peripheral’s address space and maps /dev/mem so that it is usable for programming the I/O functions. bcm_init() is a low-level function that will be described in detail in the next section, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#controlling-a-dot-matrix-display---interacting-with-the-bcm2835">Controlling a dot matrix display - interacting with the BCM2835</a>.</p><p><strong>Line 13</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#init_spi">init_spi()</a>, initializes the SPI interface which includes setting the I/O function on the GPIO pins to ALT0 (enables SPI0).</p><p><strong>Line 14</strong>, Delay_xms(50);, causes a short delay, 50ms, to give the spi interface time to complete initializing.</p><p><strong>Line 15</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#init_max7219">Init_MAX7219()</a>, initializes the MAX7219 display module. Among other things it sets the brightness of the display. Like the BCM2835, its functionality is controlled by a set of registers. Comments in the function definition below provide additional information about what it does.</p><p><strong>Lines 18–37</strong> are the heart of the main function. For each row in the disp1 and scrollDisp arrays, it writes an entire row’s values to the display module resulting in a character being displayed (e.g., 0). <strong>Lines 29-36</strong> demonstrate how to create a simple scrolling display.</p><p><strong>Lines 40 ad 41</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_spi_end">bcm_spi_end()</a> and <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_close">bcm_close()</a> reset the BCM2835 GPIO functionality and release resources (e.g., /dev/mem).</p><h4>init_spi()</h4><p>This code snippet shows how the SPI interface is initialized.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28e331ef815f1cef5b25cbe404c38a56/href">https://medium.com/media/28e331ef815f1cef5b25cbe404c38a56/href</a></iframe><p><strong>Line 4</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_spi_begin">bcm_spi_begin()</a>, is another low level function that interfaces with the BCM2835. As the comments state, it’s responsible for setting GPIO pins 7–11 to alternate function 0, which for those pins, enables the SPI0 interface. It’ll be covered in more detail in the next section.</p><p><strong>Line 6</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_spi_setbitorder">bcm_spi_setBitOrder()</a>, is more complicated depending on whether you understand the concept of most significant and least significant bit ordering (MSB and LSB). Simplistically, the most significant bit in a binary number is the left-most bit. Likewise the least significant bit in a binary number is the right-most bit. In the binary number 100 the MSB is 1 and the LSB is 0. What’s significant about this is when data is transferred serially bit ordering specifies which bit is sent first. In MSB the most significant bit is sent first. So thinking of the receiving end of a serial data transfer as a stack, the MSB gets pushed to the stack first. The rest of the bits are transferred moving from the MSB to the LSB. So if the number 100 is tranferred serially in MSB order it would be represented as 001 on the receiving end. Different devices expect data in either MSB or LSB.</p><p>It’s important to know what the device you’re interacting with expects with regard to bit order. The BCM2835 SPI0 expects bits in MSB. SPI1 and SPI2 can acccept either MSB or LSB as specified in bit 6 of the AUXSPI0/1_CNTL0 Register (see <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">the BCM2835 ARM Peripherals guide</a>, page 22–23 for details). bcm_spi_setBitOrder() allows the specification of either MSB or LSB. However, for SPI data transfers the data must be sent in MSB. So for SPI, this function is basically a no-op. For a visual representation of how data is transmitted to the MAX7219 see the <a href="https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf">MAX7219 datasheet</a>, <em>Functional Diagram</em>, at the bottom of page 5. At the very bottom-middle of the page there is a diagram of how data is transmitted via the DIN pin into the bit positions of the MAX7219’s internal shift register. At the last clock pulse (the CLK pin) the LSB is located in bit offset 0, D0 and the MSB is at bit offset 15, D15. If you’d like to see a more complete example of bit ordering see my article <a href="http://youngkin.github.io/post/shiftregistersevensegdisplay/#what-is-a-shift-register-and-what-is-it-good-for">Raspberry Pi GPIO in Go and C - Using a Shift Register &amp; 7 Segment Display</a>. It describes in detail how bit ordering is used in conjunction with a shift register. If you’d like more information on forcing the BCM2835 SPI interface to send data in LSB see this Google Groups thread on <a href="https://groups.google.com/g/bcm2835/c/9H6rDEKTru0?pli=1">BCM2835 SPI communication - LSB first</a>.</p><p><strong>Line 9</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_spi_setdatamode">bcm_spi_setDataMode(BCM_SPI_MODE0)</a> sets the clock polarity and phase. If you don’t understand what this means, just accept this setting and move on. It is the default in most cases. If you’d like more detail on this see <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">the BCM2835 ARM Peripherals guide</a>, section 10 — SPI, figure 10–3, on page 149.</p><p><strong>Line 10</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_spi_setclockdivider">bcm_spi_setClockDivider(BCM_SPI_CLOCK_DIVIDER_256)</a> sets the frequency of the SPI clock (SPISCLK, GPIO pin 11 on the Rasberry Pi). In a nutshell, the Raspberry Pi’s system clock is divided by the parameter in this function to set the frequency of the SPI clock. 256 is a good default value to use in most cases. See <a href="https://github.com/youngkin/gpio/blob/main/ledblink/bcmfuncs.h">bcmfuncs.h</a> or the <a href="https://www.airspayce.com/mikem/bcm2835/group__constants.html#gaf2e0ca069b8caef24602a02e8a00884e">BCM2835 C library documentation</a> for more details.</p><p><strong>Line 12</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_gpio_fsel">bcm_gpio_fsel()</a> sets the Max7219_pinCS pin, the SPICE0/GPIO pin 8, to the GPIO output function. This allows the program to write values, HIGH or LOW, to the pin. This is the SPI chip select/chip enable pin. This pin directs the MAX7219 to accept data from the Raspberry Pi. This pin needs to be set to LOW when sending data to the MAX7219. The bcm_gpio_fsel() function will be described in more detail below.</p><h4>Init_MAX7219()</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb1c4b6e8f460f7b1158952de760cd46/href">https://medium.com/media/cb1c4b6e8f460f7b1158952de760cd46/href</a></iframe><p>This code snippet initializes the MAX7219 display module. Like the BCM2835, the MAX7219’s capability is controlled via a set of registers. <strong>Lines 3 thru 9</strong> set the various control registers to various values.</p><p>Taking <strong>line 1</strong> as an example, it sets the MAX7219 register at offset 0x09 to the value 0x00. The first parameter in <a href="https://youngkin.github.io/post/spidotmatrixmodule/#write_max7219">Write_Max7219()</a>specifies the address offset of the register. The second parameter specifies the value to write to the register. The registers with their offsets are described in the <a href="https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf">MAX7219 datasheet</a>, <em>Table 2. Register Address Map</em>, on page 7. <em>Table 1. Serial Data Format</em> on page 6 describes how the data is laid out in each register. Each register is 16 bits long as described Table 1. There are 14 control registers. The name of each register is given in column 1 of Table 2 titled <em>Register</em>. The offset of each register is given in the <em>Hex Code</em> column. Looking again at the first argument to Write_Max7219(), 0x09, we can see that this address refers to the <em>Decode Mode</em> register which is at offset 0xX9 as given in the <em>Hex Code</em> column. The various LED rows associated with creating a character, symbol, or shape are controlled by registers <em>Digit 0</em> through <em>Digit 7</em>. The meaning of the values for each register, except the <em>Digitn</em> registers, are provided in tables 3, 4, 7, 8, and 10. The second paramater of Write_Max7219() is 0x00. Looking in table 4 we see this value means there is no decode set for digits 0-7.</p><p>In a similar manner, <strong>lines 4 thru 9</strong> will initialze the remaining registers as described in the comments.</p><h4>Write_Max7219()</h4><p>Write_Max7219() writes the data, dat1, to the register located at address, address1. Writes to the MAX7219 only take place a byte at a time. The first byte written is the register address. The second byte is the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99441e436891b16c40c4d542b4861ebb/href">https://medium.com/media/99441e436891b16c40c4d542b4861ebb/href</a></iframe><p><strong>Line 1</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_gpio_write">bcm_gpio_write()</a> uses the regular GPIO write method to set the chip select pin, Max7219_pinCS, to LOW so the MAX7219 will accept data from the Raspberry Pi.</p><p><strong>Line 6</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#write_max7219_byte">Write_Max7219_byte()</a>, sends the address1 parameter to the MAX7219. As shown in the <a href="https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf">MAX7219 datasheet</a>, <em>Functional Diagram</em>, at the bottom of page 5, the target register’s address will be written to bit offsets 8 thru 11 (as documented in the datasheet, bits 12 through 15 will be ignored).</p><p><strong>Line 7</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#write_max7219_byte">Write_Max7219_byte()</a>, sends the dat1 parameter to the MAX7219. The dat1 bits will be written to the least significant bits, offsets 0 thru 7, in the MAX7219 shift register.</p><p><strong>Line 8</strong>, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_gpio_write">bcm_gpio_write()</a>, resets the Max7219_pinCS pin back to HIGH to signal the end of the data transmission and to prevent the MAX7219 from accepting data.</p><h4>Write_Max7219_byte()</h4><p>Write_Max7219_byte() is pretty straightforward. It takes the data parameter and sends it to the SPI peripheral vi the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_spi_transfer">bcm_spi_transfer()</a> call. bcm_spi_transfer() will be covered in more detail below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e48581ebb1687b702a4f478982301308/href">https://medium.com/media/e48581ebb1687b702a4f478982301308/href</a></iframe><h3>Controlling the MAX7219 — direct interaction with the BCM2835</h3><p>This section describes how the code interacts with and controls the GPIO peripherals, specifically setting the values of the various registers associated with the SPI I/O functionality of the BCM2835. Setting register values is used to control GPIO peripherals and reading register values allow the current state of the associated GPIO peripherals to be accessed.</p><p>Many of these function descriptions are copied from the <a href="https://youngkin.github.io/post/gpioprogramming/">Raspberry Pi GPIO — Introduction To Programming Broadcom BCM2835 ARM Peripherals</a> article. This is done to avoid constant cross referencing back to that article.</p><p>The code for the file that contains this code can be found at <a href="https://github.com/youngkin/gpio/blob/main/ledblink/bcmfuncs.c">gpio/ledblink/bcmfuncs.c</a>. The associated header file can be found at <a href="https://github.com/youngkin/gpio/blob/main/ledblink/bcmfuncs.h">gpio/ledblink/bcmfuncs.h</a>.</p><h4>bcm_init()</h4><p>The <a href="https://youngkin.github.io/post/gpioprogramming/#registers">Registers in the Raspberry Pi GPIO</a> section in the <em>Introduction To Programming Broadcom BCM2835 ARM Peripherals</em> article mentions that all operations on BCM2835 peripherals are accomplished by manipulating the registers associated for that type of peripheral. The purpose of bcm_init() is to determine the address offsets for all the types of registers, e.g., GPIO, PWM, SPI, etc. so that the their associated peripherals can be controlled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23bbb32dbcf5e64c0e16747506730e31/href">https://medium.com/media/23bbb32dbcf5e64c0e16747506730e31/href</a></iframe><p>This snippet shows the beginning of the bcm_init() function.</p><p><strong>Line 10</strong> opens the BCM_RPI2_DT_FILENAME. As indicated in the comment, the rb in the fopen() call opens a binary file for reading. BCM_RPI2_DT_FILENAME is defined in the associated bcmfuncs.h header file. It’s value is /proc/device-tree/soc/ranges. As stated in <a href="https://www.kernel.org/doc/html/latest/devicetree/usage-model.html">Linux and the Devicetree</a>,</p><blockquote>An operating system used the Device Tree to discover the topology of the hardware at runtime, and thereby support a majority of available hardware without hard coded information (assuming drivers were available for all devices).</blockquote><p>One of the pieces of information the device tree holds, and is important for our purposes, is the location and length of the I/O Peripherals partition in the BCM2835’s physical address space (see <a href="https://youngkin.github.io/post/gpioprogramming/#addressing">Introduction To Programming Broadcom BCM2835 ARM Peripherals — Addressing</a>for details). Here’s a hex dump of the contents of /proc/device-tree/soc/ranges on a Raspberry Pi 3B+:</p><pre>pi@pi-node1:/ $ hexdump -C /proc/device-tree/soc/ranges<br>00000000  7e 00 00 00 3f 00 00 00  01 00 00 00 40 00 00 00  |~...?.......@...|<br>00000010  40 00 00 00 00 00 10 00                           |@.......|<br>00000018</pre><p>We’ll refer back to this in this next code snippet. Per <a href="https://www.devicetree.org/specifications/">devicetree.org</a>, in <a href="https://github.com/devicetree-org/devicetree-specification/releases/download/v0.4-rc1/devicetree-specification-v0.4-rc1.pdf">v0.4-rc1 of the Devicetree Specification</a>, the soc/ranges property is defined as follows:</p><blockquote>The ranges property provides a means of defining a mapping or translation between the address space of the bus (the child address space) and the address space of the bus node’s parent (the parent address space). The format of the value of the ranges property is an arbitrary number of triplets of (child-bus-address, parent-bus-address, length)</blockquote><p>In the case of the I/O Peripherals address block, as described in <a href="https://youngkin.github.io/post/gpioprogramming/#addressing">Introduction To Programming Broadcom BCM2835 ARM Peripherals — Addressing</a>, the <em>“child-bus-address”</em> refers to the <em>“I/O Peripherals”</em> address block in the <em>“VC CPU Bus Addresses”</em> memory space. The <em>“parent-bus-address”</em> refers to the the <em>“I/O Peripherals”</em> address block in the <em>“ARM Physical Addresses”</em> block. And the <em>“length”</em> refers to the actual length of the <em>“I/O Peripherals”</em> address block. The Raspberry Pi 3B+ has a 32 bit address space so each of the values in the triple are 32 bits or 4 bytes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bab28f9fc6d1f4311a2e86cfeaf9d2c2/href">https://medium.com/media/bab28f9fc6d1f4311a2e86cfeaf9d2c2/href</a></iframe><p>This next code snippet finds the <em>parent-bus-address</em> and <em>length</em> of the I/O peripherals block using the data from /proc/device-tree/soc/ranges. Recall that the parent bus address is the second entry in the triplet that also defines the child bus address and length. From the hex dump above, here is that triplet (array cell 0 is at the far left, array cell 11 is at the far right):</p><pre>7e 00 00 00 3f 00 00 00  01 00 00 00</pre><blockquote>Note: The output of the command is somewhat different on a Raspberry Pi 4. It will look more like this:</blockquote><blockquote>pi@kubemaster:~ $ hexdump -C /proc/device-tree/soc/ranges</blockquote><blockquote>00000000 7e 00 00 00 00 00 00 00 fe 00 00 00 01 80 00 00 |~……………|</blockquote><blockquote>In this dump the starting address of the parent bus address is at offset 8, the value is fe 00 00 00. For the Raspberry Pi 3 it’s at offset 4. In both cases the length of the the address is 4 bytes or 32 bits. The length of the I/O Peripherals partition starts at offset 12 and the value is 01 80 00 00. Although the code snippet above doesn’t reflect this difference, the code for the complete function does take this into account.</blockquote><p><strong>Lines 1 thru 4</strong> shift the contents of the <em>parent-bus-address</em>, 3f 00 00 00, the bytes at buf offsets 4 thru 7, into base_address. 3F is shifted into the high order byte of base_address. The remaining buf cells are likewise shifted into base_address from left (most significant) to right (least significant byte). After shifting is complete base_address will be set to 0x3F000000. Looking back at the diagram in <a href="https://youngkin.github.io/post/gpioprogramming/#addressing">Introduction To Programming Broadcom BCM2835 ARM Peripherals - Addressing</a> you’ll notice it <strong>DOESN’T MATCH</strong> the base address of 0x20000000 in the <em>I/O Peripherals</em> address block in <em>ARM Physical Addresses</em>. This is because the diagram in the Addressing section is for the Raspberry Pi 1. This offset is different in the Raspberry Pi models 2 &amp; 3. And it’s different yet again in the Raspberry Pi 4 model.</p><p>Moving on, in a similar manner to base_address, <strong>lines 6 thru 9</strong> get the <em>length</em> by shifting from buf offsets 8 thru 11 into peri-size. For the Raspberry Pi 3B+, 0x01000000 is the expected length of the address block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/330ff7d60d8ef57cf8b2c1214d0039df/href">https://medium.com/media/330ff7d60d8ef57cf8b2c1214d0039df/href</a></iframe><p>This next code snippet completes obtaining the addressing information from /proc/device-tree/soc/ranges. Specifically it validates that the <em>“child-bus-address”</em> and <em>“parent-bus-address”</em> have the expected values. Recall that the <em>“child-bus-address”</em> is the first value in the addresses/length triplet, buf offsets 0 thru 3. Lines 1 thru 6 do the following:</p><ol><li><strong>Lines 1 thru 4</strong> verify that the first 4 bytes of buf, the <em>child-bus-address</em>, is 0x7E000000 as defined by the <em>“I/O Peripherals”</em>address block in the <em>“VC CPU Bus Addresses”</em> memory space. We also saw this in the hex dump above where the first 32 bits, the <em>child-bus-address</em>, contained the value 7e 00 00 00.</li><li><strong>Line 5</strong> verifies that the <em>parent-bus-address</em>, base_address, matches one of the expected base addresses for Raspberry Pi models 1 thru 4.</li></ol><p><strong>Lines 7 and 8</strong> then set the base address and length of the <em>I/O Peripherals</em> address block to the variables that will be used in the rest of the program. The important thing about this line is that it casts the source variables to the types expected by the target variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5a713b59c38ef5445827616bed10ab5/href">https://medium.com/media/b5a713b59c38ef5445827616bed10ab5/href</a></iframe><p>This next snippet maps the BCM2835’s <em>“I/O Peripherals”</em> address block in the <em>“ARM Physical Addresses”</em> memory space from /dev/memso that it can be safely used in the program.</p><p><strong>Line 1</strong> first checks to see if the user running the program is running as <em>root</em> (either <em>root</em> user or <em>sudo</em>). If not, the /dev/mem device can’t be used. /dev/mem provides unrestricted access to the CPU’s memory. As this is obviously a dangerous thing to do its use is restricted to <em>root</em>. There is an alternative to /dev/mem, /dev/gpio. This will be shown later in this section.</p><p><strong>Line 4</strong> opens /dev/mem in preparation to the mapping operation. O_SYNC specifies that the write to /dev/mem must be completed before any write operations return (i.e., the write isn’t cached).</p><p><strong>Line 13</strong> assigns the bcm_peripherals variable to the memory block at offset and length, bcm_peripherals_base and bcm-peripherals_size, of the <em>I/O Peripherals</em> address block. This mapping effectively restricts the program’s access to the <em>I/O Peripherals</em>address block of physical memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5a6cfa771ebefefb536773650935edd/href">https://medium.com/media/f5a6cfa771ebefefb536773650935edd/href</a></iframe><p>This next code snippet calculates the offsets for the various types of registers (e.g., GPIO, PWM, SPI, etc). Each offset is relative to the value of bcm_peripherals which was the result of a mapmem() operation in the previous snippet. So to get the address of a register set like the GPIO register set we would add BCM_GPIO_BASE to the bcm_peripherals base address. But you may have noticed the code divides these offsets by 4 prior to adding them to bcm_peripherals. These offsets, e.g., BCM_GPIO_BASE, which are specified as integers, point to specific byte addresses, i.e., at 8 bit boundaries. bcm_peripherals is specified as a uint32_t*, a pointer. You can’t just naively add an integer to a pointer. You may recall that pointer arithmetic operates on a pointer variable based on the size of the type of the associated variable. For unint32_t&#39;s their size is 32 bits or 4 bytes. Adding 1 to a uint32_t pointer will result in that pointer pointing to the next uint32_t, which starts 4 bytes from the current position. Naively adding offsets like BCM_GPIO_BASE to bcm_peripherals will result in bcm_peripherals pointing to a position in memory that is 4 uint32_ts past the current position, not 1 uint32_t past the current position which is what we want. This is why each register type offset like BCM_GPIO_BASE is divided by 4 prior to adding it to bcm_peripherals.</p><blockquote>If you’re new to C you may not be aware that pointer arithmetic is inherently dangerous. It can be hard to know exactly what a pointer will reference as a result of pointer arithmetic. The pointer could be an unexpected type or have an unexpected value. This can lead to unexpected behavior which can be very difficult to debug. In some cases, for example performing division, pointing to an unexpected place that contains the value zero will lead to the program abruptly ending (with a segmentation fault). This is good, this way you know something is wrong and you even know where it went wrong. A pointer may even point outside the program’s address space the program which may lead to system crashes. In our case however the register locations and associated types are very well known and using pointers is relatively safe. That is, as long as we perform pointer arithmetic correctly…</blockquote><h4>bcm_spi_begin()</h4><p>bcm_spi_begin() intializes the SPI interface on the BCM2835.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5a1215ec44845b17d539666866d3360/href">https://medium.com/media/f5a1215ec44845b17d539666866d3360/href</a></iframe><p><strong>Line 2</strong> defines the 32 bit address variable, paddr, that will contain the address of the GPIO register that we’ll manipulate.</p><p><strong>Lines 4 &amp; 5</strong> verify that the SPI0 register offset was successfully initialized in <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init()</a>. Prior to calling <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init()</a> all register set offsets are set to the value MAP_FAILED to prevent the program from running if bcm_init() wasn’t called or didn’t complete successfully.</p><p><strong>Lines 7 thru 11</strong> call <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_gpio_fsel">bcm_gpio_fsel()</a> to define the alternate function, BCM_GPIO_FSEL_ALT0 or alternate function zero, that is used to set the I/O functionality of the pins referenced by the BCM_GPIO_P1_* variables. Note that the comments to the left specify which SPI pins are being set, e.g., CE1 (Chip Select/Chip Enable). These pins, when set to alternate function 0, implement the SPI protocol.</p><p><strong>Line 13</strong> sets paddr to the offset to the SPI0 address set plus the offset of the BCM2825 SPI Master Control and Status register (CS) as described on page 152 of <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">the BCM2835 Peripherals guide</a> (using the abbreviation <em>“CS”</em> in this case is kind of confusing, but in this context this is not a “chip select” offset). Note that the BCM_SPI0_CS offset is divided by 4. The reason why was discussed in the discussion in the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init</a> section above.</p><p><strong>Line 14</strong> uses the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_write">bcm_peri_write()</a> function to write zeros to SPI Control and Status (CS) register pointed at by paddr. As per the BCM2835 ARM Peripherals guide, page 155, setting the 1 byte field at this offset sets the Chip Select field, in the CS register (Control and Status), to 0’s which specifies chip select pin 0. This matches the specification of the Raspberry Pi pin BCM_GPIO_P1_24, GPIO pin 8, which is the CE0 pin (chip enable/chip select pin 0).</p><p><strong>Line 17</strong>, as the comment suggests, uses <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_write">bcm_peri_write_nb()</a> to clear the transmission and receive FIFOs. Again, looking at page 155 of the BCM2835 ARM Peripherals guide, we can see that the CLEAR field in the <em>CS</em> register is at bit offsets 4 and 5. It gives the bit values for clearing the FIFOs, 1 in each bit. The value specified by BCM_SPI0_CS_CLEAR is 0x30 (see the <a href="https://github.com/youngkin/gpio/blob/main/ledblink/bcmfuncs.h">bcmfuncs.h file</a>). Converting this to binary we get 0011 0000. Bits 4 and 5 are indeed set to 1 so these bits will be set in the CS register.</p><h4>bcm_spi_setBitOrder()</h4><p>bcm_spi_setBitOrder() sets the bit order, MSB (1) or LSB (0), of the SPI interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/909f1a3f8df0ce2aebf6860f300b2a44/href">https://medium.com/media/909f1a3f8df0ce2aebf6860f300b2a44/href</a></iframe><h4>bcm_spi_setDataMode()</h4><p>bcm_spi_setDataMode() specifies the clock polarity and phase to be used for data transfers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5c979040abf80630a91982cfae26885/href">https://medium.com/media/a5c979040abf80630a91982cfae26885/href</a></iframe><p><strong>Line 3</strong> sets paddr, the memory offset for the SPI0 Control and Status (CS) register from the base address of the SPI0 register set. Recall from the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init()</a> section, line 13, that the register offsets need to be divided by 4.</p><p><strong>Line 5</strong> calls <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_set_bits">bcm_peri_set_bits()</a> to set the bits in the SPI0 CS register to the bit pattern specified by mode. The polarity and phase bits, BCM_SPI0_CS_CPOL (0x8) and BCM_SPI0_CS_CPHA (0x4) respectively, are masks that ensure that only those bits in the SPI0 CS register are set. See the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_gpio_fsel">bcm_gpio_fsel() section</a>, line 5, for more details on how masking works.</p><h4>bcm_spi_setClockDivider()</h4><p>bcm_spi_setClockDivider() is used to set the frequency of the SPI Clock (SCLK). It accomplishes this by dividing the system’s clock frequency by the divider parameter. See <a href="https://github.com/youngkin/gpio/blob/main/ledblink/bcmfuncs.h">bcmfuncs.h</a> or the <a href="https://www.airspayce.com/mikem/bcm2835/group__constants.html#gaf2e0ca069b8caef24602a02e8a00884e">BCM2835 C library documentation</a> for more details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26ba9b87f74c1778c937ccc41b44b714/href">https://medium.com/media/26ba9b87f74c1778c937ccc41b44b714/href</a></iframe><p><strong>Line 3</strong> sets paddr to the memory offset for the SPI clock (BCM_SPI0_CLK) register from the base address of the SPI0 register set. Recall from the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init()</a> section, line 13, that the register offsets need to be divided by 4.</p><p><strong>Line 5</strong> calls <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_write">bcm_peri_write()</a> to set the divider value.</p><h4>bcm_gpio_fsel()</h4><p>bcm_fsel is responsible for setting the I/O function associated with a given pin. There are a total of 8 functions available. One defines that the associated pin is to be set as an input pin meaning that it will be read from. Another function defines the associated pin as an output pin meaning the pin will be written to. The remaining 6 are referred to as “alternate functions” and are given names like “alternate function 0”. The I/O function that is assigned for the various alternate functions is different for the various GPIO pins. For example, setting BCM GPIO pin 17 to alternate function 4 defines its I/O function to be SPI. It actually defines the pin to be a specific subset of SPI functionality called chip enable or chip select, but that is a topic for a later article. Recall that in main() above, the function is being set to BCM_GPIO_FSEL_OUTP which defines pin to be an output pin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f775667dd1196ebd8caac076a27481f/href">https://medium.com/media/0f775667dd1196ebd8caac076a27481f/href</a></iframe><p>There’s quite a bit going on in this function even though it is quite short.</p><p><strong>Line 1</strong> defines the function as taking two parameters, pin and mode. It is fairly obvious that pin is the pin whose function is to be assigned. mode is the I/O function to associate with pin. mode is actually a bit pattern to be assigned to a particular register offset. The bit pattern assignments are defined in <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">The BCM2835 I/O Peripherals datasheet</a> in section 6, <strong>GPIO</strong>, on page 92. The patterns are defined as follows:</p><pre>000 = GPIO Pin X is an input<br>001 = GPIO Pin X is an output<br>100 = GPIO Pin X takes alternate function 0<br>101 = GPIO Pin X takes alternate function 1<br>110 = GPIO Pin X takes alternate function 2<br>111 = GPIO Pin X takes alternate function 3<br>011 = GPIO Pin X takes alternate function 4<br>010 = GPIO Pin X takes alternate function 5</pre><p>There is some additional background needed to understand the rest of the function. First, the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">BCM2835 ARM Peripherals guide</a>, section 6, page 91, states that a total of 54 GPIO pins are addressable via the function select registers (GPFSEL0-GPFSEL5). Each function select register is 32 bits long. Since each of the function select patterns above are 3 bits long, each function select register can specify the I/O function for 10 pins with 2 bits left over. Ten pins per register and a total of 54 pins explains why there are 6 function select registers numbered 0 thru 5. The math that follows is derived from this information.</p><p><strong>Line 3</strong>, volatile uint32_t* paddr = bcm_gpio + BCM_GPFSEL0/4 + (pin/10);, defines the register offset, paddr, of the bits that will be set according to mode. BCM_GPFSEL0 is the base offset, in bytes, of the function select registers. Here’s an explanation of the arithmetic performed in this line.</p><ol><li>Notice that pointer arithmetic is being performed. Recall that the result of pointer arithmetic is based on the type of the target variable (see the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init()</a> section above). Since uint32_t&#39;s are 4 bytes long BCM_GPFSEL0 needs to be divided by 4 for the calculation to come out correctly. Hence ... paddr = bcm_gpio + BCM_GPFSEL0/4 ....</li><li>Also recall that each register holds the function select information for 10 pins. For a given pin we need to determine which function select register, GPFSEL0 thru GPFSEL5, specifies the I/O function for a given pin. In C, the result of integer division that results in a fraction will be rounded down. So if we divide the pin number by 10, (pin/10), we’ll get the offset to the correct function select register. So pin 9 will result in 9/10 which equals 0, meaning pin 9’s function select location is in GPFSEL0. Likewise, pin 17’s, 17/10 = 1, function select register is GPFSEL1. And so on.</li></ol><p>Taken together, the equation paddr = bcm_gpio + BCM_GPFSEL0/4 + (pin/10) results in the function select register offset appropriate for a given pin. For pin 17 this will result in paddr logically pointing to GPFSEL1 at address 0x7E20 0004, 7E being the bus address, 20004 being the offset of the GPIO registers plus the offset of GPFSEL1, 4, from the beginning of the GPIO register set. I say logically because bcm_gpio is an offset from an address returned as the result of a mmap() operation. mmap() returns a pointer into the process’s virtual memory whereas 0x7E20 0004 is an address in the BCM2835’s <em>VC CPU Bus Addresses</em> space.</p><p><strong>Line 4</strong>, uint8_t shift = (pin % 10) * 3;, calculates the location within the function select register for given pin’s function select value. Since we’ll use bit shifting to set the pin’s function select value this location becomes the number of bits to <strong>SHIFT</strong> the pin’s function select value as provided in the mode parameter. Building the calculation up we first need to find the pin’s logical location, that is, which 3 bit cell within the function select register (recall that each function select value is 3 bits long). The calculation for this is given by shift = (pin % 10) .... For pin 17 (17 % 10) = 7. So pin 17’s 3 bit cell is located at the 7th 3-bit offset. Next we have to find the actual bit offset within the register. Since each function select value is 3 bits long each pin’s boundary is a multiple of 3, hence the complete calculation of shift = (pin % 10) * 3. For pin 17 this results in (17%10)*3 which equals 7*3 which results in an absolute bit offset of 21. Consulting the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">BCM2835 ARM Peripherals guide, section 6</a>, on page 92, we can confirm that pin 17’s offset within the GPFSEL0 register is in bit positions 21 thru 23.</p><p>Now let’s look at <strong>line 5</strong>, uint32_t mask = BCM_GPIO_FSEL_MASK &lt;&lt; shift;. When setting a subset of bits to a given value we want to preserve the values of the surrounding bits. A mask is used to accomplish this. The mask contains a bit(s) that is in the position of the bit in the target value that we want to change. For example, in the bit pattern 0101 1111, if we want to set bit 6’s value from 1 to 0 we only need to define a bit sequence with 1 bit set. To create the most general solution we would just set the least significant bit(s). Since we only need a single bit set we would define the mask as hex number 0x1, which specifies the bit pattern 0000 0001. Next we need to shift this bit pattern as required so that the 1 bit is moved to the correct position. In our example, since we want to change bit 6, we would left shift the mask pattern 6 bits to the left, e.g., newMask = 0000 0001 &lt;&lt; 6. This results in newMask equaling 0100 00000, which is puts the 1bit in position 6 as we desire. It’s possible that we could have defined the mask as 0100 0000 outright, but this would not result in a general solution that would work for any mask needed to set a bit(s) in an arbitrary bit position, such as bits 21-23.</p><p>As given in bcmfuncs.h the value of BCM_GPIO_FSEL_MASK is 0x7 or 0000 0111, this is because each GPIO function select pattern is 3 bits long. So this is a useful bit pattern for masking 3 bit sequences. If we shift this pattern by the <strong>SHIFT</strong> of 21 as calculated in line 4 above we’ll get a 32 bit pattern that looks like this, 0000 0000 1110 0000 0000 0000 0000 0000. The mask is now in bit locations 21-23, which is the location of pin 17’s function select pattern in the GPFSEL1 function select register.</p><p>In summary, <strong>line 5</strong> creates the mask needed to set the 3 bit function select pattern as specified in the mode parameter on the provided pin parameter.</p><p><strong>Line 6</strong>,uint32_t value = mode &lt;&lt; shift;, creates the new 3 bit value that will be placed into the GPFSEL1 register. Recall that GPFSEL1 is a 32 bit register. To use a 3-bit value such as mode to set a 3 bit sequence at an arbitrary position, e.g., bits 21-23, we create a value mask that sets the bits in the desired position to the desired value. As with the mask above, the most general solution specifies that those bits be set starting in the least significant position. Let’s say in our example we want pin 17 to be set to alternate function 1. Looking at the bit patterns above we can see that the 3 bit value for alternate function 1 is 101. The mode parameter will contain this value. To set pin 17 to alternate function 1 we need to shift mode&#39;s bit pattern of 0000 0101 21 bits to the left. As with line 5, line 6 does this in a general way, value = mode &lt;&lt; shift. Given our value of mode and the calculated value of shift we get the 32 bit value of 0000 0000 1010 0000 0000 0000 0000 0000.</p><p>So we now have the 4 variables needed to calculate the new value of the GPFSEL1 register, paddr, mode, mask, and value.</p><p><strong>Line 7</strong> calls the function <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_set_bits">bcm_peri_set_bits()</a> to complete this operation. This operation is done in a separate function since there are other register values that require setting as we will see later.</p><h4>bcm_gpio_write()</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aec5c5dba8b8266782a746a333d054e/href">https://medium.com/media/1aec5c5dba8b8266782a746a333d054e/href</a></iframe><p>bcm_gpio_write() writes the 32 bit value to the specified pin. It uses 2 helper functions, <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_gpio_set-and-bcm_gpio_clr">bcm_gpio_set()</a> and <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_gpio_set-and-bcm_gpio_clr">bcm_gpio_clr()</a>. The parameter on is used to specify if the value for pin should be set or cleared. There are a set of 4 GPIO registers, GPSET0 and GPSET1, and GPCLR0 and GPCLR1, which specify if the value of a pin is HIGH or LOW. HIGH corresponds to GPSETn value of 1. LOW corresponds to GPCLRn value of 1.</p><p>When the value of on is 1 the GPSETn register associated with the value of pin is set to 1. If on is set to 0 then the GPCLRn register associated with the value of pin is set to 1. This raises the question, what if both the GPSETn and GPCLRn bits are set to 1? According the the BCM2835 ARM Peripherals guide, “<em>… the bit will be set according to the last set/clear operation</em>”.</p><p>GPSETn’s and GPCLRn’s values are only used when a pin’s I/O function is set to OUTPUT. Values of 0 in these registers are ignored. Recall that the BCM2835 allows GPIO functions to be specified for 54 pins (vs. the expected 40). Since each pin requires 1 bit to specify whether it’s to be set or cleared a total of 54 bits is required. This explains why two 32 bit registers are needed for set and clear.</p><p>The use of these registers is further described in section 6, page 95, of the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">BCM2835 ARM Peripherals guide</a>.</p><h4>bcm_peri_read()</h4><p>bcm_peri_read() will read the 32 bits starting at paddr and return them to the caller as a 32 bit value. Unlike bcm_fsel() and bcm_peri_set_bits(), this function is quite simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2f81bd348c24878cf03451814cfe98b/href">https://medium.com/media/e2f81bd348c24878cf03451814cfe98b/href</a></iframe><p><strong>Lines 4 &amp; 6</strong> synchronize access to memory so that the read can’t be interrupted.</p><p><strong>Line 5</strong> simply sets the return value, ret, to the contents located at paddr.</p><p>There’s another version of this function called bcm_peri_read_nb(). The difference between versions is that the nb version is non-blocking, meaning that the __sync_synchoronize() calls aren’t used.</p><h4>bcm_peri_write()</h4><p>bcm_peri_write() will set the 32 bits starting at paddr to the value contained in value. Like bcm_peri_read() this function is quite simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/292c582530dfaedc0e2b146b43056ecf/href">https://medium.com/media/292c582530dfaedc0e2b146b43056ecf/href</a></iframe><p><strong>Lines 3 and 5</strong> synchronize access (lock) to the 32 bits starting at paddr.</p><p><strong>Line 4</strong> sets the 32 bits located at paddr to value.</p><p>There’s another version of this function called bcm_peri_write_nb(). The difference between versions is that the nb version is non-blocking, meaning that the __sync_synchoronize() calls aren’t used.</p><h4>bcm_gpio_set() and bcm_gpio_clr()</h4><p>bcm_gpio_set() and bcm_gpio_clr() are twins in terms of their functionality. They only differ in which registers they operate on. *set() operates on the GPSETn registers and *clr() operates on the GPCLRn registers. They are responsible for setting the appropriate bit offset in the appropriate register for the provided pin argument. This section will only describe bcm_gpio_set(). With the exception of the register set operated on their implementations are identical. In fact, with the addition of another parameter to specify the starting offset they could be collapsed into a single function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0548218d2a2acb50360058e196800c4c/href">https://medium.com/media/0548218d2a2acb50360058e196800c4c/href</a></iframe><p>In bcm_gpio_set() <strong>line 3</strong> calculates the address, paddr, of the target register. bcm_gpio is the starting offset of the GPIO registers. BCM_GPSET0 is the starting offset of the set and clear registers. Recall from the discussion in the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init()</a> section above that pointer arithmetic is used to determine the memory offset to use for a given operation.</p><p>This is why BCM_GPSET0 is divided by 4 in this operation. pin/32 is used to calculate which of the GP*n registers is to be used for the given pin. Recall that integer division always rounds down. So the result of pin 17/32 is 0 which specifies that the first GP*n register will be used. Consistent with <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">the BCM2835 ARM Peripherals guide</a>, pages 95 and 96, this is the correct offset within the correct register.</p><p><strong>Line 4</strong> calculates the bit position for the set/clear bit within the target GPSETn/GPCLRn register. Since each pin only uses a single bit the modulus (%) operator will provide the proper location. For example, pin 17 will have the result of 17%32 which is 17. This is the bit position for pin 17 within the GPSETn/GPCLRn registers.</p><p><strong>Line 5</strong> then uses <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_write">bcm_peri_write()</a> to shift 1, shift bits to the left, in order to write to the correct offset in the correct register. For pin 17 for example, the calculation on line 4, 17%32, 1 is shifted 17 bits to the left.</p><p>You may have noticed that unlike <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_gpio_fsel">bcm_gpio_fsel()</a>, no mask was used to protect the other bits within the specified register. I’m not sure why this is the case. It’s odd because this approach will cause all the other bits in the register to be set to zero (0). I’m only speculating here, but I’m guessing it’s because zero values in these registers are ignored and as per the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">BCM2835 ARM Peripherals guide</a>, page 95, “<em>… the bit will be set according to the last set/clear operation</em>”. I take this to mean that an output pin’s value will be set, 1 for GPSETn and 0 for GPCLRn, when a 1 is written to the appropriate register and subsequent changes to 0 will have no effect. However this is just an educated guess.</p><h4>bcm_spi_transfer()</h4><p>bcm_spi_transfer() writes and reads a single byte to the SPI0 FIFO bits in the SPI0 FIFO register. SPI transfers are full-duplex meaning that data is written to, and received from, the SPI slave device.</p><p>See section 10, starting on page 153, of <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">the BCM2835 ARM Peripherals guide</a> for more details on the CS and FIFO register settings below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dca28619c7025397d81f2b8c17871f9/href">https://medium.com/media/1dca28619c7025397d81f2b8c17871f9/href</a></iframe><p><strong>Line 3</strong> defines the paddr variable which is the offset to the SPI0 CS register. Recall from the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init() section</a>, line 13, that these offsets need to be divided by 4.</p><p><strong>Line 4</strong> defines the fifo variable which is the offset of the SPI0 FIFO register.</p><p><strong>Line 7</strong> uses <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_set_bits">bcm_peri_set_bits()</a> to clear the transmission and receive FIFOs in preparation for the data transfers. More on bcm_peri_set_bits() follows below.</p><p><strong>Line 10</strong> uses <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_set_bits">bcm_peri_set_bits()</a> to set the TA bit in the SPI0 CS register. The TA bit is used to indicate that a SPI transfer is active.</p><p><strong>Line 13</strong> pauses execution until the FIFO register can accept data. The BCM_SPI0_CS_TXD value is a mask that contains a 1 in bit position 18, meaning the expression will return true if the “TX FIFO has space for at least 1 byte”.</p><p><strong>Line 17</strong> writes to the FIFO register ensuring that the bytes sent are in MSB order (see <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_correct_order">bcm_correct_order()</a> above for details). It uses the non-blocking/non-synchronized version of <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_write">bcm_peri_write</a> for the transfer, but I’m not sure why. It seems to me that the blocking/synchronized version would be safer to ensure that concurrent writes don’t conflict with each other.</p><p><strong>Line 20</strong> waits for the transfer to the SPI slave to complete.</p><p><strong>Line 24</strong> first reads from the SPI slave device then converts the output as needed to MSB order.</p><p><strong>Line 27</strong> clears the TA bit signifying that the SPI transfer is complete.</p><p><strong>Line 29</strong> returns the result of the read on <strong>line 24</strong>.</p><h4>bcm_correct_order()</h4><p>bcm_correct_order() ensures that data sent to SPI0 is in MSB order. See the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#init_spi">bcm_init_spi</a> section, Line 6, for additional details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fe1e2f17de76105de224edfaf406185/href">https://medium.com/media/8fe1e2f17de76105de224edfaf406185/href</a></iframe><p><strong>Line 5</strong> reverses the bit order if the check on <em>line 4</em> shows that the byte order is currently set to BCM_SPI_BIT_ORDER_LSBFIRST. Per the comments from bcm_byte_reverse_table:</p><pre>/* SPI bit order. BCM2835 SPI0 only supports MSBFIRST, so we instead <br> * have a software based bit reversal, based on a contribution by Damiano Benedetti<br> */</pre><p>The key point in this statement is that <em>“BCM2835 SPI0 only supports MSBFIRST”</em>. The other 2 SPI I/O functions, SPI1 and SPI2 work with both MSB and LSB. See the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">BCM2835 ARM Peripherals guide</a>, section <em>2.3.4 SPI register details</em>, page 23 for more details. Specifically, bit 6 of the AUXSPI0/1_CNTL0 registers are used to specify MSB or LSB - <em>“Shift out MS bit first”</em> and <em>“If 1 the data is shifted out starting with the MS bit. (bit 15 or bit 11). If 0 the data is shifted out starting with the LS bit. (bit 0)&quot;</em>. Support for this was added in BCM2835 version 1.53. See this <a href="https://groups.google.com/g/bcm2835/c/bkCc8mzq7io/m/DtmVmOyqAQAJ">BCM2835 Google Groups thread</a> for more details.</p><h4>bcm_peri_set_bits()</h4><p>bcm_peri_set_bits() writes the an updated value to address paddr after applying the mask to the provided value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3702809736ddf34cc909dd0d00e5a693/href">https://medium.com/media/3702809736ddf34cc909dd0d00e5a693/href</a></iframe><p><strong>Line 3</strong> reads the current value from the provided address paddr using <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_read">bcm_peri_read()</a>.</p><p><strong>Line 4 </strong>calculates the new value v, from value and the mask, to be written to paddr. Here’s an example to demonstrate how this somewhat complex line accomplishes this. This process is similar to the process explained in the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_gpio_fsel">bcm_gpio_fsel()</a> section, line 5. It’s implemented in a different manner so it’s worth describing this alternate process for applying a mask.</p><p>Let’s start with the following:</p><pre>value = 0000 0100 <br>mask  = 0000 1100</pre><p>mask has bits 2 and 3 set to 11. This specifies that these are the bits to be reset (in this example). At the end of the process these 2 bits will be set to the values for those same bits as specified in value, namely 01. The remaining bits in the current value stored at paddr will remain unchanged.</p><p>After reading the current contents of paddr on line 3 above, v is set to 1100 1011. Since value above specifies that bits 2 and 3 should be set to 01, the new value written to paddr is expected to be 1100 0111.</p><p>Now let’s build up the final value of v step by step performed in <strong>line 4</strong>:</p><pre>~mask   = 1111 0011<br>v       = 1100 1011<br>v&amp;~mask = 1100 0011</pre><p>We first take the complement of mask, ~mask so we can reset bits 2 and 3 to 00 while leaving the remaining bits of the original value vunchanged. When we calcuate v&amp;~mask we get 1100 0011. This provides the desired result, all bits except 2 &amp; 3 keep their current values.</p><p>In the next step we calculate the new values of bits 2 and 3.</p><pre>value      = 0000 0100<br>mask       = 1111 1100<br>value&amp;mask = 0000 0100</pre><p>If we | (OR) this value with the result of v&amp;~mask we’ll get the final result as shown next</p><pre>v&amp;~mask                  = 1100 0011<br>value&amp;mask               = 0000 0100<br>(v&amp;~mask) | (value&amp;mask) = 1100 0111</pre><p>So the final value of the calculations in <strong>line 4</strong> is 1100 0111, bits 2 and 3 have been set to the desired value and the remaining bits are unchanged. Here’s a comparison of the old and current values of the register:</p><pre>original value = 1100 1011<br>new value      = 1100 0111</pre><p><strong>Line 5</strong> simply writes the new value, v, to paddr using <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_peri_write">bcm_peri_write()</a>.</p><h4>bcm_spi_end()</h4><p>bcm_spi_end() reverses the effects of <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init()</a>. It uses <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_gpio_fsel">bcm_gpio_fsel()</a> to reverse all the SPI0 GPIO pins from SPI mode, the BCM_GPIO_FSEL_ALT0 alternate function, back to input mode, BCM_GPIO_FSEL_INPT. In the code below, the pin references, e.g., BCM_GPIO_P1_26, refer to #defines that cross-reference the Raspberry Pi pin numbers, e.g., 26, to the GPIO pin numbers. For example, BCM_GPIO_P1_26 refers to the Raspberry Pi pin 26 which maps to GPIO pin 7, the CE1 pin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6901f8a8fb1705ecbb3c680af52438aa/href">https://medium.com/media/6901f8a8fb1705ecbb3c680af52438aa/href</a></iframe><h4>bcm_close()</h4><p>bcm_close deallocates all resources and resets all GPIO offsets to their original values, MAP_FAILED in this case. With regard to MAP_FAILED, this value prevents any more operations on the BCM2835 peripheral registers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f1b8bb57b8b02ab66b3c4701b765aff/href">https://medium.com/media/5f1b8bb57b8b02ab66b3c4701b765aff/href</a></iframe><p><strong>Line 3</strong> releases the memory reserved by the mapmem() operation in <a href="https://youngkin.github.io/post/spidotmatrixmodule/#bcm_init">bcm_init()</a>.</p><p><strong>Lines 4–14</strong> reset all the register offsets to their default settings.</p><h3>Summary</h3><p>If you got this far, especially if you read the section on interacting directly with the BCM2835, congratulations! This has been a long and detailed article. I do hope you found it worth your investment of time and energy.</p><p>This article has covered quite a lot of ground. First, it walked you through the physical setup you needed to follow this article with a working example.</p><p>Second, it provided a fairly detailed overview of the SPI protocol. This included:</p><ol><li>An overview of SPI and how and why you might use it</li><li>A description of the MAX7219 LED Dot Matrix Display module</li><li>A description of the physical pins in the MAX7219 as well as the corresponding GPIO pins on the BCM2835</li><li>An example SPI timing diagram to illustrate how the signaling works</li></ol><p>Third, it walked you through the main program that demonstrates how to program the MAX7219 to display a series of numbers, characters, and shapes. In and of itself this main program is sufficient to gain an understanding of how to program SPI using the BCM2835 C library.</p><p>Fourth, it provided a detailed, but optional, description of how to directly program the registers on the BCM2835 that are associated with the SPI protocol.</p><p>That’s it, thanks for reading! Comments and questions about this article are welcome.</p><h3>References</h3><ul><li><a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.6_led_dot_matrix_c.html">The Sunfounder LED Dot Matrix Module</a> is the source of the breadboard diagram and the original version of the <a href="https://youngkin.github.io/post/spidotmatrixmodule/#controlling-the-max7219---main-program">main()</a> and supporting functions.</li><li><a href="https://pinout.xyz/">Raspberry Pi GPIO Pinout diagram</a> provides the location of physical board pin numbers and their mapping to the corresponding BCM/GPIO pin numbers and the WiringPi pin numbers.</li><li><a href="https://github.com/youngkin/gpio">The gpio repository</a> contains the code for this and other articles</li><li><a href="https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up">How to setup a new Raspberry Pi from scratch</a></li><li><a href="https://www.sciencebuddies.org/science-fair-projects/references/how-to-use-a-breadboard">How to use a breadboard</a></li><li><a href="https://youngkin.github.io/categories/gpio/">GPIO programming on a Raspberry Pi 3B+</a> is a link to my articles about GPIO programming on the Raspberry Pi</li><li><a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">The BCM2835 ARM Peripherals guide</a>.</li><li><a href="https://en.wikipedia.org/wiki/Serial_Peripheral_Interface">The Wikipedia Serial Peripheral Interface</a> article provides a detailed introduction to the SPI protocol.</li><li><a href="https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf">The MAX7219 datasheet</a> describes the low level details of the MAX7219 LED Dot Matrix Display, called the Serially Interfaced, 8-Digit LED Display Drivers. It includes detailed information about the registers, what they do, and how to set them.</li><li>The C <a href="https://www.airspayce.com/mikem/bcm2835/index.html">BCM2835</a> library by Mike McCauley</li><li>The C <a href="http://wiringpi.com/">WiringPi</a> library and associated <a href="https://github.com/WiringPi/WiringPi">GitHub repository</a></li><li>The Python <a href="http://abyz.me.uk/rpi/pigpio/">pgpio</a> library</li><li>The Python <a href="https://pypi.org/project/RPi.GPIO/">RPi.GPIO</a> library</li><li>The Go <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a></li><li><a href="http://robojax.com/learn/arduino/8x8LED/">Sprite Generator for LED Matrix 8x8</a> is an online tool that given an input shape on an LED matrix will output the hex numbers needed to display it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34a269f35c60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/raspberry-pi-gpio-using-spi-to-display-arbitrary-patterns-on-a-max7219-dot-matrix-display-module-34a269f35c60">Raspberry Pi GPIO — Using SPI to display arbitrary patterns on a MAX7219 Dot Matrix Display Module</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raspberry Pi GPIO — Introduction To Programming Broadcom BCM2835 ARM Peripherals]]></title>
            <link>https://medium.com/better-programming/raspberry-pi-gpio-introduction-to-programming-broadcom-bcm2835-arm-peripherals-33e6d9423f98?source=rss-80d16197df23------2</link>
            <guid isPermaLink="false">https://medium.com/p/33e6d9423f98</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[makers]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Richard Youngkin]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 11:55:09 GMT</pubDate>
            <atom:updated>2022-04-23T23:15:04.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>Raspberry Pi GPIO — Introduction To Programming Broadcom BCM2835 ARM Peripherals</h3><h4>Learn how to directly program the BCM2835 on a Raspberry Pi using its registers to perform tasks such as writing to a GPIO pin or using advanced capabilities such as SPI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_EEakhqDNtYnAbRpgEc1g.jpeg" /><figcaption>Image Credit: RasPi.tv</figcaption></figure><h3>Overview</h3><p>This is the sixth article in a series that explores <a href="https://youngkin.github.io/categories/gpio/">GPIO programming on a Raspberry Pi 3B+</a>. It is an introduction to controlling GPIO peripheral devices by directly interacting with the appropriate registers on the BCM2835 SoC (System on a chip). It is an introduction in that it only covers one of the capabilities, using the basic GPIO capability as described in <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">Section 6 of the BCM2835 ARM Peripherals guide</a>. This excludes BCM2835 support for protocols such as Serial Peripheral Interface (SPI), Pulse Width Modulation (PWM), and Inter-integrated-circuit (IC2) which overlay specific protocol capability by utilizing the underlying pins mapped to a given protocol (e.g., GPIO pins 8–11 are associated with the SPI protocol and have behaviors that can be enabled that are specific to that protocol). That said, using the basic pin level functionality covers the same concepts needed to utilize advanced protocol capabilites such as SPI. This article, coupled with the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">BCM2835 ARM Peripherals guide</a>, should provide enough background to drive devices that are controlled via those capabilities.</p><p>Of course, there are multiple libraries such as the C <a href="https://www.airspayce.com/mikem/bcm2835/index.html">BCM2835</a> and <a href="https://github.com/WiringPi/WiringPi">WiringPi</a> libraries, the Python <a href="http://abyz.me.uk/rpi/pigpio/">pgpio</a>, and <a href="https://pypi.org/project/RPi.GPIO/">RPi.GPIO</a> libraries, and the Go <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> library makes this much easier. And while these libraries are usually more appropriate for most projects, it can be helpful to understand how the BCM2835 SoC works and how those libraries interact with the BCM2835. This background is also helpful if you find yourself reading library code and/or would like to contribute to these projects, or even write your own library.</p><p>This article assumes you already have some familiarity with the BCM2835 and GPIO programming on the Raspberry Pi. If you don’t you may want to consider trying the projects covered in some of <a href="https://youngkin.github.io/categories/gpio/">my other GPIO articles</a>. The simplest article in the series is <a href="https://youngkin.github.io/post/sunfoundergpionotesled/">Raspberry Pi GPIO in Go and C — Blinking LED</a>. It demonstrates the same capability as this article does, blinking an LED, but it also demonstrates the usage of the <a href="https://github.com/WiringPi/WiringPi">WiringPi</a> and the Go <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> libraries. It is a good introduction to using GPIO on the Raspberry Pi, but it only covers basic GPIO concepts and how to wire a breadboard to a Raspberry Pi’s GPIO outputs.</p><p>The following topics will be covered:</p><ol><li><strong>Prerequisites</strong> — describes the hardware and libraries you’ll need for this article.</li><li><strong>An introduction to BCM2835 GPIO Peripherals</strong> — provides an overview the BCM2835’s architecture and capabililites.</li><li><strong>Using the BCM2835 board to control an LED via the GPIO pins</strong> — provides the details, including code, for controlling an LED using the BCM2835 GPIO registers.</li><li><strong>Summary</strong> — summarizes the important concepts covered in this article.</li><li><strong>References</strong> — provides a list of references I found helpful, some of which were used in the creation of this article.</li></ol><h3>Prerequisites</h3><p>If you don’t have one, you’ll need a Raspberry Pi. I used a Raspberry Pi 3B+ with the ‘stretch’ version of the Raspbian OS. See <a href="https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up">How to setup a new Raspberry Pi from scratch</a> if you don’t already have a Raspberry Pi and need help setting one up.</p><p>Next you’ll need is a <a href="https://www.amazon.com/dp/B082KBF7MM/ref=sspa_dk_detail_4?psc=1&amp;pd_rd_i=B082KBF7MM&amp;pd_rd_w=1tGTV&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=fX8JB&amp;pf_rd_r=44DE0RS1E9FD42RBYC7R&amp;pd_rd_r=47cbdc7f-7834-455f-9429-ef74a438bd45&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFVVkdZVUZRNUw3ODkmZW5jcnlwdGVkSWQ9QTA4MzI4MzYyU0VLNzBJM0cxRUVMJmVuY3J5cHRlZEFkSWQ9QTA0Mjk1NTMzSzNSWlNFUjU0NURBJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">breadboard</a>, some <a href="https://www.amazon.com/dp/B08HZ26ZLF/ref=syn_sd_onsite_desktop_19?psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUExRFpLWElCRjg1MUNMJmVuY3J5cHRlZElkPUEwMjMyMTE1M01aOFE3U1BQS09YSiZlbmNyeXB0ZWRBZElkPUEwODE5NTMxMktEMTlZRjEyQjBJNiZ3aWRnZXROYW1lPXNkX29uc2l0ZV9kZXNrdG9wJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">jumper wires</a>, <a href="https://www.amazon.com/Gikfun-Resistor-Experiment-Raspberry-Arduino/dp/B01G3FCMVA/ref=sr_1_19?keywords=220+ohm+resistor&amp;qid=1648933499&amp;sr=8-19">a 220 Ohm resistor, and an LED</a>. You should also consider getting a <a href="https://www.amazon.com/dp/B082PRVRYR/ref=sspa_dk_detail_2?psc=1&amp;pd_rd_i=B082PRVRYR&amp;pd_rd_w=8mKhr&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=e9psa&amp;pf_rd_r=S09F37DF2G5FW8B8GX4B&amp;pd_rd_r=c065c120-e60b-45e9-b93b-f581f048cf46&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFCMzhUQ09COFI2VlMmZW5jcnlwdGVkSWQ9QTA5NjU2ODUxRDkxNEYwSTYwV09KJmVuY3J5cHRlZEFkSWQ9QTAxOTg1MTUyRUhEUlc2VzQ2VDQ4JndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">40 pin female to female with a T-Type adapter</a> to attach the GPIO outputs to the breadboard. You can use only jumper wires, but the adapter will make things easier and will help prevent damage to the GPIO pins on the Raspberry Pi. If you elect not to buy the 40 pin cable with T-Type adapter you’ll need to buy <a href="https://www.amazon.com/SinLoon-Breadboard-Arduino-Circuit-40-Pack/dp/B08M3QLL3Q/ref=pd_sbs_7/143-0445142-7950409?pd_rd_w=sVLrc&amp;pf_rd_p=8b76d7a7-ab83-4ddc-a92d-e3e33bfdbf03&amp;pf_rd_r=CDM5TGJT03VKF0ZFB577&amp;pd_rd_r=8e58fd82-8503-41cf-b8f2-c78eaeb78d25&amp;pd_rd_wg=tT1U0&amp;pd_rd_i=B08M3QLL3Q&amp;psc=1">male-to-female jumper wires</a>. Buying all these things separately will cost more than a kit, however. <a href="https://www.amazon.com/dp/B06WP7169Y/ref=sspa_dk_detail_5?psc=1&amp;pd_rd_i=B06WP7169Y&amp;pd_rd_w=OZVyf&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=0V0IH&amp;pf_rd_r=623YJTBQ2CN2B2GYXQG5&amp;pd_rd_r=faa61f0f-3aec-4cf0-8e7e-d44eb1b3b92f&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyUVlDQzMzVVZBMFYxJmVuY3J5cHRlZElkPUEwMzExNzk4MUhGSjFSS0VKTlBROCZlbmNyeXB0ZWRBZElkPUEwMzYwNjg2UUdMRU44N0YzNzIwJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">Here’s a simple kit that has all of the above</a>. If you expect to follow this series I recommend buying the <a href="https://www.amazon.com/gp/product/B09BMVT4CB/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&amp;psc=1">Sunfounder Raspberry Pi Ultimate Starter Kit</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QdQvl9ZuAKC1ZeNH.png" /><figcaption><em>Image Credit: Sunfounder Ultimate Starter/Raphael kit</em></figcaption></figure><p>You’ll need some basic C programming knowledge as well as familiarity with logging on to a Raspberry Pi terminal, or into the desktop GUI that comes with some OS versions. Depending on the approach you take, you may need to connect a keyboard and monitor to the Raspberry Pi. I simply SSH into the Pi. You’ll need familiarity with how to use an editor like Vi or nano. You’ll also need basic familiarity with the Linux command line.</p><p>Finally, you’ll need to clone or fork <a href="https://github.com/youngkin/gpio">my GPIO repository</a> as it contains underlying library code used to access GPIO capabilities on the BCM2835. As mentioned in other sections, this library code is based on the <a href="http://www.airspayce.com/mikem/bcm2835/index.html">BCM2835 C library</a> developed by Mike McCauley.</p><h3>An introduction to the BCM2835 ARM Peripherals</h3><p>This section provides an overview of the BCM2835 peripherals. It starts with an overview of the capabilities of the various types of peripherals. It then moves to an overview of BCM2835 addressing. Understanding addressing is fundamental to understanding the rest of the article. It concludes with a more detailed discussion about how registers are used to access the peripherals and their associated I/O functions.</p><p>This is not an exhaustive description of the BCM2835. The only capability that will be covered in any detail, and is the focus of this article, is interacting with the GPIO I/O functions, namely defining the function of a pin and setting and clearing the value of the pin (e.g., setting it to HIGH and LOW), specifically programming BCM2835 GPIO to blink an LED.</p><p>There are multiple pin numbering schemes. The Raspberry Pi has physical pin numbers, i.e., the numbers printed on the Pi board. BCM2835 has a numbering scheme called GPIO numbering. It is different than, and incompatible with, the Pi’s physical numbering scheme. Finally, some libraries such as the C WiringPi library have their own numbering schemes which are incompatible with the Pi and BCM2835 schemes. This article uses the BCM2835 numbering scheme exclusively. There is a good <a href="https://pinout.xyz/">pin out diagram</a> available that maps between these 3 numbering schemes. Where a pin supports a particular I/O function, as described below, is also called out on this pin out diagram.</p><p>A quick note on terminology… The term “peripherals” is used in the title and in some parts of this article. To me, the term peripherals are something of a misnomer. Let me explain. At its most basic the GPIO capability of the BCM2835 is made available through a set of physical pins on the device. Some of these pins provide the power and ground needed to drive external devices like LEDs, sensors, and motors. Other pins can be controlled programmatically to take input from, or output to, these external devices. At a higher level, subsets of the GPIO pins provide support for complete protocols that implement more sophisticated functions like controlling the speed and direction of a motor and controlling LED displays that display text like those in highway signs. These basic and more sophisticated capabilities are controlled by setting the function of a pin. Input and output are 2 functions that can be set. There are a variety of others that will be covered. Setting the function of a pin describes how the BCM2835 interacts with a device or peripheral. Because of this, I prefer to use the term I/O Function. I think that more accurately describes the concept than the term “peripherals” does. To me “peripherals” are external devices. The first use of the term <strong>I/O Functions</strong> is the title of the next section.</p><h3>I/O Functions</h3><p>The BCM2835 supports a variety of I/O functions. These are the subject of the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">BCM2835 ARM Peripherals guide</a>. This section will only describe a few of these functions in detail. There are other sources like Wikipedia that can provide information about the others.</p><p>The main I/O functions supported by the BCM2835 are:</p><ul><li>GPIO</li><li>SPI</li><li>PWM</li><li>AUX</li><li>BSC</li><li>DMA</li><li>External Mass Media Controller</li><li>Interrupts</li><li>Audio (PCM/I2s Audio)</li><li>System Timer</li><li>UART</li></ul><p>As I have direct experience with the first 3 I/O functions, GPIO, SPI, and PWM, this section will focus on these. This will provide enough context in order to get a basic understanding of the kinds of things the BCM2835 is capable of as well as leveraging the information in the Addressing and Registers sections below in order to learn about and use the remaining I/O functions.</p><h4>GPIO (General Purpose Input/Output)</h4><p>GPIO stands for General Purpose Input Output. In the BCM2835 ARM Peripherals guide the term GPIO refers to the most general, or basic, level of control of a physical pin. This is what’s used to control the function of a pin, such as setting it as an input or output pin, or more advanced I/O functions such as SPI and PWM. It’s also used to set or get the value of a pin. Values are conceptually referred to as HIGH and LOW, but they are represented by voltage, or lack thereof, passing across the pin. There are other types of settings for pins. One of these settings is used to control whether to detect a state change on the rising or falling edge of a pin’s voltage change. Another setting controls what is called pull-up/pull-down resistors attached to each pin. These resistors are used to explicitly control the value of a pin, 1 or 0, when a pin’s voltage is in an indeterminate state. <a href="https://www.electronics-tutorials.ws/logic/pull-up-resistor.html">This tutorial</a> has a reasonably good explanation for why pull-up and pull-down resistors are needed.</p><p>The code associated with this article causes an LED to blink. Accomplishing this involves the following steps:</p><ol><li>Set the function of the pin to output, i.e., it’s going to be written to in order to send a signal to the LED.</li><li>Write LOW to the pin to cause the LED to turn on.</li><li>Pause</li><li>Write HIGH to the pin to cause the LED to turn off.</li><li>Repeat steps 2 through 4.</li></ol><p>Accomplishing this uses the GPIO I/O functions. More accurately it uses the GPIO registers to set the pin’s function (e.g., output) and to control the behavior of the peripheral, an LED in this case.</p><h4>SPI (Serial Peripheral Interface)</h4><p>SPI is used to send data serially to a peripheral that can accept or requires data in parallel. This is helpful because a relatively large set of parallel inputs can be written to using just 3 GPIO pins, not including power (VCC) and ground (GND). If SPI wasn’t used, one GPIO pin would be required for each parallel input. This could easily be prohibitive since pins are a limited resource. Let’s see how this works with an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*kpdTEOQ_e5pvTjLdunyqhA.jpeg" /><figcaption>Image credit: Author</figcaption></figure><p>The diagram above shows the MAX7219 LED Dot Matrix Display. It’s commonly used to display display arbitrary shapes such as letters, numbers, and smiley faces. It controls an 8x8 matrix of LEDs. Controlling an LED requires 1 pin excluding power or ground. An 8x8 LED matrix has 64 LEDs. This number is well in excess of the 26 or 40 GPIO pins available on a standard Raspberry Pis. As explained below, utilizing SPI requires considerably fewer GPIO pins.</p><p>The MAX7219 has the following input pins:</p><ol><li>DIN — this is the serial data input pin.</li><li>CS — This is commonly called a chip select (CS) or chip enable (CE) pin.</li><li>CLK — This pin connects to a clock pin on the Raspberry Pi that synchronizes data transfers between the Raspberry Pi and the MAX7219.</li></ol><p>There are 2 more pins that aren’t used to control the MAX7219.</p><ol><li>VCC — This is the power-in pin. It connects to a power source on the Raspberry Pi, usually a 3.3v source.</li><li>GND — This is the ground pin. It connects to a ground pin of the Raspberry Pi.</li></ol><p>A minimum of 3 GPIO pins are required to connect from the Raspberry Pi to the MAX7219, specifically to the DIN, CS, and CLK pins. A Raspberry Pi can control all 64 LEDs in a cost (pin-wise) efficient manner using only these three pins. The usual approach is to use the Raspberry Pi pins that can drive the DIN, CS, and CLK pins. These 3 pins are named:</p><ol><li>(SPI)MOSI — This stands for Master Out Slave In. The MOSI pin will be connected to the MAX7219 DIN pin and is used to send a serial data signal to the MAX7219 (or any SPI peripheral).</li><li>(SPI)SCLK — These stand for SPI Clock. This pin will be connected to the MAX7219 CLK pin. It is used as the source of the clock signal used to synchronize the data transfer between the BCM2835 and the MAX7219 (or any SPI peripheral). The data transfer will occur when both the MOSI pin and the SCLK pin are set to HIGH.</li><li>(SPI)CS or (SPI)CE — These stands for Chip Select or Chip Enable. In either case, setting the pin to LOW directs the MAX7219 to accept data as described in the previous bullet.</li></ol><blockquote>I reluctantly use the terms “master” and “slave”. However these terms are used in all of the documents I’ve read on SPI. I’ll continue to use them in order to avoid confusion.</blockquote><p>The SPI capability on the Raspberry Pi may require as many as 5 GPIO pins. The 2 additional pins are:</p><ol><li>(SPI)MISO — This stands for Master In Slave Out. This pin allows for the MAX7219 (or any SPI peripheral) to send data back to the BCM2835.</li><li>(SPI)CS or (SPI)CE — This is a second chip select/chip enable pin. Having a second CS/CE pin allows the BCM2835 to control 2 SPI peripherals. As stated above, when the CS/CE pin is set to LOW the SPI peripheral will accept data from the BCM2835. So by setting one of the CS/CE pins to HIGH and the other to LOW we can control which slave can receive and send data. The article <a href="https://adikedia.com/2016/08/10/using-multiple-spi-slave-devices-with-wiringpi/">Using Multiple SPI Slave Devices with the Raspberry Pi</a> provides more information about how the 2 CE/CS pins are used. The following schematic illustrates how this is done:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*3oddhTT2rIGAQUVv.jpg" /><figcaption><em>Image credit: BCM2835 ARM Peripherals Guide</em></figcaption></figure><p>The primary SPI interface on the BCM2835, SPI0, is implemented on GPIO pins 7–11. Pins 7 &amp; 8 are the 2 CE/CS pins available on the BCM2835. Pin 9 is MISO, 10 is MOSI, and 11 is the clock (SPICLK/SCLK). The BCM2835 has 2 auxilary SPI interfaces, SPI1 (AKA AUX_SPI0) and SPI2 (AKA AUX_SPI1). From the BCM2835 ARM Peripherals Guide, SPI1 is available on pins 16–21 and SPI2 on pins 35–39. These auxilary interfaces are available via the AUX I/O function.</p><p>The following diagram shows a GPIO extension board frequently used to connect the BCM2835 GPIO pins to a breadboard. The pins are labeled with there GPIO pin numbers or the I/O function (e.g., SPI) they support Note the SPI pins are labeled on the board using the same terms as above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/0*WLl3HwOTlwvJaHB2.jpg" /><figcaption>Image Credit: Sunfounder</figcaption></figure><p>In addition to the MAX7219, SPI can be used to control a variety of peripherals to display images, take input from touchscreens, and interact with various sensors. <a href="https://en.wikipedia.org/wiki/Serial_Peripheral_Interface">Wikipedia has a good article</a> describing SPI in more detail.</p><p>My article titled <a href="http://youngkin.github.io/post/spidotmatrixmodule/">Raspberry Pi GPIO — Using SPI to display arbitrary patterns on a MAX7219 Dot Matrix Display Module</a> provides detailed coverage of the SPI I/O function and how to program it. Similar to this article, it also includes detailed coverage of how to directly program the BCM2835 using the associated registers on the BCM2835, but for SPI instead of general GPIO I/O functionality. By reading that article you’ll gain a deeper understanding of how to use the BCM2835 registers to program the I/O functionality supported by the BCM2835.</p><h4>PWM (Pulse Width Modulation)</h4><p>PWM is used to convert a digital signal, like that produced by the BCM2835, into a simulated analog signal. It is simulated in the sense that it’s not a true analog signal. It’s still a digital signal but it cycles so fast that, much like a video, it appears to be an analog signal. Many peripherals like electric motors, dimmable LEDs, and color LEDs require an analog signal. As with SPI, there are dedicated pins that can be enabled to utilize the PWM I/O function. These are GPIO pins 12, 13, 18, and 19. With these pins, the BCM2835 supports something called hardware PWM. The PWM functionality is embedded into the BCM2835. It implements a hardware-based clock loop that controls the frequency of the simulated analog signal. It is possible to use other GPIO pins for PWM, this is called software PWM. However, in software PWM the clock loop is written in the code that runs on the Raspberry Pi CPU. Since that CPU is doing many other things it isn’t possible to create a reliable clock signal. This can result in some undesirable side effects such as a flickering LED in place of a dim LED. See my articles <a href="https://youngkin.github.io/post/sunfoundergpionotesrgbled/">Raspberry Pi GPIO in Go and C — RGB LED</a> and <a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/">Pulse Width Modulation for Dummies</a> for more information about PWM as well as examples of PWM in use.</p><h3>Addressing</h3><p>All GPIO I/O functions are accessed via registers. These registers are located at various offsets in the onboard memory. Accessing the registers requires knowledge of how addressing works on the BCM2835 was well as on the Raspberry Pi. Here’s a diagram from the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">BCM2835 ARM Peripherals guide</a>, section 1.2.1, showing how memory is mapped from Pi’s physical address to the BCM2835 addresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wRzTSl5tmelqdiZE.jpg" /><figcaption><em>BCM2835 Addressing: Image Credit BCM2835 ARM Peripherals Guide</em></figcaption></figure><p>The Raspberry Pi maps the BCM2835 memory to the Pi’s physical address of 0x2000 0000. This is shown in the middle column labeled “ARM Physical Addresses”. The gray shaded area labeled I/0 peripherals is the Pi’s physical memory location of the BCM2835’s peripherals (e.g., GPIO pins). Moving towards the left you’ll see a gold box labeled “VC/ARM MMU”. This is the <a href="https://en.wikipedia.org/wiki/Memory_management_unit">Memory Management Unit</a> that is responsible for mapping the Pi’s physical memory to the BCM2835 memory. Following the line from the middle column’s “I/O Peripherals” partition, through the VC/ARM MMU, to the far left column titled “VC CPU Bus Addresses” leads to the “I/O Peripherals” partition on the BCM2835’s CPU address bus. Its address is 0x7E00 0000.</p><p>The I/O peripheral addresses can be made available to the application through one of 2 ways. The traditional way is via the /dev/memdevice mounted on the file system. Accessing this device requires root privileges. A newer method became available starting with the Raspberry Pi 2. This method accesses the I/O peripheral addresses via /dev/gpio. An advantage of using this method is that it doesn’t require root access. A disadvantage to using this method is that only the GPIO I/O functionality of the BCM2835 can be accessed. This means advanced capabilities like PWM and SPI are not available. Accessing the I/O peripherals using /dev/mem also requires a little more work, namely mapping the physical memory from /dev/mem to the application’s virtual memory. This will be covered in more detail later.</p><blockquote>There is third way to interface with GPIO registers. In the case of SPI, there are 2 devices (generally available on many Raspberry Pi models), /dev/spidev0.0 and /dev/spidev0.1 via ioctl(). This method won’t be covered in this article.</blockquote><h3>Registers</h3><p>As mentioned above, specifying the I/O function of a pin or set of pins is accomplished through registers on the BCM2835. Each I/O function has an associated register set located at an offset within the BCM2835’s I/O peripheral address space. For example, the GPIO register set starts at the CPU bus address 0x7E20 0000. The SPI register set starts at CPU bus address offset 0x7E20 4000. The PWM register set starts at offset 0x7E20 C000. And so on, each I/O function has it’s own set of registers to manage its behavior. That said, they all work on the same principles. Namely, find the offset of the beginning of each I/O function’s register set and then set (or get) the appropriate bits at the appropriate offsets to control the behavior. To make this example more explicit, and to highlight additional details, let’s do a high level walkthrough of how to control a GPIO pin to blink an LED.</p><p>As mentioned previously the GPIO register starts at bus address 0x7e2000 0000. Section 6.1 of the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">BCM2835 ARM Peripherals guide</a> starting on page 90 provides the details about the GPIO registers. To blink an LED we’ll first need to specify the pin’s function, output in this case, and then toggle the value of the LED between HIGH and LOW.</p><h4>Specify a pin’s function</h4><p>First, the I/O function of the pin needs to be set. A pin’s functionality is defined via one of 8 alternative functions. Encoding each function requires 3 bits, 000–111. These bits are contained within what is called a GPIO Function Select Register. Each register is 32 bits long. Therefore each 32-bit register can control 10 pins with 2 bits left over. In order to control all of the GPIO pins, there are 6 function select registers. The BCM2835 has the capability to control up to 54 pins, if supported, via function select registers (on the Raspberry Pi 3B+ only 40 pins are available). Supporting 54 pins, with 10 pins/register, requires 6 registers. The first function select register is located at 0x7E20 0000, zero-offset from the start of the GPIO register set. The 6th function select register starts at offset 0x7E20 0014. The 8 alternative functions are:</p><ul><li>Input — represented by the bit pattern 000</li><li>Output — represented by the bit pattern 001</li><li>and Alternate functions 0 through 5 represented by bit patterns 010 through 111 respectively.</li></ul><p>In this example let’s use pin 17 as an output pin. Inspecting the BCM2835 ARM Peripherals guide we see that pin 17 is in function select register 1, AKA GPFSEL1. GPFSEL1 is at offset 0x7E20 0004. Pin 17’s function select offset within the register is at bits 21-23. Recall that the output bit pattern is 001 so we’ll need to put that bit pattern in bits 21-23. In the section on coding below we’ll see how this is actually accomplished.</p><h4>Set the pin value</h4><p>This article assumes that pin 17 is attached to the ground terminal of the LED (the cathode). This means that we’ll have to set the pin to LOW in order for current to flow from the power input to the anode through to the LED ground on pin 17 and light the LED. Setting the pin to HIGH will cause the LED to turn off. Switching between LOW and HIGH will cause the LED to blink, which is what we’re looking for.</p><p>GPIO pin values are controlled via the GPIO Pin Output Set register. There are 2 GPIO Pin Output Set registers. Pin 17 is in the first register, GPIO Pin Output Set 0, AKA GPSET0, at GPIO register offset 0x7E20 002C. Pin 17 is at bit offset 17 within GPSET0. Setting bit 17 to 1 sets the register to HIGH. GPIO Pin Output Set registers can only set a pin to HIGH, setting a pin to 0 has no effect. But recall we need to set the pin to LOW. Since setting a pin in GPSET0 won’t result in the pin being set to LOW how can we accomplish this? It turns out there is another set of GPIO registers called GPIO Pin Output Clear registers. These are used to set a pin’s value to LOW. Pin 17 is in GPIO Pin Output Clear register 0, AKA GPCLR0, starting at offset 0x7E20 0028. It’s position within the register is also at bit 17. Setting bit 17 to 1 will set the pin to LOW. So we’ll need to left shift a 1 into bit 17 in order to turn on the LED. We’ll use GPSET0 to turn the LED off. As with specifying a pin’s function, how this is accomplished will be covered later in this article. By using the GPCLR0 and GPSET0 registers in turn we can cause the LED to blink.</p><h4>Other GPIO settings</h4><p>The GPIO register set can be used to control many other functions of a GPIO pin in addition to selecting the function and setting/clearing a pin’s value. It can also be used to read the value of a pin. As discussed in the I/O functions section above other things that can be managed include specifying how state changes are to be detected (rising/falling edge detection) and how to set the voltage of a pin when it’s in an indeterminate state (pull-up/down resistors). Discussing these other registers is an advanced topic and is beyond the scope of this article.</p><h3>Setup and Code</h3><p>This section starts with a program that causes an LED to blink. It’s fairly simple and will show the basic steps needed to program the BCM2835. The next part of this section will cover the BCM2835 programming in more detail. But before all that, here’s how to wire the breadboard to work with the blinking LED example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/0*CjtBu2b0bJo540n1.png" /><figcaption><em>Image credit: Sunfounder</em></figcaption></figure><p>The breadboard should be wired as illustrated in the above diagram. Note that the (bent) long lead of the LED, the anode, is connected to the 3.3 volt power pin via the resister and the cathode, or ground, is connected to GPIO pin 17. If you’re unfamiliar with breadboards and breadboard diagrams this <a href="https://www.sciencebuddies.org/science-fair-projects/references/how-to-use-a-breadboard">breadboard tutorial </a>should be helpful.</p><p>This section will first describe the main program that blinks an LED. After that, it goes into detail about how the code that interacts with the BCM2835 works to control the I/O functions.</p><p>All code in this article can be found in <a href="https://github.com/youngkin/gpio/tree/main/ledblink">my gpio repository</a>, in the ledblink directory.</p><h3>Controlling an LED — main program</h3><p>The code for the file that contains this code can be found at <a href="https://github.com/youngkin/gpio/blob/main/ledblink/blinkinglednolib.c">gpio/ledblink/blinkinglednolib.c</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9bc6ccad9db80a1b59ed98e8ef00666/href">https://medium.com/media/a9bc6ccad9db80a1b59ed98e8ef00666/href</a></iframe><p>This first code snippet shows a couple of important things:</p><ol><li>Line 1 gives the command to compile and link the program.</li><li>Line 3 provides the included directive needed to import the BCM2835 functions that directly interact with the BCM2835.</li><li>Line 8 defines the BCM GPIO pin that is used to control the LED. It matches the wiring diagram above.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fba6705b7e9bbb4fe9ad14625abf184a/href">https://medium.com/media/fba6705b7e9bbb4fe9ad14625abf184a/href</a></iframe><p>This snippet declares an interrupt handler to be used to gracefully exit the program. This ensures that the pin, and the LED, are left in a known state. The definition of the interrupt handler will be shown later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f6ed7d06917e1e96a631265a4921566/href">https://medium.com/media/3f6ed7d06917e1e96a631265a4921566/href</a></iframe><p>This snippet shows the beginning of the main function.</p><p><strong>Line 3</strong> registers the interrupt handler for the SIGINT signal (i.e., ctrl-C).</p><p><strong>Lines 5–10</strong> initialize the BCM2835 GPIO functionality. Briefly, it finds the GPIO peripherals offset and length within main memory and maps it to /dev/mem so it can be safely accessed within the program. It then sets variables to the offsets of the various capability registers (e.g., GPIO or SPI). If initialization fails the program exits. The bcm_init() function will be described in more detail below.</p><p><strong>Line 13</strong> sets LEDPIN to the GPIO output function. This allows the program to write values, HIGH or LOW, to the pin. The bcm_gpio_fsel() function will be described in more detail below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/548a8777b3bc853248c48c912097aca0/href">https://medium.com/media/548a8777b3bc853248c48c912097aca0/href</a></iframe><p>This snippet implements the primary functionality of the program. <strong>Lines 2–10</strong> blink the LED on and off.</p><p><strong>Lines 5 and 8</strong> set the value of the LEDPIN by calling bcm_gpio_write() and setting the value of the pin to either LOW to turn the LED on, or HIGH to turn the LED off. LOW turns the LED off because the lead connecting BCM GPIO pin 17 to the LED is connected to the LED’s ground pin. To get current to flow the pin must be set to 0 volts. Likewise, HIGH turns the LED off. bcm_gpio_write() will be described in more detail below.</p><p><strong>Lines 6 and 9</strong> cause the program to sleep for 500 milliseconds so the LED can be observed blinking.</p><p>As the comment states, <strong>line 13</strong> releases the GPIO resources obtained by bcm_init(). This will also set the GPIO system back to a known state. bcm_close() will be described in more detail below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14aa9595a588edf7123742da5b04ff39/href">https://medium.com/media/14aa9595a588edf7123742da5b04ff39/href</a></iframe><p>This snippet defines the interrupt handler function. <strong>Lines 3 and 4</strong> first turn the LED off, then release the GPIO resources obtained by bcm_init().</p><h3>Controlling an LED — interacting with the BCM2835</h3><p>This section describes how the code interacts with and controls the GPIO peripherals, specifically setting the values of the various registers associated with the I/O functionality of the BCM2835. Setting register values is used to control GPIO peripherals and reading register values allow the current state of the associated GPIO peripherals to be accessed.</p><p>The code for this section can be found in <a href="https://github.com/youngkin/gpio/blob/main/ledblink/bcmfuncs.c">bcmfuncs.c</a> in <a href="https://github.com/youngkin/gpio">my gpio repository</a>. The <a href="https://github.com/youngkin/gpio/blob/main/ledblink/bcmfuncs.h">header file can be found in bcmfuncs.h</a>.</p><h4>bcm_init()</h4><p>The above section on Registers mentions that all operations on BCM2835 peripherals are accomplished by manipulating the registers associated with that type of peripheral. The purpose of bcm_init() is to determine the address offsets for all the types of registers, e.g., GPIO, PWM, SPI, etc. so that their associated peripherals can be controlled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23bbb32dbcf5e64c0e16747506730e31/href">https://medium.com/media/23bbb32dbcf5e64c0e16747506730e31/href</a></iframe><p>This snippet shows the beginning of the bcm_init() function.</p><p><strong>Line 10</strong> opens the BCM_RPI2_DT_FILENAME. As indicated in the comment, the rb in the fopen() call opens a binary file for reading. BCM_RPI2_DT_FILENAME is defined in the associated bcmfuncs.h header file. It’s value is /proc/device-tree/soc/ranges. As stated in <a href="https://www.kernel.org/doc/html/latest/devicetree/usage-model.html">Linux and the Devicetree</a>,</p><blockquote>An operating system used the Device Tree to discover the topology of the hardware at runtime, and thereby support a majority of available hardware without hard coded information (assuming drivers were available for all devices).</blockquote><p>One of the pieces of information the device tree holds, and is important for our purposes, is the location and length of the I/O Peripherals partition in the BCM2835’s physical address space. Here’s a hex dump of the contents of /proc/device-tree/soc/ranges on a Raspberry Pi 3B+:</p><pre>pi@pi-node1:/ $ hexdump -C /proc/device-tree/soc/ranges<br>00000000  7e 00 00 00 3f 00 00 00  01 00 00 00 40 00 00 00  |~...?.......@...|<br>00000010  40 00 00 00 00 00 10 00                           |@.......|<br>00000018</pre><p>We’ll refer back to this in this next code snippet. Per <a href="https://www.devicetree.org/specifications/">devicetree.org</a>, in <a href="https://github.com/devicetree-org/devicetree-specification/releases/download/v0.4-rc1/devicetree-specification-v0.4-rc1.pdf">v0.4-rc1 of the Devicetree Specification</a>, the soc/ranges property is defined as follows:</p><blockquote>The ranges property provides a means of defining a mapping or translation between the address space of the bus (the child address space) and the address space of the bus node’s parent (the parent address space). The format of the value of the ranges property is an arbitrary number of triplets of (child-bus-address, parent-bus-address, length)</blockquote><p>In the case of the I/O Peripherals address block, as described in the <a href="https://youngkin.github.io/post/gpioprogramming/#addressing">Addressing section</a> above, the <em>“child-bus-address”</em> refers to the <em>“I/O Peripherals”</em> address block in the <em>“VC CPU Bus Addresses”</em> memory space. The <em>“parent-bus-address”</em> refers to the the <em>“I/O Peripherals” </em>address block in the <em>“ARM Physical Addresses”</em> block. And the <em>“length”</em> refers to the actual length of the <em>“I/O Peripherals”</em> address block. The Raspberry Pi 3B+ has a 32 bit address space so each of the values in the triple are 32 bits or 4 bytes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bab28f9fc6d1f4311a2e86cfeaf9d2c2/href">https://medium.com/media/bab28f9fc6d1f4311a2e86cfeaf9d2c2/href</a></iframe><p>This next code snippet finds the <em>parent-bus-address</em> and <em>length</em> of the I/O peripherals block using the data from /proc/device-tree/soc/ranges. Recall that the parent bus address is the second entry in the triplet that also defines the child bus address and length. <strong>Lines 1 thru 4</strong> shift the contents of the <em>parent-bus-address</em>, bytes at buf offsets 4 thru 7, into base_address. 3F is shifted into the high order byte of base_address. The remaining buf cells are likewise shifted into base_address from left (most significant) to right (least significant byte). After shifting is complete base_address will be set to 0x3F000000. Looking back at the diagram in the <a href="https://youngkin.github.io/post/gpioprogramming/#addressing">Addressing section</a> above you’ll notice it doesn’t match<strong> </strong>the base address of 0x20000000 in the <em>I/O Peripherals</em> address block in <em>ARM Physical Addresses</em>. This is because the diagram in the Addressing section is for the Raspberry Pi 1. This offset is different in the Raspberry Pi models 2 &amp; 3. And it’s different yet again in the Raspberry Pi 4 model.</p><p>Moving on, in a similar manner to base_address, <strong>lines 6 to 9</strong> get the <em>length</em> by shifting from buf offsets 8 thru 11 into peri-size. For the Raspberry Pi 3B+, 0x01000000 is the expected length of the address block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/330ff7d60d8ef57cf8b2c1214d0039df/href">https://medium.com/media/330ff7d60d8ef57cf8b2c1214d0039df/href</a></iframe><p>This next code snippet completes obtaining the addressing information from /proc/device-tree/soc/ranges. Specifically it validates that the <em>“child-bus-address”</em> and <em>“parent-bus-address”</em> have the expected values. Recall that the <em>“child-bus-address”</em> is the first value in the addresses/length triplet, buf offsets 0 thru 3. Lines 1 through 6 do the following:</p><ol><li><strong>Lines 1 thru 4</strong> verify that the first 4 bytes of buf, the <em>child-bus-address</em>, is 0x7E000000 as defined by the <em>“I/O Peripherals”</em>address block in the <em>“VC CPU Bus Addresses”</em> memory space.</li><li><strong>Line 5</strong> verifies that the <em>parent-bus-address</em>, base_address, matches one of the expected base addresses for Raspberry Pi models 1 thru 4.</li></ol><p><strong>Lines 7 and 8</strong> then set the base address and length of the <em>I/O Peripherals</em> address block to the variables that will be used in the rest of the program. The important thing about this line is that it casts the source variables to the types expected by the target variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5a713b59c38ef5445827616bed10ab5/href">https://medium.com/media/b5a713b59c38ef5445827616bed10ab5/href</a></iframe><p>This next snippet maps the BCM2835’s <em>“I/O Peripherals”</em> address block in the <em>“ARM Physical Addresses”</em> memory space from /dev/memso that it can be safely used in the program.</p><p><strong>Line 1</strong> first checks to see if the user running the program is running as <em>root</em> (either <em>root</em> user or <em>sudo</em>). If not, the /dev/mem device can’t be used. /dev/mem provides unrestricted access to the CPU’s memory. As this is obviously a dangerous thing to do its use is restricted to <em>root</em>. As you may recall from the <a href="https://youngkin.github.io/post/gpioprogramming/#addressing">Addressing section</a>, there is an alternative to /dev/mem, /dev/gpio. This will be shown later in this section.</p><p><strong>Line 4</strong> opens /dev/mem in preparation to the mapping operation.</p><p><strong>Line 13</strong> assigns the bcm_peripherals variable to the offset and length, bcm_peripherals_base and bcm-peripherals_size, of the <em>I/O Peripherals</em> address block. This mapping effectively restricts the program’s access to the <em>I/O Peripherals</em> address block of physical memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5a6cfa771ebefefb536773650935edd/href">https://medium.com/media/f5a6cfa771ebefefb536773650935edd/href</a></iframe><p>This next code snippet calculates the offsets for the various types of registers (e.g., GPIO, PWM, SPI, etc). Each offset is relative to the value of bcm_peripherals which was the result of a mapmem() operation in the previous snippet. So to get the address of a register set like the GPIO register set we would add BCM_GPIO_BASE to the bcm_peripherals base address. But you may have noticed the code divides these offsets by 4 prior to adding them to bcm_peripherals. These offsets, e.g., BCM_GPIO_BASE, which are specified as integers, point to specific byte addresses, i.e., at 8 bit boundaries. bcm_peripherals is specified as a uint32_t*, a pointer. You can’t just naively add an integer to a pointer. You may recall that pointer arithmetic operates on a pointer variable based on the size of the type of the associated variable. For unint32_t&#39;s their size is 32 bits or 4 bytes. Adding 1 to a uint32_t pointer will result in that pointer pointing to the next uint32_t, which starts 4 bytes from the current position. Naively adding offsets like BCM_GPIO_BASE to bcm_peripherals will result in bcm_peripherals pointing to a position in memory that is 4 uint32_ts past the current position, not 1 uint32_t past the current position which is what we want. Which is why each register type offset like BCM_GPIO_BASE is divided by 4 prior to adding it to bcm_peripherals.</p><blockquote>If you’re new to C you may not be aware that pointer arithmetic is inherently dangerous. It can be hard to know exactly what a pointer will reference as a result of pointer arithmetic. The pointer could be an unexpected type or have an unexpected value. This can lead to unexpected behavior which can be very difficult to debug. In some cases, for example performing division, pointing to an unexpected place that contains the value zero will lead to the program abruptly ending (with a segmentation fault). This is good, this way you know something is wrong and you even know where it went wrong. A pointer may even point outside the program’s address space the program which may lead to system crashes. In our case however the register locations and associated types are very well known and using pointers is relatively safe. That is, as long as we perform pointer arithmetic correctly…</blockquote><h4>bcm_fsel()</h4><p>bcm_fsel is responsible for setting the I/O function associated for a given pin. There are a total of 8 functions available. One defines that the associated pin is to be set as an input pin meaning that it will be read from. Another function defines the associated pin as an output pin meaning the pin will be written to. The remaining 6 are referred to as “alternate functions” and are given names like “alternate function 0”. The I/O function that is assigned for the various alternate functions is different for the various GPIO pins. For example, setting BCM GPIO pin 17 to alternate function 4 defines its I/O function to be SPI. It actually defines the pin to be a specific subset of SPI functionality called chip enable or chip select, but that is a topic for a later article. Recall that in main() above the function is being set to BCM_GPIO_FSEL_OUTP which defines pin 17 to be an output pin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f775667dd1196ebd8caac076a27481f/href">https://medium.com/media/0f775667dd1196ebd8caac076a27481f/href</a></iframe><p>There’s quite a bit going on in this function even though it is quite short.</p><p><strong>Line 1</strong> defines the function as taking two parameters, pin and mode. It is fairly obvious that pin the pin whose function is to be assigned. mode is the I/O function to associate with pin. mode is actually a bit pattern to be assigned to a particular register offset. The bit pattern assignments are defined in the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">The BCM2835 I/O Peripherals datasheet</a> in section 6, <strong>GPIO</strong>. The patterns are defined as follows:</p><pre>000 = GPIO Pin X is an input<br>001 = GPIO Pin X is an output<br>100 = GPIO Pin X takes alternate function 0<br>101 = GPIO Pin X takes alternate function 1<br>110 = GPIO Pin X takes alternate function 2<br>111 = GPIO Pin X takes alternate function 3<br>011 = GPIO Pin X takes alternate function 4<br>010 = GPIO Pin X takes alternate function 5</pre><p>There is some additional background needed to understand the rest of the function. First, <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">The BCM2835 I/O Peripherals datasheet</a>, section 6, shows that a total of 54 GPIO pins are addressable via the function select registers (GPFSEL0-GPFSEL5). Each function select register is 32 bits long. Since each of the function select patterns above is 3 bits long each function select register can specify the I/O function for 10 pins with 2 bits left over. Ten pins per register and a total of 54 pins explains why there are 6 function select registers numbered 0 thru 5. The math that follows is derived from this information.</p><p><strong>Line 3</strong> defines the register offset, paddr, of the bits that will be set according to mode. BCM_GPFSEL0 is the base offset, in bytes, of the function select registers. Here’s an explanation of the arithmetic performed in this line.</p><ol><li>Notice that pointer arithmetic is being performed. Recall that the result of pointer arithmetic is based on the type of the target variable (see the bcm_init() section above). Since uint32_t&#39;s are 4 bytes long BCM_GPFSEL0 needs to be divided by 4 for the calculation to come out correctly. Hence ... paddr = bcm_gpio + BCM_GPFSEL0/4 ....</li><li>Also, recall that each register holds the function select information for 10 pins. For a given pin we need to determine which function select register, GPFSEL0 thru GPFSEL5, specifies the I/O function for a given pin. In C, the result of integer division that results in a fraction will be rounded down. So if we divide the pin number by 10, (pin/10), we’ll get the offset to the correct function select register. So pin 9 will result in 9/10 which equals 0, meaning pin 9’s function select location is in GPFSEL0. Likewise, pin 17’s, 17/10 = 1, function select register is GPFSEL1. And so on.</li></ol><p>Taken together, the equation paddr = bcm_gpio + BCM_GPFSEL0/4 + (pin/10) results in the function select register offset appropriate for a given pin. For pin 17 this will result in paddr logically pointing to GPFSEL1 at address 0x7E20 0004, 7E being the bus address, 20004 being the offset of the GPIO registers plus the offset of GPFSEL1, 4, from the beginning of the GPIO register set. I say logically because bcm_gpio is an offset from an address returned as the result of a mmap() operation. mmap() returns a pointer into the process’s virtual memory whereas 0x7E20 0004 is an address in the BCM2835’s <em>VC CPU Bus Addresses</em> space.</p><p><strong>Line 4</strong> calculates the location within the function select register for given pin’s function select value. Since we’ll use bit shifting to set the pin’s function select value this location becomes the number of bits to <strong>SHIFT</strong> the pin’s function select value as provided in the modeparameter. Building the calculation up we first need to find the pin’s logical location, that is, which 3 bit cell within the function select register (recall that each function select value is 3 bits long). The calculation for this is given by shift = (pin % 10) .... For pin 17 (pin % 17) = 7. So pin 17’s 3 bit cell is located at the 7th 3-bit offset. Next we have to find the actual bit offset within the register. Since each function select value is 3 bits long each pin’s boundary is a multiple of 3, hence the complete calculation of shift = (pin % 10) * 3. For pin 17 this results in (17%10)*3 which equals 7*3 which results in an absolute bit offset of 21. Consulting <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">the BCM2835 I/O Peripherals datasheet, section 6</a>, on page 92, we can confirm that pin 17’s offset within the GPFSEL0 register is in bit positions 21 thru 23.</p><p>Now let’s look at <strong>line 5</strong>. When setting a subset of bits to a given value we want to preserve the values of the surrounding bits. A mask is used to accomplish this. The mask contains a bit(s) that is in the position of the bit in the target value that we want to change. For example, in the bit pattern 0101 1111, if we want to set bit 6’s value from 1 to 0 we only need to define a bit sequence with 1 bit set. To create the most general solution we would just set the least significant bit(s). Since we only need a single bit set we would define the mask as hex number 0x1, which specifies the bit pattern 0000 0001. Next we need to shift this bit pattern as required so that the 1 bit is moved to the correct position. In our example, since we want to change bit 6, we would left shift the mask pattern 6 bits to the left, e.g., newMask = 0000 0001 &lt;&lt; 6. This results in newMask equaling 0100 00000, which is puts the 1 bit in position 6 as we desire. It’s possible that we could have defined the mask as 0100 0000 outright, but this would not result in a general solution that would work for any mask needed to set a bit(s) in an arbitrary bit position, such as bits 21-23.</p><p>As given in bcmfuncs.h the value of BCM_GPIO_FSEL_MASK is 0x7 or 0000 0111, this is because each GPIO function select pattern is 3 bits long. So this is a useful bit pattern for masking 3 bit sequences. If we shift this pattern by the <strong>SHIFT</strong> of 21 as calculated in line 4 above we’ll get a 32 bit pattern that looks like this, 0000 0000 1110 0000 0000 0000 0000 0000. The mask is now in bit locations 21-23, which is the location of pin 17’s function select pattern in the GPFSEL1 function select register.</p><p>In summary, <strong>line 5</strong> creates the mask needed to set the 3 bit function select pattern as specified in the mode parameter on the provided pin parameter.</p><p><strong>Line 6</strong> creates the new 3 bit value that will be placed into the GPFSEL1 register. Recall that GPFSEL1 is a 32 bit register. To use a 3 bit value such as mode to set a 3 bit sequence at an arbitrary position, e.g., bits 21-23, we create a value mask that sets the bits in the desired position to the desired value. As with the mask above, the most general solution specifies that those bits be set starting in the least significant position. Let’s say in our example we want pin 17 to be set to alternate function 1. Looking at the bit patterns above we can see that the 3 bit value for alternate function 1 is 101. The mode parameter will contain this value. To set pin 17 to alternate function 1 we need to shift mode&#39;s bit pattern of 0000 0101 21 bits to the left. As with line 5, line 6 does this in a general way, value = mode &lt;&lt; shift. Given our value of mode and the calculated value of shift we get the 32 bit value of 0000 0000 1010 0000 0000 0000 0000 0000.</p><p>So we now have the 4 variables needed to calculate the new value of the GPFSEL1 register, paddr, mode, mask, and value.</p><p><strong>Line 7</strong> calls the function bcm_peri_set_bits() to complete this operation. This operation is done in a separate function since there are other register values that require setting as we will see later.</p><h4>bcm_peri_set_bits()</h4><p>bcm_peri_set_bits() is the function that sets a 32 bit sequence, v, to a new value, value, at position paddr, using a mask as discussed above. As with bcm_fsel(), this function does quite a bit in just a few lines of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef68fe334eb55c35f4910f61c6ca23c3/href">https://medium.com/media/ef68fe334eb55c35f4910f61c6ca23c3/href</a></iframe><p><strong>Line 3</strong> uses bcm_peri_read() to read the 32 bit value v located at paddr. More on this later.</p><p><strong>Line 4</strong> sets the v to its new value. Recall that when a mask is used a subset of bits can be set while leaving the remaining bits unchanged. Line 4 does this in 3 steps. First it does a bitwise-AND operation, &amp;, between the current value v with the complement of mask. Taking the example in the previous section for BCM_GPIO_FSEL_MASK, it’s bit value, for brevity just bit positions 16 and 23, is reversed from ... 1110 0000 ... to ... 0001 1111 .... When the bitwise-AND occurs between the the complemented mask and vas in (v &amp; ~mask), only the bits 21-23 of the original value v are modified and bits 21-23 are reset to 0s. The remaining bits are unchanged. If bits 16-23 of v were originally set to ... 0100 1010 ..., the new value of bits 16-23 will now look like ... 0000 1010 .... In our example for pin 17 its function select bits have been reset to zeros. Note the bits in positions 16 thru 20 are unchanged.</p><p>The next operation, (value &amp; mask) only retains the values of the bits at positions 21-23 of the new value, value, setting the remaining bits to 0. Bits 16-23 of value are ... 1010 0000 ... which specifies pin 17 is is to be set to alternate function 1. The result of the operation ... 1010 0000 ... &amp; ... 1110 0000 ... is ... 1010 0000 ..., which is expected. The operation is specified as (value &amp; mask)because we can’t say ahead of time that only bits 21-23 are to be reset to value. Both value and mask could have bits set at other positions.</p><p>Putting this all together, the third and final step, (v &amp; ~mask) | (value &amp; mask) will OR the 2 results, ... 0000 1010 ... | ... 1010 0000 ... which results in v being reset to ... 1010 1010 .... Remember that only bits 21-23 were changed. This is shown here by bits 16-20 retaining their previous values. Likewise, the other bits of v will remain unchanged.</p><p><strong>Line 5</strong> the sets the 32 bits at paddr to v via bcm_peri_write(). More on this later as well.</p><h4>bcm_peri_read()</h4><p>bcm_peri_read() will read the 32 bits starting at paddr and return them to the caller as a 32 bit value. Unlike bcm_fsel() and bcm_peri_set_bits() this function is quite simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2f81bd348c24878cf03451814cfe98b/href">https://medium.com/media/e2f81bd348c24878cf03451814cfe98b/href</a></iframe><p><strong>Lines 4 and 6</strong> synchronize access to memory so that the read can’t be interrupted.</p><p><strong>Line 5</strong> simply sets the return value, ret, to the contents located at paddr.</p><h4>bcm_peri_write()</h4><p>bcm_peri_write() will write the 32 bits starting at paddr to the value contained in value. Like bcm_peri_read() this function is quite simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/292c582530dfaedc0e2b146b43056ecf/href">https://medium.com/media/292c582530dfaedc0e2b146b43056ecf/href</a></iframe><p><strong>Lines 3 and 5</strong> synchronize access (lock) to the 32 bits starting at paddr.</p><p><strong>Line 4</strong> sets the 32 bits located at paddr to value.</p><h4>bcm_gpio_write()</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aec5c5dba8b8266782a746a333d054e/href">https://medium.com/media/1aec5c5dba8b8266782a746a333d054e/href</a></iframe><p>bcm_gpio_write() writes the 32 bit value to the specified pin. It uses 2 helper functions, bcm_gpio_set() and bcm_gpio_clr(). The parameter on is used to specify if the value for pin should be set or cleared. There are a set of 4 GPIO registers, GPSET0 and GPSET1, and GPCLR0 and GPCLR1, which specify if the value of a pin is HIGH or LOW. HIGH corresponds to GPSETn. LOW corresponds to GPCLRn. When the value of on is 1 the GPSETn register associated with the value of pin is set to 1. If on is set to 0 then the GPCLRn register associated with the value of pin is set to 1. GPSETn’s values are only used when a pin’s I/O function is set to OUTPUT. GPCLRn’s values are likewise only used when a pin’s I/O function is set to OUTPUT. Values of 0 in these registers are ignored. Recall that the BCM2835 allows GPIO functions to be specified for 54 pins (vs. the expected 40). Since each pin requires 1 bit to specify whether it’s to be set or cleared a total of 54 bits is required. This explains why two 32 bit registers are needed for set and clear.</p><p>The use of these registers is further described in section 6, page 95, of <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">the BCM2835 I/O Peripherals datasheet</a>.</p><h4>bcm_gpio_set() and bcm_gpio_clr()</h4><p>bcm_gpio_set() and bcm_gpio_clr() are twins in terms of their functionality. They only differ in which registers they operate on. *set() operates on the GPSETn registers and *clr() operates on the GPCLRn registers. They are responsible for setting the appropriate bit offset in the appropriate register for the provided pin argument. This section will only describe bcm_gpio_set(). With the exception of the register set operated on their implementations are identical. In fact, with the addition of another parameter to specify the starting offset they could be collapsed into a single function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0548218d2a2acb50360058e196800c4c/href">https://medium.com/media/0548218d2a2acb50360058e196800c4c/href</a></iframe><p>In bcm_gpio_set() <strong>line 3</strong> calculates the address, paddr, of the target register. bcm_gpio is the starting offset of the GPIO registers. BCM_GPSET0 is the starting offset of the set and clear registers. Recall from the discussion in the bcm_init() section above that pointer arithmetic is used to determine the memory offset to use for a given operation. This is why BCM_GPSET0 is divided by 4 in this operation. pin/32 is used to calculate which of the GP*n registers is to be used for the given pin. Recall that integer division always rounds down. So the result of pin 17/32 is 0 which specifies that the first GP*n register will be used. This is consistent with the BCM2835 ARM Peripherals guide. And 0 is correct in the calculation of the paddr because of the use of integer arithmetic.</p><p><strong>Line 4</strong> calculates how large of a shift is needed to set the proper bit associated with pin in the GP*n register. Taking our example of pin 17, 17%32 is 17, which corresponds to bit 17 in GPSET0. Again, per the BCM2835 ARM Peripherals guide, this is the correct offset within the correct register.</p><p><strong>Line 5</strong> then uses bcm_peri_write() to shift 1, shift bits to the left, in order to write to the correct offset in the correct register. From the calculation on line 4, 1 is shifted 17 bits to the left.</p><h4>bcm_close()</h4><p>bcm_close deallocates all resources and resets all GPIO offsets to their original values, MAP_FAILED in this case. With regards to MAP_FAILED, this value prevents any more operations on the BCM2835 peripheral registers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f1b8bb57b8b02ab66b3c4701b765aff/href">https://medium.com/media/5f1b8bb57b8b02ab66b3c4701b765aff/href</a></iframe><p><strong>Line 3</strong> releases the memory reserved by the mapmem() operation in bcm_init().</p><p><strong>Lines 4–14</strong> reset all the register offsets to their default settings.</p><h3>Summary</h3><p>This article has provided a detailed look at how to interact directly with the BCM2835’s peripherals registers, without using a 3rd party library, to make an LED blink. It first provided an overview of the BCM2835’s ARM peripherals main concepts including the types of I/O functions that operate on external devices/peripherals, how the BCM2835 addressing works as a prerequiste for describing how to interact with the BCM2835 registers to control external devices (like an LED). It then described the lab setup needed to control an LED. Next, it presented the code, along with explanations of what the code is doing, used by the main program. It finished up by presenting the code, with explanations, that interacts directly with the BCM2835’s registers that are associated with various types of peripherals.</p><p>At this point, you should have a good understanding of how to directly program the BCM2835 to control a variety of peripheral types using the various I/O functions supported by the BCM2835. While the low-level details for a specific I/O function, e.g., SPI, may differ, the mechanics for programming the BCM2835 are the same.</p><p>Keep an eye out for my upcoming article titled “Raspberry Pi GPIO — Using SPI to display alphanumeric characters on a MAX7219 Dot Matrix Display Module” which, among other things, will demonstrate how to control a dot matrix LED display using only low-level access to the BCM2835 registers. It makes a nice companion to this article as it will introduce a new set of peripheral registers used to program the SPI I/O function.</p><p>Feedbacks about this article are welcome.</p><h3>References</h3><ul><li><a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.1_blinking_led_c.html">The Sunfounder Blinking LED project</a> is the source of the breadboard diagram. It was also the inspiration for this series on Raspberry Pi GPIO programming. See my <a href="https://youngkin.github.io/post/sunfoundergpionotesled/">Blinking LED projec</a>t for more details.</li><li><a href="https://pinout.xyz/">Raspberry Pi GPIO Pinout diagram</a> including the physical board pin numbers, the BCM/GPIO pin numbers, and the WiringPi pin numbers.</li><li><a href="https://github.com/youngkin/gpio">The gpio repository</a> containing the code for this and other articles</li><li><a href="https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up">How to setup a new Raspberry Pi from scratch</a></li><li><a href="https://www.sciencebuddies.org/science-fair-projects/references/how-to-use-a-breadboard">How to use a breadboard</a></li><li><a href="https://youngkin.github.io/categories/gpio/">GPIO programming on a Raspberry Pi 3B+</a> contains a list of my articles about GPIO programming on the Raspberry Pi</li><li><a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">The BCM2835 Peripherals guide</a>.</li><li>The C <a href="https://www.airspayce.com/mikem/bcm2835/index.html">BCM2835</a> library by Mike McCauley</li><li>The C <a href="http://wiringpi.com/">WiringPi</a> library and associated <a href="https://github.com/WiringPi/WiringPi">GitHub repository</a></li><li>The Python <a href="http://abyz.me.uk/rpi/pigpio/">pgpio</a> library</li><li>The Python <a href="https://pypi.org/project/RPi.GPIO/">RPi.GPIO</a> library</li><li>The Go <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a></li><li><a href="https://www.kernel.org/doc/html/latest/devicetree/usage-model.html">Linux and the Devicetree</a> describes what a Linux device tree is and how it is used.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33e6d9423f98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/raspberry-pi-gpio-introduction-to-programming-broadcom-bcm2835-arm-peripherals-33e6d9423f98">Raspberry Pi GPIO — Introduction To Programming Broadcom BCM2835 ARM Peripherals</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raspberry Pi GPIO Blinking LED in Golang and C]]></title>
            <link>https://medium.com/better-programming/raspberry-pi-gpio-blinking-led-in-golang-and-c-5382182fe570?source=rss-80d16197df23------2</link>
            <guid isPermaLink="false">https://medium.com/p/5382182fe570</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Richard Youngkin]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 15:47:12 GMT</pubDate>
            <atom:updated>2022-04-04T15:47:12.693Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to use Golang, C, and GPIO to make an LED blink</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nW76kQtZIspxXULmU1_Exg.png" /><figcaption>Image Credit: Author</figcaption></figure><h3>Contents</h3><ul><li>Overview</li><li>Prerequisites</li><li>Blinking LED in C</li><li>Information that would have been helpful</li><li>Blinking LED in Go</li><li>Summary</li></ul><p>This is the first article in a series that explores GPIO programming on a Raspberry Pi 3B+. You can find the full series <a href="https://youngkin.github.io/categories/gpio/">here</a>. It is a supplement to the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.1_blinking_led_c.html">Sunfounder Blinking LED project</a>. The code samples will be in Go and C.</p><h3>Overview</h3><p>I recently became interested in GPIO programming on a Raspberry Pi. It’s a nice way to see something concrete controlled by software. It’s also a nice way to learn a little bit about electronics. This is the first article in a series I intend to write to document my journey in GPIO programming.</p><p>To lower the bar to getting started I decided to purchase a GPIO/electronics kit and repurpose one of my Raspberry Pis. I chose <a href="https://www.sunfounder.com/">Sunfounder</a>, mostly because they seem to be well regarded and their kits get good reviews. I ended up choosing the <a href="https://www.amazon.com/gp/product/B09BMVT4CB/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&amp;psc=1">Sunfounder Raspberry Pi Ultimate Starter Kit</a> (AKA Raphael) because it has a good number of interesting electronic components and associated projects.</p><p>One thing I noticed right away is that most GPIO articles assume Python for the programming language. Sunfounder’s kits and associated documentation support a number of languages including Python and C, but they lean towards Python and more projects are available in Python and not so many in C. I’m primarily a Go developer so I’m also interested in implementing GPIO projects in Go.</p><p>Some of the Sunfounder kit reviews mention that the project documentation is a little sparse and short on explaining how things work. I’m just getting started and I’ve seen a little of this, but the first project, <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.1_blinking_led_c.html">Sunfounder Blinking LED project</a>, is pretty well documented. I only got hung up in a couple of spots and it didn’t take long for me to figure out what I did wrong. The second project, <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.2_rgb_led_c.html">RGB LED</a> was a bit different. It’s more complicated and much less detailed regarding explaining how and why things work. If all you want to do is follow a cookbook to implement the project it works well enough. But it’s lacking if you want to understand how and why it works in more detail. I spent quite a while working on this one trying to fill in the information missing from the project documentation. The point of this series is to fill that gap, from both coding and electronics perspectives.</p><p>The focus of this article is the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.1_blinking_led_c.html">Sunfounder Blinking LED project</a>. It’s the first project in a <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/introduction.html">set of projects targeting the Ultimate Starter/Raphael kit</a>.</p><h3>Prerequisites</h3><p>If you don’t have one, you’ll need a Raspberry Pi. I used a Raspberry Pi 3B+ with the ‘stretch’ version of the Raspbian OS. Given that the Sunfounder Ultimate Starter Kit is advertised to work with a Raspberry Pi 4, I would expect the 4 series to work as well. I’m less sure about other Raspberry Pi versions, especially versions with 26 vs. 40 GPIO pins.</p><p>Next you’ll need:</p><ul><li>a <a href="https://www.amazon.com/dp/B082KBF7MM/ref=sspa_dk_detail_4?psc=1&amp;pd_rd_i=B082KBF7MM&amp;pd_rd_w=1tGTV&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=fX8JB&amp;pf_rd_r=44DE0RS1E9FD42RBYC7R&amp;pd_rd_r=47cbdc7f-7834-455f-9429-ef74a438bd45&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFVVkdZVUZRNUw3ODkmZW5jcnlwdGVkSWQ9QTA4MzI4MzYyU0VLNzBJM0cxRUVMJmVuY3J5cHRlZEFkSWQ9QTA0Mjk1NTMzSzNSWlNFUjU0NURBJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">breadboard</a></li><li><a href="https://www.amazon.com/dp/B08HZ26ZLF/ref=syn_sd_onsite_desktop_19?psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUExRFpLWElCRjg1MUNMJmVuY3J5cHRlZElkPUEwMjMyMTE1M01aOFE3U1BQS09YSiZlbmNyeXB0ZWRBZElkPUEwODE5NTMxMktEMTlZRjEyQjBJNiZ3aWRnZXROYW1lPXNkX29uc2l0ZV9kZXNrdG9wJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">jumper wires</a></li><li><a href="https://www.amazon.com/ELEGOO-Electronics-Component-resistors-Potentiometer/dp/B01ERPXFZK/ref=sr_1_7_sspa?crid=3EJQNCOWP00IF&amp;dchild=1&amp;keywords=resistors&amp;qid=1631478270&amp;s=industrial&amp;sprefix=resis%2Cindustrial%2C219&amp;sr=1-7-spons&amp;psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEzTktVSzNYMkxMSDlKJmVuY3J5cHRlZElkPUEwMjAzMDY0NVRERkFLVjVRTUFWJmVuY3J5cHRlZEFkSWQ9QTA5MjM2NjUxUFZYQUlETVAzRDA3JndpZGdldE5hbWU9c3BfbXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">a 220 Ohm resistor</a></li><li><a href="https://www.amazon.com/ELEGOO-Electronics-Component-resistors-Potentiometer/dp/B01ERPXFZK/ref=sr_1_7_sspa?crid=3EJQNCOWP00IF&amp;dchild=1&amp;keywords=resistors&amp;qid=1631478270&amp;s=industrial&amp;sprefix=resis%2Cindustrial%2C219&amp;sr=1-7-spons&amp;psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEzTktVSzNYMkxMSDlKJmVuY3J5cHRlZElkPUEwMjAzMDY0NVRERkFLVjVRTUFWJmVuY3J5cHRlZEFkSWQ9QTA5MjM2NjUxUFZYQUlETVAzRDA3JndpZGdldE5hbWU9c3BfbXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">an LED</a></li></ul><p>You should also consider getting a <a href="https://www.amazon.com/dp/B082PRVRYR/ref=sspa_dk_detail_2?psc=1&amp;pd_rd_i=B082PRVRYR&amp;pd_rd_w=8mKhr&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=e9psa&amp;pf_rd_r=S09F37DF2G5FW8B8GX4B&amp;pd_rd_r=c065c120-e60b-45e9-b93b-f581f048cf46&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFCMzhUQ09COFI2VlMmZW5jcnlwdGVkSWQ9QTA5NjU2ODUxRDkxNEYwSTYwV09KJmVuY3J5cHRlZEFkSWQ9QTAxOTg1MTUyRUhEUlc2VzQ2VDQ4JndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">40 pin female to female with a T-Type adapter</a> to attach the GPIO outputs to the breadboard. You can use only jumper wires, but the cable will make things easier and will help prevent damage to the GPIO pins on the Raspberry Pi. If you elect not to buy the 40 pin cable with T-Type adapter you’ll need to buy <a href="https://www.amazon.com/SinLoon-Breadboard-Arduino-Circuit-40-Pack/dp/B08M3QLL3Q/ref=pd_sbs_7/143-0445142-7950409?pd_rd_w=sVLrc&amp;pf_rd_p=8b76d7a7-ab83-4ddc-a92d-e3e33bfdbf03&amp;pf_rd_r=CDM5TGJT03VKF0ZFB577&amp;pd_rd_r=8e58fd82-8503-41cf-b8f2-c78eaeb78d25&amp;pd_rd_wg=tT1U0&amp;pd_rd_i=B08M3QLL3Q&amp;psc=1">male-to-female jumper wires</a>.</p><p>Buying all these things separately will cost more than a kit however. <a href="https://www.amazon.com/dp/B06WP7169Y/ref=sspa_dk_detail_5?psc=1&amp;pd_rd_i=B06WP7169Y&amp;pd_rd_w=OZVyf&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=0V0IH&amp;pf_rd_r=623YJTBQ2CN2B2GYXQG5&amp;pd_rd_r=faa61f0f-3aec-4cf0-8e7e-d44eb1b3b92f&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyUVlDQzMzVVZBMFYxJmVuY3J5cHRlZElkPUEwMzExNzk4MUhGSjFSS0VKTlBROCZlbmNyeXB0ZWRBZElkPUEwMzYwNjg2UUdMRU44N0YzNzIwJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">Here’s a simple kit that has all of the above</a>. If you expect to follow this series I recommend buying the <a href="https://www.amazon.com/gp/product/B09BMVT4CB/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&amp;psc=1">Sunfounder Raspberry Pi Ultimate Starter Kit</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYIgjshQqjJNq5P_xNJ8ow.png" /><figcaption><em>Sunfounder Ultimate Starter/Raphael kit — Image Credit: Author</em></figcaption></figure><p>To compile and run the C program you’ll need the WiringPi libary. It’s easy to get:</p><pre>sudo apt-get install wiringpi</pre><p>Then test the installation using:</p><pre>pi@pi-node1:~/go/src/github.com/youngkin/gpio/rgbled $ gpio -v<br>gpio version: 2.50<br>Copyright (c) 2012-2018 Gordon Henderson<br>This is free software with ABSOLUTELY NO WARRANTY.<br>For details type: gpio -warranty</pre><pre>Raspberry Pi Details:<br>  Type: Pi 3B+, Revision: 03, Memory: 1024MB, Maker: Sony<br>  * Device tree is enabled.<br>  *--&gt; Raspberry Pi 3 Model B Plus Rev 1.3<br>  * This Raspberry Pi supports user-level GPIO access.</pre><p>In the above you’ll notice gpio version: 2.50. If you’re using a Rasberry Pi 4, use the instructions given in the Sunfounder <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/check_the_wiringpi_c.html">Checking the WiringPi</a>.</p><p>You will also need some basic C and Go programming knowledge as well as familiarity with logging on to a Raspberry Pi terminal, or into the desktop GUI that comes with some OS versions. Depending on the approach you take, you may need to connect a keyboard and monitor to the Raspberry Pi. I simply SSH into the Pi. You’ll also need familiarity with how to use an editor like Vi or nano.</p><p>I chose not to download the code from the Sunfounder site, preferring to write my own instead, even if all I did was copy directly from the project documentation. Due to this I created my own location to create the code. In fact, <a href="https://github.com/youngkin/gpio">my code is in Github</a>. If you do like downloading code you have the option of downloading, cloning, or forking it from my Github repository. As an added bonus, the project code written in Go is also located there. The code for this project is located at <a href="https://github.com/youngkin/gpio/tree/main/ledblink">gpio/ledblink</a>.</p><p>If you’re interested in Go development on a Raspberry Pi you’ll need to install the development environment onto the Raspberry Pi. <a href="https://www.jeremymorgan.com/tutorials/raspberry-pi/install-go-raspberry-pi/">Here’s a simple source</a> that explains how to accomplish this. This source is a little dated, but the only significant issue is with the version of Go to install. The source shows installing Go <strong>1.14.4.linux-arm64.tar.gz</strong> and <strong>1.14.4.linuxarmv6l.tar.gz</strong>. The current versions are <strong>1.17.1.linux-arm64.tar.gz</strong> and <strong>1.17.1.linuxarmv6l.tar.gz</strong>. For the Raspberry Pi 3B+ the correct choice will be <strong>1.17.1.linuxarmv6l.tar.gz</strong>. The other is intended for 64 bit systems like the Raspberry Pi 4 series.</p><p>Finally, I’m assuming a basic knowledge of Linux if you want to veer away from the cookbook style of the Sunfounder docs. For example, I won’t be explaining what <strong>root privileges</strong> are.</p><h3>Blinking LED in C</h3><p>As mentioned above, this article is about the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.1_blinking_led_c.html">Blinking LED project</a>. The Sunfounder documentation for this project is quite good. You should start with the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/introduction.html">Introduction</a> and work your way through the following sections up to and including the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/play_with_c.html">Play with C</a> section. You should set up the breadboard as described in the project documentation or in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*bCr41y0djDkilkWYoCf0pg.png" /><figcaption><em>Sunfounder Blinking LED breadboard setup — Image Credit: </em><a href="http://_images/image49.png"><em>Sunfounder</em></a></figcaption></figure><p>Since the Sunfounder project documentation is so good, I only have a couple of comments.</p><h3>Information that would have been helpful</h3><p>The documentation for the project states “<em>Therefore, to turn on an LED, we need to make GPIO17 low (0V) level.</em>”. What it doesn’t explain is why. The reason is that the 220 Ohm resistor is connected on one side to a 3.3 volt power source and the LED anode (positive terminal) on the other. And GPIO17 is connected to the LED’s cathode (negative terminal). LEDs only illuminate when current flows from the anode to the cathode. GPIO pins on the Raspberry Pi, e.g., GPIO17, generally have a default state of HIGH (3.3 volts). With the connection of the 3.3 volt power source to the anode and the 3.3 volt GPIO17 pin on the cathode side, no current will flow through the circuit. So the LED will not turn on. Setting GPIO17 to LOW, 0 volts, allows the current to flow, lighting the LED.</p><p>This is a minor point, but the program does not need to be run with root (sudo) privileges. Simply running ./BlinkingLed, vs. sudo ./BlinkingLed, will work. This is not always true for GPIO programs. I’ll point that out when running a program that does require root privileges.</p><h3>Blinking LED in Go</h3><p>This version of Blinking LED will work with the same breadboard setup as the C version.</p><p>First things first, we need a Go library to drive the GPIO interface. I’m using <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> for several reasons:</p><ol><li>It seems to be in fairly wide use</li><li>It seems to be fairly complete</li><li>It’s relatively active</li><li>It comes with example code and good documentation</li><li>Its API is similar to WiringPi’s</li></ol><p>Another option is <a href="https://github.com/periph/host">periph</a> (code) with <a href="https://periph.io/">documentation</a>. It is more active and the documentation is very good, better than go-rpio. This project would be trivial to do using periph. Overall, for the LED examples I was able to find, go-rpio better matched what I was looking for, especially with regard to the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.2_rgb_led_c.html">RGB LED</a> using Pulse Width Modulation (PWM, more on this in the next article in the series). But this is an excellent alternative to go-rpio and vice-versa.</p><p>You can just use the <a href="https://github.com/stianeikeland/go-rpio/blob/master/examples/blinker/blinker.go">rpio-go blinker.go example</a>. It uses rpio.Pin.Toggle(). I created a <a href="https://github.com/youngkin/gpio">Github respository</a> that contains examples in both C and Go. My Go version of blinker uses direct writes instead of rpio.Pin.Toggle. I thought showing an optional way to do this would be helpful, especially since later projects will use direct writes. My <a href="https://github.com/youngkin/gpio">gpio respository</a> uses Go’s module system which will automatically download the rpio-go library when built. Here’s my version of blinker. I won’t be explaining Go sytax as I’m assuming familiarity with Go.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/642d65468ef213ece53c3871b119c6c7/href">https://medium.com/media/642d65468ef213ece53c3871b119c6c7/href</a></iframe><p>Line 15 imports to go-rpio library which provides the capability needed to interact with the GPIO board.</p><pre>&quot;github.com/stianeikeland/go-rpio/v4&quot;</pre><p>The rest of the program is explained through embedded comments. The program can be run typing go run blinkingled.go at the command prompt and hitting enter.</p><p>This article has shown how to configure a breadboard with an LED that can be controlled by programs written in both C and Go. Feel free to suggest changes or ask questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5382182fe570" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/raspberry-pi-gpio-blinking-led-in-golang-and-c-5382182fe570">Raspberry Pi GPIO Blinking LED in Golang and C</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raspberry Pi GPIO in Go and C — Using a Shift Register & 7 Segment Display]]></title>
            <link>https://medium.com/better-programming/raspberry-pi-gpio-in-go-and-c-using-a-shift-register-7-segment-display-aa8ad85dec70?source=rss-80d16197df23------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa8ad85dec70</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Richard Youngkin]]></dc:creator>
            <pubDate>Tue, 23 Nov 2021 15:28:33 GMT</pubDate>
            <atom:updated>2021-11-23T15:28:33.586Z</atom:updated>
            <content:encoded><![CDATA[<h3>Raspberry Pi GPIO in Go and C — Using a Shift Register and 7 Segment Display</h3><h4>What are shift registers &amp; 7-Segment LEDs and how to program them on a Raspberry Pi using C &amp; Golang</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4L2IjxS6coO0UK9o7PpMw.png" /><figcaption>Image Credit: Author</figcaption></figure><h3>Contents</h3><ul><li>Overview</li><li>Prerequisites</li><li>Information that would have been helpful</li><li>What is a 7-segment display?</li><li>What is a shift register and what is it good for?</li><li>How does this project use the shift register and 7-segment display?</li><li>Setup and Code</li><li>Shift Register/7-Segment Display in C</li><li>Shift Register/7-Segment Display in Go</li><li>Summary</li><li>References</li></ul><h3>Overview</h3><p>This is the fourth article in a series that explores GPIO programming on a Raspberry Pi 3B+. It is a supplement to the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.4_7-segment_display_c.html">Sunfounder 7-Segment Display</a> project. You can find the full series <a href="https://youngkin.github.io/categories/gpio/">here</a>. The code for the series can be found on <a href="https://github.com/youngkin/gpio">github</a>.</p><p>Like the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.2_rgb_led_c.html">Sunfounder RGB LED</a> project, there are some complicated aspects to this project that aren’t well covered in the Sunfounder project documentation. The purpose of this article is to fill those gaps, specifically:</p><ol><li>What is a “shift register” (the 74HC595 chip)?</li><li>What are the uses of a shift register?</li><li>What is a 7-segment display?</li><li>How is a shift register used on conjunction with a 7-segment display?</li></ol><p>An additional goal of this article is to provide a more complete example of the capability of shift registers and 7-segment displays using a program written in C. This program is significantly more advanced in this area than the Sunfounder code. This article will also provide this same program written in Go.</p><p>If you haven’t worked with LEDs before you should consider having a look at my <a href="https://youngkin.github.io/post/sunfoundergpionotesled/">Raspberry Pi GPIO in Go and C — Blinking LED</a> first. That article covers the basics of using an LED with Raspberry Pi GPIO and the associated C and Go libraries which isn’t discussed in this article.</p><h3>Prerequisites</h3><p>This section is repeated in all articles in my <a href="https://youngkin.github.io/categories/gpio/">Raspberry Pi GPIO series</a>. If you’ve already completed a project from one of these articles you can skim this section, looking only for required items not included in other projects, specifically the shift register and 7-segment display.</p><p>If you don’t have one, you’ll need a Raspberry Pi. I used a Raspberry Pi 3B+ with the ‘Stretch’ version of the Raspbian OS. The Raspberry Pi website has instructions on how to <a href="https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up">setup a new Raspberry Pi from scratch</a> if you decide to go that way vs. buying a complete kit.</p><p>Other items you’ll need include:</p><ul><li>a <a href="https://www.amazon.com/dp/B082KBF7MM/ref=sspa_dk_detail_4?psc=1&amp;pd_rd_i=B082KBF7MM&amp;pd_rd_w=1tGTV&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=fX8JB&amp;pf_rd_r=44DE0RS1E9FD42RBYC7R&amp;pd_rd_r=47cbdc7f-7834-455f-9429-ef74a438bd45&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFVVkdZVUZRNUw3ODkmZW5jcnlwdGVkSWQ9QTA4MzI4MzYyU0VLNzBJM0cxRUVMJmVuY3J5cHRlZEFkSWQ9QTA0Mjk1NTMzSzNSWlNFUjU0NURBJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">breadboard</a> <em>(You may find </em><a href="https://www.sciencebuddies.org/science-fair-projects/references/how-to-use-a-breadboard"><em>this tutorial on breadboards</em></a><em> helpful)</em>,</li><li>some <a href="https://www.amazon.com/dp/B08HZ26ZLF/ref=syn_sd_onsite_desktop_19?psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUExRFpLWElCRjg1MUNMJmVuY3J5cHRlZElkPUEwMjMyMTE1M01aOFE3U1BQS09YSiZlbmNyeXB0ZWRBZElkPUEwODE5NTMxMktEMTlZRjEyQjBJNiZ3aWRnZXROYW1lPXNkX29uc2l0ZV9kZXNrdG9wJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">jumper wires</a>,</li><li>a <a href="https://www.amazon.com/Resistor-Tolerance-Resistors-Assortment-Certificated/dp/B08QR72BFW/">220 Ohm resistor</a>,</li><li>a <a href="https://www.amazon.com/Texas-Instruments-SN74HC595N-Registers-3-State/dp/B01J6WI7RA">74HC595 shift register</a></li><li>a <a href="https://www.amazon.com/microtivity-7-segment-Display-Common-Cathode/dp/B004S95VJE/">common cathode 7-segment display</a></li><li>You should also consider getting a <a href="https://www.amazon.com/dp/B082PRVRYR/ref=sspa_dk_detail_2?psc=1&amp;pd_rd_i=B082PRVRYR&amp;pd_rd_w=8mKhr&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=e9psa&amp;pf_rd_r=S09F37DF2G5FW8B8GX4B&amp;pd_rd_r=c065c120-e60b-45e9-b93b-f581f048cf46&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFCMzhUQ09COFI2VlMmZW5jcnlwdGVkSWQ9QTA5NjU2ODUxRDkxNEYwSTYwV09KJmVuY3J5cHRlZEFkSWQ9QTAxOTg1MTUyRUhEUlc2VzQ2VDQ4JndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">40 pin female to female with a T-Type adapter</a> to attach the GPIO outputs to the breadboard. You can use only jumper wires, but the T-Type adapter will make things easier and will help prevent damage to the GPIO pins on the Raspberry Pi. If you elect not to buy the 40 pin cable with T-Type adapter you’ll need to buy <a href="https://www.amazon.com/SinLoon-Breadboard-Arduino-Circuit-40-Pack/dp/B08M3QLL3Q/ref=pd_sbs_7/143-0445142-7950409?pd_rd_w=sVLrc&amp;pf_rd_p=8b76d7a7-ab83-4ddc-a92d-e3e33bfdbf03&amp;pf_rd_r=CDM5TGJT03VKF0ZFB577&amp;pd_rd_r=8e58fd82-8503-41cf-b8f2-c78eaeb78d25&amp;pd_rd_wg=tT1U0&amp;pd_rd_i=B08M3QLL3Q&amp;psc=1">male-to-female jumper wires</a>. Buying all these things separately will cost more than a kit however.</li></ul><p><a href="https://www.amazon.com/dp/B06WP7169Y/ref=sspa_dk_detail_5?psc=1&amp;pd_rd_i=B06WP7169Y&amp;pd_rd_w=OZVyf&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=0V0IH&amp;pf_rd_r=623YJTBQ2CN2B2GYXQG5&amp;pd_rd_r=faa61f0f-3aec-4cf0-8e7e-d44eb1b3b92f&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyUVlDQzMzVVZBMFYxJmVuY3J5cHRlZElkPUEwMzExNzk4MUhGSjFSS0VKTlBROCZlbmNyeXB0ZWRBZElkPUEwMzYwNjg2UUdMRU44N0YzNzIwJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">Here’s a simple kit</a> that has all (most?) of the above. The photo of the kit appears to show a shift register, but I can’t be sure. I’m finding the <a href="https://www.amazon.com/gp/product/B09BMVT4CB/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&amp;psc=1">Sunfounder Raspberry Pi Ultimate Starter Kit</a> especially useful. NOTE: The Ultimate Starter Kit and the Raphael Kit are the same product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IOC3nrXvkgY0xxI-.png" /><figcaption>Image Credit: <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.4_7-segment_display_c.html">Sunfounder</a></figcaption></figure><p>You will also need some basic C and Go programming knowledge as well as familiarity with logging on to a Raspberry Pi terminal, or into the desktop GUI that comes with some OS versions. Depending on the approach you take, you may need to connect a keyboard and monitor to the Raspberry Pi. I simply SSH into the Pi. You’ll also need familiarity with how to use an editor like vim or nano.</p><p>To compile and run the C program you’ll need the <a href="https://github.com/WiringPi">WiringPi</a> library. It’s easy to get:</p><pre>sudo apt-get install wiringpi</pre><p>Then test the installation using:</p><pre>pi@pi-node1:~/go/src/github.com/youngkin/gpio/rgbled $ gpio -v<br>gpio version: 2.50<br>Copyright (c) 2012-2018 Gordon Henderson<br>This is free software with ABSOLUTELY NO WARRANTY.<br>For details type: gpio -warranty</pre><pre>Raspberry Pi Details:<br>  Type: Pi 3B+, Revision: 03, Memory: 1024MB, Maker: Sony<br>  * Device tree is enabled.<br>  *--&gt; Raspberry Pi 3 Model B Plus Rev 1.3<br>  * This Raspberry Pi supports user-level GPIO access.</pre><p>In the above you’ll notice gpio version: 2.50. If you’re using a Rasberry Pi 4, use the instructions given in the Sunfounder <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/check_the_wiringpi_c.html">Checking the WiringPi</a>.</p><p>WiringPi is unique in that it includes a command line tool, gpio, as shown above, that can be used to manage, control, and query the GPIO board. This can be very handy. See the <a href="http://wiringpi.com/the-gpio-utility/">gpio reference</a> for more information on what it can do and how to use it.</p><p>If you’re interested in Go development on a Raspberry Pi you’ll need to install the development environment onto the Raspberry Pi. <a href="https://www.jeremymorgan.com/tutorials/raspberry-pi/install-go-raspberry-pi/">Here’s a simple source</a> that explains how to accomplish this. This source is a little dated, but the only significant issue is with the version of Go to install. The source shows installing Go <strong>1.14.4.linux-arm64.tar.gz</strong> and <strong>1.14.4.linuxarmv6l.tar.gz</strong>. The current versions are <strong>1.17.1.linux-arm64.tar.gz</strong> and <strong>1.17.1.linuxarmv6l.tar.gz</strong>. For the Raspberry Pi 3B+ the correct choice will be <strong>1.17.1.linuxarmv6l.tar.gz</strong>. The other is intended for 64 bit systems like the Raspberry Pi 4 series. You can find current ARM versions of Go at the <a href="https://golang.org/dl/">Golang download site</a>.</p><p>For Go development you’ll also need the <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> library.</p><p>If you want to veer away from the cookbook style of the Sunfounder docs you’ll need some basic knowledge of Linux . For example, I won’t be explaining what <strong>root privileges</strong> are.</p><h3>Information that would have been helpful</h3><p>The <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.4_7-segment_display_c.html">Sunfounder 7-Segment Display</a> project documentation pretty much just jumps into how to wire up the breadboard and the code without mentioning much about the hardware components, especially the shift register. Even the code description was a little confusing given my lack of knowledge about shift registers. I accidentally stumbled across the <a href="https://docs.sunfounder.com/projects/electronic-kit/en/latest/lesson_19_7-segment.html">Sunfounder 7-Segment Python</a> project documentation that did provide some useful information on the 7-segment display, but still no mention of the shift register. This project could easily be done without the shift register, in fact many <a href="https://www.circuitbasics.com/arduino-7-segment-display-tutorial/">other articles on 7-segment displays</a> do just that. So why does the project use a shift register? Why not just wire the 7-segment display directly to the GPIO pins? Clearly there’s something to the shift register and I wanted to know what that was. It turns out, for me anyway, that this project is really about shift register with the 7-segment display being merely a tool to visualize how shift registers work. But before we get to shift registers, let’s have a short discussion about 7-segment displays.</p><h3>What is a 7-segment display?</h3><p>So what is a 7-segment display? Well, to be pedantic, it has 8 segments if you include the decimal point on the device. That aside, it’s a common device you’re already familiar with having seen them used in everything from clocks to calculators and other devices that need a numeric display. In terms of the physical implementation there are a few details we need to know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*t3OWzqMWMIYmLpZp.png" /><figcaption>Pinout diagram — <a href="https://www.circuitbasics.com/arduino-7-segment-display-tutorial/"><em>Image Credit: Circuit Basics</em></a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/0*WS2RDHB5DQXSNNZ7.png" /><figcaption>LED ID diagram — <a href="https://www.circuitbasics.com/arduino-7-segment-display-tutorial/"><em>Image Credit: Circuit Basics</em></a></figcaption></figure><p>First of all, the first diagram above shows the pinout designations for the 7-segment display. This diagram shows the middle pins on the top and the bottom with a (-) annotation. This designates those pins to be the ground pins for the display. The letters on the remaining pins correspond to the letters in the lower LED ID diagram. For example, applying power to the ‘A’ pin on the display will light up the LED labeled ‘A’ in the lower LED ID diagram. The letters “DP” stand for decimal point.</p><p>For this project we need what is known as a common cathode 7-segment display. This is what the diagram above is showing <em>(the middle pins on the top and the bottom have a (-) annotation)</em>. All this means is that all the negative terminals of the LEDs in the display are connected to a common ground pin. Common anode is the other type, which as you might expect, means all the LEDs’ positive terminals are connected to the same pin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*gKiP7ezNVdp64pNL.png" /><figcaption>Determining common cathode or common anode — <a href="https://www.circuitbasics.com/arduino-7-segment-display-tutorial/"><em>Image Credit: Circuit Basics</em></a><em> &amp; </em><a href="https://fritzing.org/"><em>Fritzing</em></a></figcaption></figure><p>If you’re using the Sunfounder kit the 7-segment display is a common cathode display. If you got a 7-segment display from another source you might want to verify it’s type. Determining whether a 7-segment display is a common cathode or common anode is fairly easy to do. Paraphrasing from <a href="https://www.circuitbasics.com/arduino-7-segment-display-tutorial/">How to set up seven segment displays on the Arduino</a>, the steps are as follows:</p><blockquote>While the above diagram shows an Arduino, hooking it up to a Raspberry Pi is very similar.</blockquote><ol><li>Connect the power from the Raspberry Pi as shown above (or to the breadboard’s power bus).</li><li>Connect a resistor between the 2 sides of the breadboard, or from the power bus to one side of the breadboard.</li><li>Connect a jumper wire (red) on the far end of the resistor from the power source.</li><li>Connect a jumper wire (black) to the Raspberry Pi’s GPIO ground pin.</li><li>Connect the black jumper wire (ground) to the middle pin, top or bottom, of the display.</li><li>Connect the red jumper wire (positive) to any of the other pins (except the middle pin!).</li></ol><p>If an LED lights up the display is a common cathode.</p><blockquote>If an LED doesn’t light up, try these steps:</blockquote><ol><li>Disconnect the jumpers from the display</li><li>Connect the red jumper to one of the middle pins, top or bottom</li><li>Connect the black wire to one of the other pins.</li></ol><blockquote>At this point an LED should light up and you’ve verified that the display is a common anode display. If no LED lights up then double-check your wiring.</blockquote><p><a href="https://youtu.be/Fa7BHbPAM98">This YouTube video</a> shows how to accomplish this using a multimeter instead of wiring up a breadboard as described above.</p><h3>What is a shift register and what is it good for?</h3><p>There are <a href="https://www.elprocus.com/what-is-a-shift-register-different-types-counters-and-applications/">several types of shift registers</a>. For this project we’re using what’s known as a “Serial In, Parallel Out” (SIPO) shift register. This type of shift register converts a serial input into a parallel output. For example, several pulses of a signal generated on a single Raspberry Pi GPIO pin can be accumulated by the shift register and then sent as a single parallel output to a 7-segment display. This is exactly what is being done in this project.</p><p>So why use a shift register? Well for one, as noted above, it only takes one GPIO pin to drive 8 pins on a 7-segment display <em>(not quite true, this will be explained in more detail farther into the article)</em>. Versions of this project without a shift register take 8 GPIO pins to accomplish the same thing. So, one use of a shift register is to conserve GPIO pins. This is especially true of LED displays with a very large number of LEDs that perhaps wouldn’t be usable due to a lack of available GPIO pins. Although this isn’t true of a 7-segment display, some devices only take parallel input. So for this kind of situation, a SIPO shift register is mandatory in converting a serial source into a parallel output.</p><h4>Shift register anatomy</h4><p>The 74HC595 shift register has a couple of logical components that are pertinent to this article:</p><ul><li>Input shift register — This is a series of connected flip-flop devices that receive incoming (serial) data on the receipt of each synchronizing clock pulse (more about this later). This register is comprised of outputs that are named in sequence from Qa’ to Qh’, i.e., Qa’, Qb’, …, Qh’.</li><li>Output or storage register — This is another series of connected flip-flop devices that transfer the serial data in parallel to a connected device. This register is comprised of outputs that are named in sequence from Qa to Qh, and Qh’ (more on Qh’ below).</li></ul><p>This anatomy is shown graphically in the following, albeit somewhat complex, diagram from the <a href="https://www.ti.com/lit/ds/symlink/cd74hc595.pdf?ts=1636840974607&amp;ref_url=https%253A%252F%252Fwww.google.com%252F">Texas Instruments CD74HC595 8-Bit Shift Registers with 3-State Output Registers datasheet</a>. The first column of 8 boxes to the left, labeled C1 or C2, comprise the input shift register. The second column of 8 boxes to the right, labeled C3, comprise the output shift register. The output register’s output pins can be seen at the far right, labeled Qa through Qh, and Qh’. The input and control channels, as shown by OE, RCLK, SRCLR, SRCLK, and SER in the upper left of the diagram, are discussed in more detail below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sTAlIzqjp6U9SDT_.png" /><figcaption><a href="https://www.ti.com/lit/ds/symlink/cd74hc595.pdf?ts=1636840974607&amp;ref_url=https%253A%252F%252Fwww.google.com%252F%22"><em>TI CD74HC595 schematic diagram — Image Credit: Texas Instruments</em></a></figcaption></figure><p>More information pertaining to the Q* names for the registers’ outputs is provided below.</p><p>It is a little confusing for the entire device to be called shift register as well as the input component to also be called shift register. To differentiate between the two, if it’s not clear from the context, I’ll make sure to reference which one I’m referring to when the term is used later in the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PFuu5EqPRYY1J5SG.png" /><figcaption>74HC595 pinout diagram — <a href="https://www.ti.com/lit/ds/symlink/cd74hc595.pdf?ts=1636840974607&amp;ref_url=https%253A%252F%252Fwww.google.com%252F%22"><em>Image Credit: Texas Instruments</em></a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RaV-9KGosBDXh8ej.png" /><figcaption>SN744HC595N photograph — Image Credit: Author</figcaption></figure><p>The first diagram above shows the pinouts for a SN74HC595 shift register. The photo in the SN74HC595N diagram above is in the same orientation as the pin diagram, namely GND is in the lower left, Vcc is in the upper right, and the “notch” is at the top center. The pins in the above diagrams are defined as follows:</p><ul><li><strong>Pin 15</strong> (right side, 2nd from the top), Qa, is the first output pin. Qa is also known as Q0.</li><li><strong>Pins 1–7</strong>, Qb-Qh, are the remaining output pins. Notice that there are 8 output pins (including Qa above). Having 8 outputs makes this an 8-bit shift register. Qb-Qh are also known as Q1-Q7.</li><li><strong>Pin 8</strong>, GND is the ground pin.</li><li><strong>Pin 16</strong>, Vcc, is the power-in pin.</li><li><strong>Pin 14</strong>, SER, is the serial input pin. This is the pin that takes the incoming serial data pulses from the Raspberry Pi. This is sometimes referred to as DS, SI, or SDI.</li><li><strong>Pin 11</strong>, SRCLK, is the pin that accepts the synchronization signal that indicates 1 bit of data has been transmitted to the SER pin. This type of signal is called a clock. SRCLK stands for shift register clock. SRCLK is also known as sh_cp.</li><li><strong>Pin 12</strong>, RCLK, is the pin that accepts the synchronization signal that indicates all 8 shift register bits have been populated and it’s time to transfer the bits, in parallel, to the output/storage register and thereby to the device connected to the output pins, Qa-Qh. RCLK is also known as st_cp or latch.</li><li><strong>Pin 10</strong>, SRCLR, is used to clear the current values of the shift register. SRCLR stands for shift register clear. SRCLR is also known as MR. If clearing the shift register is not required it can be connected to the power source which generates a HIGH signal (or 1). To clear the shift register the SRCLR pin is set to LOW (or 0). It must be set back to HIGH before the shift register is functional again.</li><li><strong>Pin 13</strong>, OE, is used to block the availability of the output or storage register. The OE pin’s effect is temporary. When it’s set to LOW (0) the data in the output register is accessible. When it’s HIGH(1) the data is not accessible. Setting it from HIGH to LOW makes the data once again accessible. Unlike the SRCLR pin, it does not clear the register. If disabling the output register is not required it can be connected to ground.</li><li><strong>Pin 9</strong>, Qh’, is used to daisy chain multiple shift registers. For example, imagine a project that needed to control 16 LEDs in a parallel fashion. In this case a single 8-bit shift register is inadequate, we need 2 that can communicate in some manner. We can get the other required 8 bits from a second 8-bit shift register. To link the 2 shift registers we connect the Qh’ output from the first, to pin 14, SER, on the second shift register. Daisy chaining shift registers is beyond the scope of this project, but you can read more about it on <a href="https://www.electroschematics.com/multiple-shift-registers-arduino-part-1/">Multiple Shift-out Registers on Arduino — part 1</a>.</li></ul><h4>Shift register in operation</h4><p>As stated above, input data is stored in the input shift register. Data is transferred on each pulse of the SRCLK input. When an SRCLK input is received, data on a prior Q*’ pin is shifted to the next Q*’ register in the sequence. When the input shift register has been populated an RCLK signal causes all of the input register contents to be transferred to the output register. The following table illustrates this behavior. To keep things simple, I’m limiting the example to 4 bits, Qa* to Qd*. The input bit sequence will be 1011. The first bit, 1, will be transmitted at time <em>t0</em>. The transmitted bits are indicated in parentheses next to the time indication (e.g., t0(1)). The 4 bits become available at the output register on a signal from RCLK at t4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*c_IGw7u1yGZ8OaGkyAtLDg.png" /><figcaption>Operation of shift register — Image Credit: Author</figcaption></figure><p>Notice that in the output sequence of bits, if the output bits are read from Qa to Qd, the bit sequence is reversed. That is, 1101 vs. the input sequence of 1011. This manner of shifting is called Most Significant Bit (MSB) shifting. It starts with the leftmost bit as in this example. This must be kept in mind or unexpected results may occur. It is possible to shift in a more intuitive way, Least Significant Bit (LSB). To do this the shifting must start with the least, or rightmost, input bit. In C &amp; Go, MSB shifting is done using the &lt;&lt; shift operator. LSB shifting is done by using the &gt;&gt; shift operator. The impact of shift method will become more obvious when we get to how the shift register (not the input shift register) is used in conjunction with the 7-segment display. <a href="https://en.wikipedia.org/wiki/Bit_numbering">See Wikipedia for more about MSB and LSB</a>.</p><blockquote>As noted previously, I simplified things a little bit when I stated above that only one Raspberry Pi GPIO pin is needed to drive the 8 LED segments in the 7-segment display. The one pin I identified is used for the SER (serial data in) pin. A minimum of 2 more are needed; 1 for the SRCLK pin and the other for the RCLK pins. As shown above these are required to advance the clock on the input shift register and transfer data from the input shift register to the output register respectively. So that’s now 3 pins to drive the 8 LEDs on the 7-segment display. This is still a good tradeoff. But 2 more GPIO pins are needed if the SRCLR and OE pins are needed. So now that’s 5 GPIO pins to drive 8 LED segments. Still a net gain of 3 pins. However, the savings become even greater when shift registers are daisy-chained as discussed above. Without requiring additional GPIO pins it is possible to control 16 or even more LEDs from those 5 GPIO pins. The savings become more significant as more devices, e.g., LEDs, need to be controlled.</blockquote><h3>How does this project use the shift register and 7-segment display?</h3><p>This project uses the shift register component to capture serial input, accumulate it until 8 bits are written, and then make it available to the output register. Since the shift register component is wired to the 7-segment display, the contents of the output register are made available to the 7-segment display, controlling what is ultimately displayed. The details of the pin connections from the shift register component to the 7-segment display pins, coupled with the shift method used, MSB in this case, dictate what LEDs will be illuminated on the 7-segment display. The following table provides the specific pin assignments as well as what the final values at the output register will be given that the input number is 0x3f, 0011 1111, is used with MSB shifting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*mAVmluD6Afbr7aKOOcQZGg.png" /><figcaption>Shift Register to 7-Segment Display Value Mapping — Image Credit: Author</figcaption></figure><p>Using the diagrams below we can ascertain what number will be displayed at the 7-segment LED.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*xtZGyxQrGFuBJaVD.png" /><figcaption>7-Segment Display pinout diagram — <a href="https://www.circuitbasics.com/arduino-7-segment-display-tutorial/"><em>Image Credit: Circuit Basics</em></a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/0*C-jo6N0thZ8hB7MB.png" /><figcaption>7-Segment Display LED ID diagram — <a href="https://www.circuitbasics.com/arduino-7-segment-display-tutorial/"><em>Image Credit: Circuit Basics</em></a></figcaption></figure><p>7-segment display pins A-F will have the value 1, G and DP will have the values 0. Mapping this to the above LED Identification diagram we can see that the number displayed will be 0.</p><h3>Setup and Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NkTQJ3WqF4-nlNQ0.png" /><figcaption><em>Sunfounder wiring diagram — </em><a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.4_7-segment_display_c.html"><em>Image Credit — Sunfounder</em></a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-e99aUrYhubV5zD3.png" /><figcaption><em>Actual wiring (mostly) — Image Credit: Author</em></figcaption></figure><p>The breadboard should be wired as illustrated in the above diagram <em>(as indicated in the </em><a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.4_7-segment_display_c.html"><em>Sunfounder 7-Segment Display</em></a><em> project documentation)</em>. One very important thing to note, something that I spent way too much time debugging, is that the resistor connecting the ground pin on the 7-segment display must be connected to the ground or negative bus on the breadboard. In all my prior projects I’ve connected the resistor to the positive breadboard bus. I initially missed this detail and the 7-segment display didn’t display anything. One other thing I got wrong on the initial wiring is that I had the 74HC595 output register pins connected incorrectly to the 7-segment display. This is easy to do. I debugged this by noting which LED segments lit up for which expected number. After going through several numbers it became apparent that I had the ‘G’ and ‘E’ pins on the 7-segment display reversed.</p><p>If you’re unfamiliar with breadboards and breadboard diagrams this <a href="https://www.sciencebuddies.org/science-fair-projects/references/how-to-use-a-breadboard">breadboard tutorial </a>should be helpful.</p><h3>Shift Register/7-Segment Display in C</h3><p>This code is quite different from the Sunfounder code. This is because I chose to add several capabilities including:</p><ol><li>Support for an interrupt handler. This will gracefully exit the program by clearing the input shift register thereby turning off all the LEDs. The Sunfounder program will leave the LEDs in whatever state they were in when that version exits.</li><li>It supports setting both the SRCLR and OE shift register pins.</li><li>It adds support for illuminating the decimal point in the 7-segment display.</li><li>It add several functions that provide the ability to test different capabilities of the 74HC595 shift register including using the SRCLR and OE pins.</li><li>It accepts user input from the keyboard allowing the user to specify how they’d like the program to drive the shift register and hence the LED. This includes things like clearing the input shift register, disabling and reenabling the output register as well as writing all hexadecimal digits/decimal point as well as writing an 8. to the display.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c4ac9b6ca6bdcdeb89ca3033c29394d/href">https://medium.com/media/6c4ac9b6ca6bdcdeb89ca3033c29394d/href</a></iframe><p>Most of this is pretty well explained by the embedded comments, but I’ll mention of few highlights.</p><p>Lines 12 and 13 provide information on how to build and run the program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6ArCGoZDKr-DcSQF.png" /><figcaption>74HC595 Pinout Diagram — <a href="https://www.ti.com/lit/ds/symlink/cd74hc595.pdf?ts=1636840974607&amp;ref_url=https%253A%252F%252Fwww.google.com%252F%22"><em>Image Credit: Texas Instruments</em></a></figcaption></figure><p>Lines 27 and 28 define the GPIO pins that drive the SRCLR and OE pins respectively. Note that the GPIO pin numbers are the <a href="https://github.com/WiringPi/WiringPi">WiringPi</a> pin numbers. If you decide you want to see this behavior in action, wire pin 24 to the SRCLR shift register pin, and wire pin 29 to the OE shift register pin instead of positive and ground respectively.</p><p>Lines 32 and 33 define an array, SegCode, that contains the hexadecimal numbers that will be shifted into the shift register in order to display a number that matches the index of a particular number in the array. For example, to display an 8 SegCode[8] should be used. Note that these numbers reflect the use of the MSB form of shifting. The numbers would be different if the LSB shifting form were used. For example, the number to use to display 0, as shown on line 32, is 0x3F (0011 1111). To display 0 using the LSB method the hex number 0xFC(1111 1100) and the C right-shift operator, &gt;&gt;, should be used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48ad3cc55c3cf7566347aeca80e22b23/href">https://medium.com/media/48ad3cc55c3cf7566347aeca80e22b23/href</a></iframe><p>This next code snippet shows the initialization of the shift register. In a nutshell, all the pins we’re using are placed in OUTPUT mode so we can write to them. Next, all pins except for the SRCLR pin are set to LOW (0). Recall that the SRCLR pin must be set to HIGH for the shift register to be operational.</p><blockquote>The alternative to pin mode OUTPUT is PWM (Pulse Width Modulation). Since PWM simulates lower voltages by rapidly pulsing the associated pin it’s not suitable for use with shift registers. Recall that a pulse to the SRCLK and RCLK pins represents a clock advancing. Using PWM, and the resulting rapid pulsing, would interfere with the clocks advancing in a reliable manner.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e39f7a50584bd424ea1b1ef70554c5aa/href">https://medium.com/media/e39f7a50584bd424ea1b1ef70554c5aa/href</a></iframe><p>This code snippet demonstrates 2 methods of turning off all the LEDs in the 7-segment display. Specifically, it shows how to use both the SRCLR pin and writing zeros to all the input shift register bits to clear the input shift register that will result in the 7-segment display showing nothing.</p><p>In shiftRegClr, lines 1 through 11, note the use of the RCLK pin on lines 4 and 6. The clock signal to that pin must be pulsed, i.e., set to HIGH followed by LOW, in order to make the input shift register contents available to the output register. Also note that the SRCLR pin needs to be reset to HIGH after the operation to reenable the shift register.</p><p>Lines 16 through 28 show the method of writing zeros to all the input shift register bits to clear the input shift register (zeroClear()). This is functionally equivalent to using the SRCLR method, they both set the input shift register bits to 0. It does take a lot more effort however. The for loop in lines 18 through 23 shifts a zero into each bit of the input shift register. It repeats the process 8 times, advancing the SRCLK with each write, to fill the input shift register bits. Lines 20 and 22 send the SRCLK pulse to advance the input shift register bits. Strictly speaking, it’s not necessary to shift the 0 and &amp; it to 0x80 on line 19. It would be sufficient to merely write 0 to the SDI pin. However, it is necessary to use this method of writing to the SDI pin write any other number, e.g., 0x3F into the input shift register.</p><p>As with shiftRegClr() above, lines 25 and 27 toggle the RCLK pin to transfer the bits to the output register.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa9c01b6c62f887e6fb6d08996c92a21/href">https://medium.com/media/fa9c01b6c62f887e6fb6d08996c92a21/href</a></iframe><p>This next code snippet demonstrates how to light up all the LEDs, including the decimal point, as well as toggling the OE pin to temporarily disable the output register.</p><p>Lines 3 through 15 show writeAllOnes(). It’s implemented almost exactly like zeroClear() above. The one notable exception is that it doesn’t left-shift the 1 and &amp; it to 0x80 before writing it to the pin. This demonstrates that when all input shift register bits will have the same value, i.e., 1 or 0, it’s not necessary to do this. It does however repeat the process of writing to the pin 8 times, advancing the SRCLK clock after each write.</p><p>Lines 22 through 29 implement oeToggle(), which toggles the OE pin to HIGH (1) and then LOW again. There’s a 1 second delay between the writes to ensure that the effect is visible. Recall that setting to OE pin to HIGH is how the output register is disabled. From the observer’s perspective, the 7-segment display will turn off for 1 second and then be restored to whatever was being displayed prior to the toggling. It’s up to the calling function to decide what is displayed on the 7-segment display prior to calling this function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2b6dd85d54c4764c7a275b2fd450458/href">https://medium.com/media/b2b6dd85d54c4764c7a275b2fd450458/href</a></iframe><p>hc595_shift() is responsible for shifting the various bits of the input number, dat, into the input shift register. With the exception that the input number is variable based on what the value of dat is, the function is implemented exactly like zeroClr() above. In fact, both zeroClr() and writeAllOnes() can, and probably should have been, implemented using hc595_shift().</p><p>For those that might have trouble imagining how the &lt;&lt; works in conjunction with the &amp; operator, like I did, here’s a short example using 0x3f or 0011 1111 as an example. Note that the order of precedence of the operations is that &lt;&lt; happens first followed by the &amp;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*ZNL4Es7VT4-mLMrlbIxssw.png" /><figcaption>Bit shifting example — Image Credit: Author</figcaption></figure><p>The last entry, i = 8, is what would happen if dat was shifted 9 times instead of 8. This was included just to make it clear that dat has been shifted 8 bits to the left leaving all 8 bits set to 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fdce830265768d60a5ba09cfbc2fb03/href">https://medium.com/media/3fdce830265768d60a5ba09cfbc2fb03/href</a></iframe><p>Most of the functions in the above code snippet merely setup the test by setting the display to 8, and then delegate the behavior to the functions that we saw implemented above (e.g., shiftRegClr()). Instead of only displaying hexadecimal numbers 0-F, testWriteNums() will rotate through all the hexadecimal numbers and decimal point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ac4b03fc9477abc1a9a2c6a884edc95/href">https://medium.com/media/6ac4b03fc9477abc1a9a2c6a884edc95/href</a></iframe><p>Finally, this code snippet implements the main() and interruptHandler() functions.</p><p>Line 3 registers a signal handler, interruptHandler(), with interest in the SIGINT signal. SIGINT is what will be generated when ctl-C is entered at the terminal.</p><p>Lines 6 through 9 initialize the WiringPi library, exiting if the initialization fails.</p><p>Line 16 prompts the user for what behavior they’d like to see demonstrated.</p><p>Lines 17 through 25 first read the terminal input from the user and populate a null terminated string with the results. The code doesn’t care for any characters that might have been entered except the first character. Any additional characters between it and the newline will be ignored.</p><p>Line 26 frees the memory allocated by getline() on line 19. This is necessary to avoid memory leaks. Don’t worry if you don’t understand this. It’s not important to what’s being demonstrated in this program. If you’re interested, investigate memory allocation in C including how memory is allocated (malloc), how it’s freed (free), why this is important, and finally the operation of the getline() function. Otherwise just remember it’s required.</p><blockquote>ASIDE: strictly speaking it’s not actually required in this program as the resulting memory leak is likely to be trivial in normal use. At a minimum it’s bad form to not free all allocated memory when it’s no longer needed. At worst, the program can fail in various ways once all available memory has been allocated. So, call free when the memory associated with a variable like line is no longer needed.</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/C_dynamic_memory_allocation">Wikipedia</a> has a very detailed discussion about memory allocation and management.</blockquote><p>Lines 28 through 56 detect which option the user chose and call the function associated with that option. The entire process described from line 15 onwards is repeated until the user chooses the (q)uit option.</p><p>Lines 63 through 67 register the signal handler that will gracefully exit the program if ctl-C is entered at the terminal. It calls toggle8() which briefly displays an 8 before turning off all the LEDs in the 7-segment display.</p><h3>Shift Register/7-Segment Display in Go</h3><p>The Go program is very similar to the C version. There are some minor differences in the implementation and the runtime output. Some of these differences are due to structural differences between the languages as well as differences in coding conventions. The snippets below represent most, but not all of the program. I left out some of the boiler plate and whitespace.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f28c8f86532b78ba4e2548a029c9e798/href">https://medium.com/media/f28c8f86532b78ba4e2548a029c9e798/href</a></iframe><p>There are 4 major parts to this snippet. The first is the definition of the segcode variable on line 3. It serves the same purpose as SegCode in the C program, namely defining the values to be left-shifted into the shift register. One thing of note is that, as with the C version, these values are dependent on the use of Most Significant Bit shifting (MSB). For convenience, here’s the explanatory text from the C version:</p><blockquote>SegCode … contains the hexadecimal numbers that should be shifted into the shift register in order to display a number that matches the index of a particular number in the array. For example, to display an 8 SegCode[8] should be used. Note that these numbers reflect the use of the MSB form of shifting. The numbers would be different if the LSB shifting form were used. For example, the number to use to display 0, as shown on line 32, is 0x3F (0011 1111). To display 0 using the LSB method the hex number 0xFC(1111 1100) and the C right-shift operator, &gt;&gt;, should be used.</blockquote><p>Second, lines 7–13, in main(), initialize the go-rpio library, exiting if there’s a problem. Line 13 guarantees that the resources held by the go-rpio library will be released on program termination.</p><p>Third, lines 15–20, create the go-rpio rpio.Pin objects that are manipulated by the rest of the program.</p><p>Finally, lines 22–35, define a signal/interrupt handler to catch ctl-C inputs from the terminal. This is needed to gracefully exit the program if the user enters ctl-C at the keyboard. A key point to notice in this snippet is the use of the channel named stop. The signal/interrupt handler runs in its own goroutine (line 35). At this point, there are 2 goroutines running, the main() goroutine and the goroutine associated with the signal/interrupt handler. They are run and scheduled independently and as a result, control can shift from one goroutine to another in arbitrary and unpredictable ways. In order to gracefully shut down the program, they must both be stopped in a controlled manner. Otherwise exiting the program would result in unpredictable behavior. For example, at program exit, the 7-segment display might still have some illuminated LEDs. Synchronizing program exit using the stop channel prevents this from happening. See the Tour of Go lessons on <a href="https://tour.golang.org/concurrency/1">Goroutines</a> and <a href="https://tour.golang.org/concurrency/2">Channels</a> for a quick introduction to goroutines and channels. Don’t worry if you don’t quite understand all this, concurrency in Go is an advanced topic. Mostly I just wanted to provide a high-level explanation of why the code is written this way.</p><p>The program comments provide additional detail. The rest of main() is in the following snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f716b4d3d02be7fe81dcb301e7da6243/href">https://medium.com/media/f716b4d3d02be7fe81dcb301e7da6243/href</a></iframe><p>The rest of main() as shown above handles prompting the user about what capability they’d like to see demonstrated is fairly self-explanatory. One thing to point out though is the for/select loop starting in lines 2-8. for/select is a common pattern used in Go programs. Its use here goes back to the prior discussion about the stop channel. The select part of the for/select pattern is listening on the stop for the message indicating this goroutine should exit. Notice the select had 2 case choices. The first is for listening to the stop channel. If a message is received the for loop, and program, will exit. If no message is received then control will immediately pass to the default case, continuing with normal program flow. In the default case the user is prompted, in lines 18-57, for their choice which will result in one of the test functions being called.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f76de5f9b0bd386df74d43aa78bf9ecd/href">https://medium.com/media/f76de5f9b0bd386df74d43aa78bf9ecd/href</a></iframe><p>There are 3 parts to this next code snippet. The first is the creation of the go-rpio rpio.Pin objects that represent the logical connection to the shift register’s physical pins. The GPIO/BCM pins 17, 18, 27, 19, and 21 are used for the SDI, RCLK, SRCLK, SRCLR, and OE pins respectively.</p><p>The second part sets the pins to OUTPUT mode so that they can be written to.</p><p>The final part sets the voltage on the pins to their initial values. Note the SRCLR pin is set to HIGH. This is required in order for the shift register to work. In later code snippets, we’ll see that clearing the input shift register is accomplished by setting the SRCLR pin to LOW to clear the input shift register, and then back to HIGH to reenable the normal operation of the shift register.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfe828ceec8c66b15ebe9da419522892/href">https://medium.com/media/cfe828ceec8c66b15ebe9da419522892/href</a></iframe><p>This code snippet shows the implementation of the test functions that are called in response to users’ choices regarding what capability they’d like to see demonstrated. If any data has been written to the 7-segment display it will be cleared before the functions exit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71f35ab07a26d5e5956a5b7018541bba/href">https://medium.com/media/71f35ab07a26d5e5956a5b7018541bba/href</a></iframe><p>This code snippet shows the implementation of the function that’s the heart of the program, hc595_shift(), which does the actual writing to the input shift register. The comments provide a good detailed explanation of what the function does. See the C version above for more detail about how the bit shifting works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f02c7a1284029397816583697bd15da0/href">https://medium.com/media/f02c7a1284029397816583697bd15da0/href</a></iframe><p>This final code snippet shows the implementation of 2 helper functions and the signal/interrupt handler. The first helper function, writeNums(), writes the actual data needed to illuminate the hexadecimal numbers on the 7-segment display.</p><p>The second, shiftRegClr(), shows how to use the combination of the SRCLR and RCLK pins to clear the shift register ultimately clearing the 7-segment display. Note that, as described above, the SRCLR pin needs to be set back to HIGH in order to reenable the shift register.</p><p>In shiftRegClr, lines 12 through 18, note the use of the RCLK pin on lines 14and 16. The clock signal to that pin must be pulsed, i.e., set to HIGH followed by LOW, in order to make the input shift register contents available to the output register. Also note that the SRCLR pin needs to be reset to HIGH after the operation to reenable the shift register.</p><p>Finally, the signalHandler() function catches the signal from the OS (line 23) via the sigs channel. Then on (line 25) it closes the stop channel. A side effect of closing a channel is a notification is sent to all listeners on the other end of the channel. This is a common pattern in Go. Finally, it clears the shift register, releases go-rpio resources (line 28), and exits the program.</p><h3>Summary</h3><p>This article has covered quite a bit of ground. If you’ve been following my series starting with the <a href="https://youngkin.github.io/post/sunfoundergpionotesled/">Raspberry Pi GPIO in Go and C — Blinking LED</a> project, you’re already familiar with using GPIO to drive LEDs. You might agree that the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.4_7-segment_display_c.html">Sunfounder 7-Segment Display</a> project didn’t really add to your knowledge of GPIO and LEDs that hasn’t already been covered in previous projects. So this is why, for me anyway, this project is really about learning shift register fundamentals and using them in a non-trivial way.</p><p>This article covered several interesting things:</p><ol><li>It demonstrated wiring up a relatively complex circuit on a breadboard. As I did, you might have made some mistakes along the way that gave you some useful knowledge of how to debug circuits.</li><li>Through an academic discussion and hands-on practice you’ve learned quite a bit about shift registers and what they can be used for.</li><li>Despite my somewhat trivializing the use of LEDs in this project, this project did shed light on how to use LEDs in a more realistic manner. Controlling an individual LED is interesting, but being able to control an array of LEDs in parallel and display digits on that array is a big step forward. You also learned that there are 2 types of 7-segment displays, common anode and common cathode.</li></ol><p>Comments and questions about this article are welcome (so are ‘claps’ :) ).</p><h3>References</h3><ul><li>The <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.4_7-segment_display_c.html">Sunfounder 7-Segment Display</a> project documentation.</li><li>The <a href="https://docs.sunfounder.com/projects/electronic-kit/en/latest/lesson_19_7-segment.html">Sunfounder 7-Segment Python</a> project contains some additional information not available in the C version of the project.</li><li><a href="https://pinout.xyz/">Raspberry Pi GPIO Pinout diagram</a> including the physical board pin numbers, the BCM/GPIO pin numbers, and the WiringPi pin numbers.</li><li><a href="https://www.allaboutcircuits.com/textbook/digital/chpt-12/serial-in-parallel-out-shift-register/">Shift Registers: Serial-in, Parallel-out (SIPO) Conversion</a> is a good resource for getting a detailed introduction to shift registers in general, and the 74HC595 shift register in particular.</li><li><a href="https://www.ti.com/lit/ds/symlink/cd74hc595.pdf?ts=1636840974607&amp;ref_url=https%253A%252F%252Fwww.google.com%252F">Texas Instruments CD74HC595 Datasheet</a> contains some interesting information including a timing diagram.</li><li><a href="https://www.circuitbasics.com/arduino-7-segment-display-tutorial/">How to set up seven segment displays on the Arduino</a> provides an example of a 7-segment LED project that doesn’t use a shift register. It also has some other useful information such as how to determine whether a 7-segment display is a common cathode or common anode display.</li><li><a href="https://github.com/WiringPi/WiringPi">WiringPi</a> library for C</li><li><a href="http://wiringpi.com/">WiringPi website</a></li><li><a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> library for Go</li><li>Other articles in my <a href="https://youngkin.github.io/categories/gpio/">Raspberry Pi GPIO series</a></li><li><a href="https://github.com/youngkin/gpio">The gpio repository</a> containing the code for this article</li><li><a href="https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up">How to setup a new Raspberry Pi from scratch</a></li><li><a href="https://www.sciencebuddies.org/science-fair-projects/references/how-to-use-a-breadboard">How to use a breadboard</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa8ad85dec70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/raspberry-pi-gpio-in-go-and-c-using-a-shift-register-7-segment-display-aa8ad85dec70">Raspberry Pi GPIO in Go and C — Using a Shift Register &amp; 7 Segment Display</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raspberry Pi GPIO in Go and C — LED Bar Graph]]></title>
            <link>https://medium.com/better-programming/raspberry-pi-gpio-in-go-and-c-led-bar-graph-8194eff66d2e?source=rss-80d16197df23------2</link>
            <guid isPermaLink="false">https://medium.com/p/8194eff66d2e</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Richard Youngkin]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 13:38:12 GMT</pubDate>
            <atom:updated>2021-11-15T01:08:31.293Z</atom:updated>
            <content:encoded><![CDATA[<h3>Raspberry Pi GPIO in Go and C — LED Bar Graph</h3><h4>How to control an LED bar graph in Golang and C</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuVTRDap9tYxnZErMPbj_w.png" /><figcaption>Image Credit: Author</figcaption></figure><p>This is the third article in a series that explores GPIO programming on a Raspberry Pi 3B+. It is a supplement to the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.3_led_bar_graph_c.html">Sunfounder LED Bar Graph</a> project. You can find the full series <a href="https://youngkin.github.io/categories/gpio/">here</a>. The code for the series can be found in my <a href="https://github.com/youngkin/gpio">gpio repository</a>.</p><p>The <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.3_led_bar_graph_c.html">Sunfounder LED Bar Graph</a> project provides very good documentation regarding how to set up the project as well as describing the C code. This article is more geared towards describing what an LED bar graph is, what it’s good for, and how to control an LED bar graph using Go as well as C.</p><p>LED bar graphs consist of several LEDs embedded into a single component. In the picture to the right the bar graph contains 10 LEDs arranged side-by-side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oi5nHfjZZjV-cq-i.png" /><figcaption>LED Bar Graph component — Image Credit: Author</figcaption></figure><p>LED bar graphs have several uses including:</p><ul><li>Progress indicators</li><li>Battery charge</li><li>Voltmeter</li><li>Sound meter</li><li>Speed</li></ul><p>In short, just about anything that requires an indication of a value at a relative position on a scale can be represented by an LED bar graph.</p><h3>Prerequisites</h3><p>This section is repeated in all articles in my <a href="https://youngkin.github.io/categories/gpio/">Raspberry Pi GPIO series</a>. If you’ve already completed a project from one of these articles you can skim this section. With the exception of the inclusion of the required LED Bar Graph component, the rest of the section is identical.</p><p>If you don’t have one, you’ll need a Raspberry Pi. I used a Raspberry Pi 3B+ with the ‘Stretch’ version of the Raspbian OS. The Raspberry Pi website has instructions on how to <a href="https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up">setup a new Raspberry Pi from scratch</a> if you decide to go that way vs. buying a complete kit.</p><p>Other items you’ll need include:</p><ul><li>a <a href="https://www.amazon.com/dp/B082KBF7MM/ref=sspa_dk_detail_4?psc=1&amp;pd_rd_i=B082KBF7MM&amp;pd_rd_w=1tGTV&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=fX8JB&amp;pf_rd_r=44DE0RS1E9FD42RBYC7R&amp;pd_rd_r=47cbdc7f-7834-455f-9429-ef74a438bd45&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFVVkdZVUZRNUw3ODkmZW5jcnlwdGVkSWQ9QTA4MzI4MzYyU0VLNzBJM0cxRUVMJmVuY3J5cHRlZEFkSWQ9QTA0Mjk1NTMzSzNSWlNFUjU0NURBJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">breadboard</a> <em>(You may find </em><a href="http://wiki.sunfounder.cc/index.php?title=Breadboard_Basics_%E2%80%93_Types"><em>this tutorial on breadboards</em></a><em> helpful)</em>,</li><li>some <a href="https://www.amazon.com/dp/B08HZ26ZLF/ref=syn_sd_onsite_desktop_19?psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUExRFpLWElCRjg1MUNMJmVuY3J5cHRlZElkPUEwMjMyMTE1M01aOFE3U1BQS09YSiZlbmNyeXB0ZWRBZElkPUEwODE5NTMxMktEMTlZRjEyQjBJNiZ3aWRnZXROYW1lPXNkX29uc2l0ZV9kZXNrdG9wJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">jumper wires</a>,</li><li>10 <a href="https://www.amazon.com/Resistor-Tolerance-Resistors-Assortment-Certificated/dp/B08QR72BFW/ref=sr_1_8?crid=1E3LWKK431TDV&amp;keywords=resistor+assortment&amp;qid=1636936543&amp;qsid=143-6049131-7886617&amp;s=industrial&amp;sprefix=resistor%2Cindustrial%2C203&amp;sr=1-8&amp;sres=B085NQZNTY%2CB072BL2VX1%2CB07N1ZK8CC%2CB098BKR447%2CB08QR72BFW%2CB07L851T3V%2CB09CZ18Z31%2CB08PF3HNMD%2CB07D54XMFK%2CB088WQMNYK%2CB08NY3XR96%2CB06WRQS97C%2CB07PXYVP3J%2CB07D2Z45CG%2CB089Q88QPN%2CB08ZRYH9VC%2CB08FD1XVL6%2CB08QRH6HFT%2CB07PTNN78Z%2CB07P3MFG5D">220 Ohm resistors </a>— this set actually has an assortment of resistors including 220 Ohm resistors,</li><li>a <a href="https://www.amazon.com/10-Segment-LED-BAR-Graph-Indicator/dp/B0155SPLN2/ref=pd_sbs_3/143-6049131-7886617?pd_rd_w=1Ex07&amp;pf_rd_p=0a3ad226-8a77-4898-9a99-63ffeb1aef90&amp;pf_rd_r=PSA6XYZEJZTWWA8QVHG1&amp;pd_rd_r=63d233c3-3180-4b34-8452-eee71e2cc984&amp;pd_rd_wg=GSCIp&amp;pd_rd_i=B0155SPLN2&amp;psc=1">10 segment LED Bar Graph</a></li><li>You should also consider getting a <a href="https://www.amazon.com/dp/B082PRVRYR/ref=sspa_dk_detail_2?psc=1&amp;pd_rd_i=B082PRVRYR&amp;pd_rd_w=8mKhr&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=e9psa&amp;pf_rd_r=S09F37DF2G5FW8B8GX4B&amp;pd_rd_r=c065c120-e60b-45e9-b93b-f581f048cf46&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFCMzhUQ09COFI2VlMmZW5jcnlwdGVkSWQ9QTA5NjU2ODUxRDkxNEYwSTYwV09KJmVuY3J5cHRlZEFkSWQ9QTAxOTg1MTUyRUhEUlc2VzQ2VDQ4JndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">40 pin female to female with a T-Type adapter</a> to attach the GPIO outputs to the breadboard. You can use only jumper wires, but the T-Type adapter will make things easier and will help prevent damage to the GPIO pins on the Raspberry Pi. If you elect not to buy the 40 pin cable with T-Type adapter you’ll need to buy <a href="https://www.amazon.com/SinLoon-Breadboard-Arduino-Circuit-40-Pack/dp/B08M3QLL3Q/ref=pd_sbs_7/143-0445142-7950409?pd_rd_w=sVLrc&amp;pf_rd_p=8b76d7a7-ab83-4ddc-a92d-e3e33bfdbf03&amp;pf_rd_r=CDM5TGJT03VKF0ZFB577&amp;pd_rd_r=8e58fd82-8503-41cf-b8f2-c78eaeb78d25&amp;pd_rd_wg=tT1U0&amp;pd_rd_i=B08M3QLL3Q&amp;psc=1">male-to-female jumper wires</a>. Buying all these things separately will cost more than a kit however.</li></ul><p><a href="https://www.amazon.com/dp/B06WP7169Y/ref=sspa_dk_detail_5?psc=1&amp;pd_rd_i=B06WP7169Y&amp;pd_rd_w=OZVyf&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=0V0IH&amp;pf_rd_r=623YJTBQ2CN2B2GYXQG5&amp;pd_rd_r=faa61f0f-3aec-4cf0-8e7e-d44eb1b3b92f&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyUVlDQzMzVVZBMFYxJmVuY3J5cHRlZElkPUEwMzExNzk4MUhGSjFSS0VKTlBROCZlbmNyeXB0ZWRBZElkPUEwMzYwNjg2UUdMRU44N0YzNzIwJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">Here’s a simple kit that has all of the above</a>. I’m finding the <a href="https://www.amazon.com/gp/product/B09BMVT4CB/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&amp;psc=1">Sunfounder Raspberry Pi Ultimate Starter Kit</a> especially useful. NOTE: The Ultimate Starter Kit and the Raphael Kit are the same product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iAFdk74nkXhXIq7z.png" /><figcaption>Image Credit: Author</figcaption></figure><p>You will also need some basic C and Go programming knowledge as well as familiarity with logging on to a Raspberry Pi terminal, or into the desktop GUI that comes with some OS versions. Depending on the approach you take, you may need to connect a keyboard and monitor to the Raspberry Pi. I simply SSH into the Pi. You’ll also need familiarity with how to use an editor like vim or nano.</p><p>To compile and run the C program you’ll need the <a href="https://github.com/WiringPi">WiringPi</a> library. It’s easy to get:</p><pre>sudo apt-get install wiringpi</pre><p>Then test the installation using:</p><pre>pi@pi-node1:~/go/src/github.com/youngkin/gpio/rgbled $ gpio -v<br>gpio version: 2.50<br>Copyright (c) 2012-2018 Gordon Henderson<br>This is free software with ABSOLUTELY NO WARRANTY.<br>For details type: gpio -warranty</pre><pre>Raspberry Pi Details:<br>  Type: Pi 3B+, Revision: 03, Memory: 1024MB, Maker: Sony<br>  * Device tree is enabled.<br>  *--&gt; Raspberry Pi 3 Model B Plus Rev 1.3<br>  * This Raspberry Pi supports user-level GPIO access.</pre><p>In the above you’ll notice gpio version: 2.50. If you’re using a Rasberry Pi 4, use the instructions given in the Sunfounder <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/check_the_wiringpi_c.html">Checking the WiringPi</a>.</p><p>WiringPi is unique in that it includes a command line tool, gpio, as shown above, that can be used to manage, control, and query the GPIO board. This can be very handy. See the <a href="http://wiringpi.com/the-gpio-utility/">gpio reference</a> for more information on what it can do and how to use it.</p><p>If you’re interested in Go development on a Raspberry Pi you’ll need to install the development environment onto the Raspberry Pi. <a href="https://www.jeremymorgan.com/tutorials/raspberry-pi/install-go-raspberry-pi/">Here’s a simple source</a> that explains how to accomplish this. This source is a little dated, but the only significant issue is with the version of Go to install. The source shows installing Go <strong>1.14.4.linux-arm64.tar.gz</strong> and <strong>1.14.4.linuxarmv6l.tar.gz</strong>. The current versions are <strong>1.17.1.linux-arm64.tar.gz</strong> and <strong>1.17.1.linuxarmv6l.tar.gz</strong>. For the Raspberry Pi 3B+ the correct choice will be <strong>1.17.1.linuxarmv6l.tar.gz</strong>. The other is intended for 64 bit systems like the Raspberry Pi 4 series. You can find current ARM versions of Go at the <a href="https://golang.org/dl/">Golang download site</a>.</p><p>For Go development you’ll also need the <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> library.</p><p>If you want to veer away from the cookbook style of the Sunfounder docs you’ll need some basic knowledge of Linux . For example, I won’t be explaining what <strong>root privileges</strong> are.</p><h3>Setup and Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZLr1jIHnb7Fn7D-N.png" /><figcaption><em>Sunfounder wiring diagram — Image Credit: </em><a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/_images/image61.png"><em>Sunfounder</em></a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iEvZWsXFpyPkDwrg.png" /><figcaption>Actual wiring — Image Credit: Author</figcaption></figure><p>The breadboard should be wired as illustrated in the above diagram. If you’re unfamiliar with breadboards and breadboard diagrams this <a href="https://www.sciencebuddies.org/science-fair-projects/references/how-to-use-a-breadboard">breadboard tutorial </a>should be helpful.</p><p>One thing to note about the wiring diagram is that the resistors are all attached to the breadboard’s positive power bus on one side and the positive terminals of the LED bar graph on the other (<em>Label Side</em>). This means the LED bar graph is always getting power. In order for power to flow through a component one of the component’s terminals must be receiving power and the other must either not be receiving power or be connected to a negative or ground terminal. As noted, the resistors are directly attached to the power bus. In this diagram the GPIO pins are connected to the bar graph’s negative terminals. GPIO pins are set to either <strong>HIGH</strong> or <strong>LOW</strong> when in output mode <em>(i.e., the pins are written to)</em>. <strong>HIGH</strong> means voltage is flowing to the pin, <strong>LOW</strong> means no voltage is flowing to the pin. Since completing a circuit requires one side of the circuit to have zero volts, and the bar graph is always receiving power via the power bus, the GPIO pins must be set to <strong>LOW</strong> voltage for current to flow and the LEDs to illuminate. In the code sections below, the LEDs are set to <strong>LOW</strong> when the LEDs should be illuminated.</p><h3>LED Bar Graph in C</h3><p>The code for this program can be found in the <a href="https://github.com/youngkin/gpio/blob/main/ledbargraph/ledbargraph.c">ledbargraph.c</a> file in the <a href="https://github.com/youngkin/gpio">github respository</a> accompanying this series. It substantially similar to the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.3_led_bar_graph_c.html">Sunfounder program</a>, but there are some important differences:</p><ul><li>This program includes an initialization function that turns all the LEDs on then off prior to continuing with the remainder of the program. This can be useful to verify that the LED bar graph is wired up correctly.</li><li>This program includes an interrupt handler that cleans up when the program is interrupted via entering ctl-C at the terminal. The Sunfounder code does not. This cleanup includes resetting the bar graph to its state prior to the program starting, e.g., turning all the LEDs off.</li><li>Finally, this program also includes a function that randomly lights individual LEDs.</li></ul><p>The major parts of the program are described in more detail below. The code is pretty well described in the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.3_led_bar_graph_c.html">Sunfounder article</a> so I won’t repeat what’s already covered there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3cedeb61b33d259f0145b90a364b9e7/href">https://medium.com/media/f3cedeb61b33d259f0145b90a364b9e7/href</a></iframe><p>Lines 8 &amp; 9 show how to build and run the program. Line 19 declares the interrupt handler that’s used to intercept ctl-C input from the terminal. The rest of this section shows the init() function I added. It iterates through the pins array and first sets all the pins to LOW which has the effect of lighting them up. They’re set to LOW because the positive terminals of the LED bar graph are connected to the positive power bus. The pins are connected to the negative terminals of the bar graph. To get current to flow the pin states must be set to 0 volts, or LOW. The bar graph stays lit for 500 microseconds, then the LEDs are turned off, then there’s another delay of 500 microseconds before the program continues. The delays provide enough time to see the entire bar graph light up then turn off before the program continues. This provides a visual indication that the bar graph is connected properly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcbf6324ac0ab3abe3383d43bd5e54cf/href">https://medium.com/media/dcbf6324ac0ab3abe3383d43bd5e54cf/href</a></iframe><p>This next section contains the functions that control the bar graph LEDs. The oddLedBarGraph(), evenLedBarGraph(), and allLedBarGraph() functions are taken directly from the Sunfounder code. I added the randomBarGraph() function on lines 1 - 12 just to make things more interesting. It uses the C standard library rand() function, line 5, to generate a random number that is adjusted on line 6 to be within the range of the pins array, offsets 0 through 9. That resulting number is used as the offset in the array to find the pin to be toggled (lines 7 and 9). There is a very brief delay between lighting the individual LEDs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e7368962c2da7c44e6a9888daea0b45/href">https://medium.com/media/3e7368962c2da7c44e6a9888daea0b45/href</a></iframe><p>This last section of code shows the main() function and the interrupt handler, interruptHandler(). With the exception of the addition of lines 3, 18, and 19, main() is identical to the Sunfounder code. Line 3 registers the interruptHandler() function to receive the SIGINT signal associated with entering ctl-C at the terminal.</p><p>Lines 26 through 34 define the interruptHandler() function. It’s parameter, sig, contains the integer value of the signal being passed to the function. In our case it doesn’t matter what signal is passed, it’ll exit the program in any case.</p><p>Lines 27 thorugh 30 iterate through the pins array making sure each pin is set to OUTPUT mode, i.e., it can be written to, and setting it’s value to HIGH. Recall from above that setting the pin to LOW will light the pin, setting it to HIGH will turn it off.</p><p>Finally, the program exits on line 33 with a “success”, 0, exit code.</p><h3>LED Bar Graph in Go</h3><p>The code for this program can be found in the <a href="https://github.com/youngkin/gpio/blob/main/ledbargraph/ledbargraph.go">ledbargraph.go</a> file in the <a href="https://github.com/youngkin/gpio">github respository</a> accompanying this series. This program in this section is very similar to its C counterpart above. There are some minor differences however. It doesn’t include functions to light the even and odd numbered LEDs. The major parts of the program are described in more detail below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21846ae7bc90bc2882feb1c13d74ed77/href">https://medium.com/media/21846ae7bc90bc2882feb1c13d74ed77/href</a></iframe><p>Line 6 provides the command to run the program. Lines 34 and 35, set up the slices that will contain the pin numbers and the associated go-rpio rpio.Pin instances. Line 33 shows the comparable WiringPi pin numbers as a cross-reference.</p><p>The <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/gpio_extension_board.html">Sunfounder GPIO Extension Board diagram</a> doesn’t show the GPIO pins associated with SDA1, SCL1, and SPICE0 pins. The <a href="https://pinout.xyz/">Raspberry Pi Pinout diagram</a> does. Using this reference we can see that SDA1 maps to GPIO pin 2, SCL1 maps to GPIO pin 3, and SPICE0 maps to GPIO pin 8.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7937bd09a8926db0fc8ded39cac93be4/href">https://medium.com/media/7937bd09a8926db0fc8ded39cac93be4/href</a></iframe><p>This next part of the program shows the init function. Lines 4 - 9 create rpio.Pin instances, define the pins as rpio.OUTPUT pins, and append them to the gpins slice defined in the first part of the program. Lines 10 - 13 set the pins to LOW state, lighting them up. Recall the discussion about the C program above that describes why the pins are set to LOW. Line 14 briefly pauses the program so the effect of lighting them up can be seen. Finally lines 15 - 17 turn the pins off by setting them to HIGH.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/450a2e0a8284859c8c80464f9ddbdf9a/href">https://medium.com/media/450a2e0a8284859c8c80464f9ddbdf9a/href</a></iframe><p>This part of the program contains the randBarGraph() and ledAll() functions. Line 3 seeds the Go random number generator which is used in line 9 to generate the pin number to be lit. Lines 5 - 15 and lines 22 - 30 contain Go select blocks which are used to make sure the 2 functions will exit if a ctl-C signal is received from the terminal. Specifically, line 6 and 23 receive the stop command via the stop channel and lines 7 &amp; 24 exit the functions. The rest of the code is self-explanatory, the LEDs are turned on and off.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8ede03edb6da8c951aa8b8304480e21/href">https://medium.com/media/a8ede03edb6da8c951aa8b8304480e21/href</a></iframe><p>This final part of the program contains the main() and the signalHandler() functions. Lines 11 &amp; 15 create unbuffered Go channels. The stop channel is used to signal other parts of the program that the program is exiting. This is needed because the signalHandler() is started in a separate goroutine on line 21. It must be able to stop the main goroutine before exiting the program. The stop channel is defined as taking an interface{} type. This means that the channel can contain any type. For this channel the type of the data sent isn’t important.</p><p>The sigs channel, defined on line 15, is used by the Go runtime to notify the signalHandler() that an interrupt signal has been received. signalHandler() is registered with the Go runtime on line 20. Line 21 starts the goroutine that will run signalHandler().</p><p>The rest of main() simply initializes the pins and runs the controlling functions.</p><p>LInes 28–42 contain the definition of signalHandler().</p><h3>Summary</h3><p>This brief article provided a quick overview of the LED bar graph component and its application in the real world. It also included some C code that wasn’t included in the original Sunfounder program. This additional code is used to show how to turn on the different LEDs in random fashion. Finally, an implementation of this same C program was provided in Go. This was meant to demonstrate the usage of how use the <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> library implements functionality similar to <a href="https://github.com/WiringPi/WiringPi">WiringPi</a>.</p><p>Hopefully, you’ve learned enough from this article to use LED bar graphs in your own applications.</p><h3>References</h3><ul><li><a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.3_led_bar_graph_c.html">Sunfounder LED Bar Graph</a> project</li><li><a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/gpio_extension_board.html">Sunfounder GPIO Extension Board diagram</a></li><li><a href="https://pinout.xyz/">Raspberry Pi Pinout diagram</a></li><li><a href="https://github.com/WiringPi/WiringPi">WiringPi</a> library for C</li><li><a href="http://wiringpi.com/">WiringPi website</a></li><li><a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> library for Go</li><li>Other articles in my <a href="https://youngkin.github.io/categories/gpio/">Raspberry Pi GPIO series</a></li><li><a href="https://github.com/youngkin/gpio">The gpio repository</a> containing the code for this article</li><li><a href="https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up">How to setup a new Raspberry Pi from scratch</a></li><li><a href="https://www.sciencebuddies.org/science-fair-projects/references/how-to-use-a-breadboard">How to use a breadboard</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8194eff66d2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/raspberry-pi-gpio-in-go-and-c-led-bar-graph-8194eff66d2e">Raspberry Pi GPIO in Go and C — LED Bar Graph</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raspberry Pi GPIO in Golang and C — RGB LED]]></title>
            <link>https://medium.com/better-programming/raspberry-pi-gpio-in-golang-and-c-rgb-led-cebdb9b456a9?source=rss-80d16197df23------2</link>
            <guid isPermaLink="false">https://medium.com/p/cebdb9b456a9</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gpio]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Richard Youngkin]]></dc:creator>
            <pubDate>Mon, 08 Nov 2021 16:15:25 GMT</pubDate>
            <atom:updated>2021-11-09T23:09:46.294Z</atom:updated>
            <content:encoded><![CDATA[<h3>Raspberry Pi GPIO in Golang and C — RGB LED</h3><h4>How to control an RGB LED using Golang and C</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iD62Gg_9RyyaJxJAXe1ONQ.png" /><figcaption>Image Credit: Author</figcaption></figure><h3>Contents</h3><ul><li>Overview</li><li>Prerequisites</li><li>Information that would have been helpful</li><li>RGB LED in C (Software PWM)</li><li>RGB LED in C (Hardware PWM)</li><li>RGB LED in Go (Hardware PWM)</li><li>Summary</li><li>References</li></ul><h3>Overview</h3><p>This is the second article in a series that explores GPIO programming on a Raspberry Pi 3B+. The first is <a href="https://youngkin.github.io/post/sunfoundergpionotesled/">Raspberry Pi GPIO in Go and C — Blinking LED</a>. It is a supplement to the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.2_rgb_led_c.html">Sunfounder RGB LED project</a>. You can find the full series <a href="https://youngkin.github.io/categories/gpio/">here</a>.</p><p>This article explores the use of Pulse Width Modulation (PWM) to drive an RGB LED as well as how to control an individual LED pin’s brightness. The code samples will be in Go and C.</p><h3>Prerequisites</h3><p>If you don’t have one, you’ll need a Raspberry Pi. I used a Raspberry Pi 3B+ with the ‘stretch’ version of the Raspbian OS. Given that the Sunfounder Ultimate Starter Kit is advertised to work with a Raspberry Pi 4, I would expect the 4 series to work as well. I’m less sure about other Raspberry Pi versions, especially versions with 26 vs. 40 GPIO pins.</p><p>Next you’ll need</p><ol><li>A <a href="https://www.amazon.com/dp/B082KBF7MM/ref=sspa_dk_detail_4?psc=1&amp;pd_rd_i=B082KBF7MM&amp;pd_rd_w=1tGTV&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=fX8JB&amp;pf_rd_r=44DE0RS1E9FD42RBYC7R&amp;pd_rd_r=47cbdc7f-7834-455f-9429-ef74a438bd45&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFVVkdZVUZRNUw3ODkmZW5jcnlwdGVkSWQ9QTA4MzI4MzYyU0VLNzBJM0cxRUVMJmVuY3J5cHRlZEFkSWQ9QTA0Mjk1NTMzSzNSWlNFUjU0NURBJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">breadboard</a></li><li>Some <a href="https://www.amazon.com/dp/B08HZ26ZLF/ref=syn_sd_onsite_desktop_19?psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUExRFpLWElCRjg1MUNMJmVuY3J5cHRlZElkPUEwMjMyMTE1M01aOFE3U1BQS09YSiZlbmNyeXB0ZWRBZElkPUEwODE5NTMxMktEMTlZRjEyQjBJNiZ3aWRnZXROYW1lPXNkX29uc2l0ZV9kZXNrdG9wJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">jumper wires</a></li><li>A <a href="https://www.amazon.com/EDGELEC-Tri-Color-Multicolor-Diffused-Resistors/dp/B077XGF3YR/ref=asc_df_B077XGF3YR/?tag=hyprod-20&amp;linkCode=df0&amp;hvadid=242051162351&amp;hvpos=&amp;hvnetw=g&amp;hvrand=11064062033670066895&amp;hvpone=&amp;hvptwo=&amp;hvqmt=&amp;hvdev=c&amp;hvdvcmdl=&amp;hvlocint=&amp;hvlocphy=9028749&amp;hvtargid=pla-430228081645&amp;psc=1">220 Ohm resistor, and a RGB LED</a>.</li></ol><p>You should also consider getting a <a href="https://www.amazon.com/dp/B082PRVRYR/ref=sspa_dk_detail_2?psc=1&amp;pd_rd_i=B082PRVRYR&amp;pd_rd_w=8mKhr&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=e9psa&amp;pf_rd_r=S09F37DF2G5FW8B8GX4B&amp;pd_rd_r=c065c120-e60b-45e9-b93b-f581f048cf46&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFCMzhUQ09COFI2VlMmZW5jcnlwdGVkSWQ9QTA5NjU2ODUxRDkxNEYwSTYwV09KJmVuY3J5cHRlZEFkSWQ9QTAxOTg1MTUyRUhEUlc2VzQ2VDQ4JndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">40 pin female to female with a T-Type adapter</a> to attach the GPIO outputs to the breadboard. You can use only jumper wires, but the cable will make things easier and will help prevent damage to the GPIO pins on the Raspberry Pi. If you elect not to buy the 40 pin cable with T-Type adapter you’ll need to buy <a href="https://www.amazon.com/SinLoon-Breadboard-Arduino-Circuit-40-Pack/dp/B08M3QLL3Q/ref=pd_sbs_7/143-0445142-7950409?pd_rd_w=sVLrc&amp;pf_rd_p=8b76d7a7-ab83-4ddc-a92d-e3e33bfdbf03&amp;pf_rd_r=CDM5TGJT03VKF0ZFB577&amp;pd_rd_r=8e58fd82-8503-41cf-b8f2-c78eaeb78d25&amp;pd_rd_wg=tT1U0&amp;pd_rd_i=B08M3QLL3Q&amp;psc=1">male-to-female jumper wires</a>. Buying all these things separately will cost more than a kit however. <a href="https://www.amazon.com/dp/B06WP7169Y/ref=sspa_dk_detail_5?psc=1&amp;pd_rd_i=B06WP7169Y&amp;pd_rd_w=OZVyf&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=0V0IH&amp;pf_rd_r=623YJTBQ2CN2B2GYXQG5&amp;pd_rd_r=faa61f0f-3aec-4cf0-8e7e-d44eb1b3b92f&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyUVlDQzMzVVZBMFYxJmVuY3J5cHRlZElkPUEwMzExNzk4MUhGSjFSS0VKTlBROCZlbmNyeXB0ZWRBZElkPUEwMzYwNjg2UUdMRU44N0YzNzIwJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">Here’s a simple kit that has all of the above</a>. If you expect to follow this series I recommend buying the <a href="https://www.amazon.com/gp/product/B09BMVT4CB/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&amp;psc=1">Sunfounder Raspberry Pi Ultimate Starter Kit</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYIgjshQqjJNq5P_xNJ8ow.png" /><figcaption><em>Sunfounder Ultimate Starter/Raphael kit — </em>Image Credit: Author</figcaption></figure><p>You will also need some basic C and Go programming knowledge as well as familiarity with logging on to a Raspberry Pi terminal, or into the desktop GUI that comes with some OS versions. Depending on the approach you take, you may need to connect a keyboard and monitor to the Raspberry Pi. I simply SSH into the Pi. You’ll also need familiarity with how to use an editor like Vi or nano.</p><p>To compile and run the C program you’ll need the <a href="https://github.com/WiringPi/WiringPi">WiringPi</a> libary. It’s easy to get:</p><pre>sudo apt-get install wiringpi</pre><p>Then test the installation using:</p><pre>pi@pi-node1:~/go/src/github.com/youngkin/gpio/rgbled $ gpio -v<br>gpio version: 2.50<br>Copyright (c) 2012-2018 Gordon Henderson<br>This is free software with ABSOLUTELY NO WARRANTY.<br>For details type: gpio -warranty</pre><pre>Raspberry Pi Details:<br>  Type: Pi 3B+, Revision: 03, Memory: 1024MB, Maker: Sony<br>  * Device tree is enabled.<br>  *--&gt; Raspberry Pi 3 Model B Plus Rev 1.3<br>  * This Raspberry Pi supports user-level GPIO access.</pre><p>In the above you’ll notice gpio version: 2.50. If you’re using a Rasberry Pi 4, use the instructions given in the Sunfounder <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/check_the_wiringpi_c.html">Checking the WiringPi</a>.</p><p>WiringPi is unique in that it includes a command line tool, gpio, as shown above, that can be used to manage, control, and query the GPIO board. This can be very handy. See the <a href="http://wiringpi.com/the-gpio-utility/">gpio reference</a> for more information on what it can do and how to use it.</p><p>I chose not to download the code from the Sunfounder site, preferring to write my own instead, even if all I did was copy directly from the project documentation. Due to this I created my own location to create the code. In fact, <a href="https://github.com/youngkin/gpio">my code is in Github</a>. If you do like downloading code you have the option of downloading, cloning, or forking it from my Github repository. As an added bonus, the project code written in Go is also located there. The code for this project is located at <a href="https://github.com/youngkin/gpio/tree/main/rgbled">gpio/rgbled</a>.</p><p>If you’re interested in Go development on a Raspberry Pi you’ll need to install the development environment onto the Raspberry Pi. <a href="https://www.jeremymorgan.com/tutorials/raspberry-pi/install-go-raspberry-pi/">Here’s a simple source</a> that explains how to accomplish this. This source is a little dated, but the only significant issue is with the version of Go to install. The source shows installing Go <strong>1.14.4.linux-arm64.tar.gz</strong> and <strong>1.14.4.linuxarmv6l.tar.gz</strong>. The current versions are <strong>1.17.1.linux-arm64.tar.gz</strong> and <strong>1.17.1.linuxarmv6l.tar.gz</strong>. For the Raspberry Pi 3B+ the correct choice will be <strong>1.17.1.linuxarmv6l.tar.gz</strong>. The other is intended for 64 bit systems like the Raspberry Pi 4 series.</p><p>For Go development you’ll also need the <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> library. I chose it for several reasons:</p><ol><li>It seems to be in fairly wide use</li><li>It seems to be fairly complete</li><li>It’s relatively active</li><li>It comes with example code and good documentation</li><li>Its API is similar to WiringPi’s</li></ol><p>Another Go option is <a href="https://github.com/periph/host">periph</a> (code) with <a href="https://periph.io/">documentation</a>. It is more active and the documentation is very good, better than go-rpio. But for the LED examples I was able to find, go-rpio better matched what I was looking for, especially with regard to this project. But this is an excellent alternative to go-rpio and vice-versa.</p><p>Finally, I’m assuming a basic knowledge of Linux if you want to veer away from the cookbook style of the Sunfounder docs. For example, I won’t be explaining what <strong>root privileges</strong> are.</p><h3>Information that would have been helpful</h3><p>This project uses PWM (Pulse Width Modulation) on GPIO pins to achieve the desired effect, namely demonstrating how to create different colors with a simple RGB LED. Unfortunately the Sunfounder documentation leaves out information about PWM, like what is PWM and how is it implemented on a Raspberry Pi? I started to include in this section all the information I found missing from the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.2_rgb_led_c.html">Sunfounder project documentation</a>, but it quickly became apparent that would better be left to a separate article. So if you don’t already have a good understanding of PWM I’d recommend reading my <a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/">Pulse Width Modulation for Dummies, with a Slice of Raspberry Pi</a> article before continuing with this article. I will be using terminology explained in that article throughout this one.</p><h3>RGB LED in C (Software PWM)</h3><p>Depending on your experience, you should consider reviewing the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.2_rgb_led_c.html">RGB LED</a> project starting with <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/component_list.html">Components List and Introduction</a>. Peruse it up through the <em>Play with C </em>section. If you’re experienced with basic electronics and components like breadboards and resistors you can skip it.</p><p>You should set up the breadboard as described in the project documentation or in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xiUJfxPaCtzpYHWJj_Z__w.png" /><figcaption><em>Sunfounder RGB LED breadboard setup — </em>Image Credit: <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/_images/image61.png">Sunfounder</a></figcaption></figure><p>The WiringPi gpio utility can help with debugging if necessary. You already have this utility, you used it to verify the WiringPi installation in the Prerequisites section above.</p><p>The C code described in the Sunfounder <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.2_rgb_led_c.html">RGB LED project</a> uses software PWM. When run, the colors of the RGB LED change as expected. Varying voltages to the respective RGB pins using software PWM produces light of varying brightness (off to full bright) which will produce a wide range of colors.</p><p>Here is a slightly modified version of the Sunfounder C program that the controls an RGB LED:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c281b624784f618aee5728fb536d069/href">https://medium.com/media/2c281b624784f618aee5728fb536d069/href</a></iframe><p>Line 8 provides the command needed to build the program — gcc -o rgbled rgbled.c -lwiringPi -lpthread. The -l flags reference the libraries needed to build the program. -lwiringPi refers to the WiringPi library. It should be installed in the correct place along with WiringPi and the build command should just work. Libraries are usually located in /usr/lib. Line 9 provides the command to run the program.</p><p>Lines 18–20 specify, using the WiringPi pin numbering scheme, the GPIO pins 0, 1, and 2 for LedPinRed, LedPinGreen, and LedPinBlue respectively.</p><p>Line 24 contains the declaration of a signal handler for interrupt signals (SIGINT).</p><p>Lines 27–29 use the softPwmCreate() function to initialize the pins. The initial characters in the function name, softPwm, indicate that the pins are being initialized for software PWM. The function’s first parameter is the pin number. The second parameter is the starting pulse width. The final parameter is the range. See <a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/">Pulse Width Modulation for Dummies, with a Slice of Raspberry Pi</a> if you don’t understand these terms.</p><p>Lines 33–35, softPwmWrite() send the desired signal/voltage to the associated pin. The first parameter is the pin number, the same as in softPwmCreate() above. The second parameter is the pulse width. Notice that the pulse width was 0 in softPwmCreate(). This has the effect of setting the pin to zero volts. In softPwmWrite() the pulse width is set to the values specified by r_val, g_val, and b_val. These values represent the red, green, and blue values respectively. The maximum effective value for the pulse width is the range. This will result in full brightness/voltage. Any values greater than range will have no additional impact. It is important to note that the desired voltage will continue to flow to the pins until reset by another softPwmWrite().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87c93813af5ac9e8533ec085ae36b30a/href">https://medium.com/media/87c93813af5ac9e8533ec085ae36b30a/href</a></iframe><p>The code snippet above is a continuation of the program. It shows the main() function. Lines 2–5 initialize the WiringPi library. The program exits if this initialization fails.</p><p>Line 7 specifies a signal handler to be called when SIGINT signal is received by the program. This is the signal set when the user enters ctl-C at the keyboard. This signal handler will terminate the program. This function was declared in the previous code snippet.</p><p>The calls to ledColorSet(...) within the while(keepRunning) loop at line 11 use hex numbers to set the colors. These are used to generate the full range of available colors. They must fall in the range of 0 to 0xff, recall the range value was specified in softPwmCreate(). I did change the values from the original Sunfounder code as the green LED used apparently has less resistance as it’s quite a bit brighter than the red and blue LEDs and therefore throws off the generated colors. Similarly, the blue LED seems to have more resistance as it is quite a bit dimmer than the other 2 LEDs. Changing the values, at least for my specific RGB LED, generated truer colors. The code loops, changing the LED color, until terminated via a ctl-C at the keyboard.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46b9a83f818ed83551c01d352c4e11cb/href">https://medium.com/media/46b9a83f818ed83551c01d352c4e11cb/href</a></iframe><p>The code snippet above is a continuation of the previous code snippet. It contains the implementation of the interrupt handler described previously. It turns off all the RGB LED’s pins, resulting in the LED being completely off. pinMode() sets the mode for the specified pin (first parameter) to OUTPUT (second parameter). This changes the pin from a PWM pin to a pin that can only be set to ON or OFF. The voltage of an output pin cannot be varied. digitalWrite() sets the voltage for the specified pin to zero (LOW).</p><p>The program can be run, after compiling, using ./rgbled.</p><h3>RGB LED in C (Hardware PWM)</h3><p>Since the Sunfounder documentation doesn’t include a hardware PWM solution in C I decided to create one for myself. For this program modify the breadboard as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*220SjKgRg3BttSTpGwDyHw.jpeg" /><figcaption><em>Modified Sunfounder RGB LED breadboard setup — </em>Image Credit: <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/_images/image61.png">Sunfounder</a> &amp; Author</figcaption></figure><p>This time I’m using WiringPi pins 24, 1, and 23 for red, green, and blue, which correspond to BCM pins 19, 18, and 13 respectively. This is because these are 3 of the 4 hardware PWM pins on the Broadcomm BCM2835 board. Be sure to rewire the board to match these new pin assignments . The WiringPi gpio utility can help with debugging if necessary. You already have this utility, you used it to verify the WiringPi installation in the Prerequisites section above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/487ec7643f6cd839d126c193159b32cf/href">https://medium.com/media/487ec7643f6cd839d126c193159b32cf/href</a></iframe><p>This version of RGB LED is very similar to the software PWM version above. There are 2 significant differences.</p><ol><li>Note the pin numbering used in lines 14–16. The WiringPi pin numbers used here correspond to the hardware PWM pins available on the GPIO board.</li><li>The ledInit() and ledColorSet() functions (lines 30-48) are quite different. In these functions pin mode is set to PWM_OUTPUT vs. the use of softPwmCreate(), and pwmWrite() is used instead of softPwmWrite(). Line 34 sets the range. Note that the pin number isn’t specified for the pwmSetRange() call. There are 2 reasons for this. The first is that range is set at the channel level, not for individual pins. The second is that the WiringPi library doesn’t allow for the 2 channels to be specified separately. It sets both channels to the same value. Line 35, pwmSetClock(), (indirectly) sets the frequency. It specifies a <em>divisor</em>, in this case 2, that is used to divide the board’s oscillator’s clock frequency into the frequency used to control the pins. The <em>divisor</em> must be a number between 2 and 4095. As with pwmSetRange(), pwmSetClock() is specified at the channel level, not for individual pins. See <a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/">Pulse Width Modulation for Dummies, with a Slice of Raspberry Pi</a> for more discussion about clocks, frequency, and <em>divisor</em> as they relate to PWM.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd9b6f7cca8158b4401ca94bbabed22c/href">https://medium.com/media/cd9b6f7cca8158b4401ca94bbabed22c/href</a></iframe><p>The code snippet above contains the remainder of the program, main() and the interrupt handler. The interrupt handler is exactly the same as the interrupt handler in the software PWM version. Like the software PWM version of the program, the program loops until interrupted via a ctl-C.</p><p>The program is run using root privileges with sudo ./rgbledHardware. sudo is needed because direct hardware access is limited to users with root privileges. sudo provides root privileges to commands prefixed with sudo.</p><p>When running the program you’ll notice that the RGB LED doesn’t produce the expected colors. Sometimes it might show purple when it should be showing blue. Sometimes it might be turned off completely when it’s supposed to be showing a color. This behavior occurs because BCM pin 13 (blue) and BCM pin 19 (red) are on the same hardware channel. As explained above, when a signal is sent to one channel it will propagate to both pins that share that channel. Green, on BCM pin 12, is unaffected. One behavior I don’t understand is why sometimes the LED is off when it should be showing a color. This only happens for red (BCM19) and blue (BCM 13) pins. Perhaps the pins that share a channel don’t produce a signal at exactly the same time. Imagine a case where the blue pin is set to 0xff and the red pin is set to 0x00. If the red pin’s signal comes in slightly after the blue signal it would override the blue pin signal turning the LED off. The takeaway from all this is that for all intents and purposes, there are only 2 hardware PWM pins can be in use at the same time, and they can’t be on the same channel.</p><h3>RGB LED in Go (Hardware PWM)</h3><p>This version of RGB LED will work with the same breadboard setup as the C hardware PWM version. That is, it uses the hardware PWM pins on the GPIO board. Unlike the Sunfounder C version, and the first C version in this article, the Go library only supports hardware PWM. In my <a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/">Pulse Width Modulation for Dummies, with a Slice of Raspberry Pi</a> article I do include a software version of PWM in Go. It’s implemented in a companion program, <a href="https://github.com/youngkin/gpio/blob/main/pwmdemo/pwmexplorer/apps/freqtest.go">freqtest.go</a> in the runSoftwarePWM() function. Here is the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0827d0a45ba9da1f25b3b8c4956afc0/href">https://medium.com/media/e0827d0a45ba9da1f25b3b8c4956afc0/href</a></iframe><p>Lines 27–29 define the pins to use for the red, green and blue elements of the LED.</p><p>Lines 30–31 define default values to use for settings.</p><p>Lines 35–75 set the Mode to PWM and theDutyCycle for the LED’s pins. In DutyCycle(), the first parameter is the pulse width, called <em>duty</em> by go-rpio. The second parameter is the range, called <em>cycle</em> by go-rpio. The remainder of the lines contain comments and code that address the issues with trying to use 2 hardware PWM pins residing on the same channel as noted in the <em>Hardware PWM in C </em>section above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cb47139c29bb206031f8d63b2636e73/href">https://medium.com/media/0cb47139c29bb206031f8d63b2636e73/href</a></iframe><p>This code snippet is a continuation of the program above. This gist shows ledInit(). It initializes the GPIO pins for use in the program. They set the mode (PWM), frequency, and duty cycle (providing parameters for pulse width (aka duty) and range (aka cycle)). As described in <a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/">Pulse Width Modulation for Dummies, with a Slice of Raspberry Pi</a>, the specified frequency must be between 4688 and 9,600,000.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3f88e2ba6f03d22c20c79275d46a41d/href">https://medium.com/media/c3f88e2ba6f03d22c20c79275d46a41d/href</a></iframe><p>This is part 3 of the program and shows the implementation of main(). Lines 2-4 initialize the go-rpio library. Line 5 makes sure the resources used are released when the program exits.</p><p>The remainder of the program prompts the user for the red, green, and blue values to use and the sets the pins approporiately.</p><p>The full program, <a href="https://github.com/youngkin/gpio/blob/main/rgbled/rgbled.go">rgbled.go</a>, can be found in the <a href="https://github.com/youngkin/gpio">gpio github repo</a>.</p><h3>Summary</h3><p>That’s it, I hope you found this article interesting. To quickly review, this article covered the following:</p><ol><li>Setting up the physical environment needed to experiment with an RGB LED on a Raspberry Pi 3B+.</li><li>Provided, via a link to<a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/">Pulse Width Modulation for Dummies, with a Slice of Raspberry Pi</a>, the detailed knowledge of PWM that’s missing from the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.2_rgb_led_c.html">Sunfounder RGB LED Project</a>.</li><li>Provided and explained the C and Go code needed to set colors in an RGB LED using both hardware and software PWM.</li></ol><h3>References</h3><ol><li><a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.2_rgb_led_c.html">Sunfounder RGB LED Project</a> was the basis for this article</li><li><a href="https://github.com/WiringPi/WiringPi">WiringPi</a> — The C library used in this article for GPIO programming</li><li><a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> — The Go library used in this article for GPIO programming</li><li><a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/">Pulse Width Modulation for Dummies, with a Slice of Raspberry Pi</a> contains all you need to know about PWM on a Raspberry Pi, at least until you want to become a PWM expert!</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cebdb9b456a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/raspberry-pi-gpio-in-golang-and-c-rgb-led-cebdb9b456a9">Raspberry Pi GPIO in Golang and C — RGB LED</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raspberry Pi Pulse Width Modulation for Dummies]]></title>
            <link>https://medium.com/better-programming/raspberry-pi-pulse-width-modulation-for-dummies-10005f3f3583?source=rss-80d16197df23------2</link>
            <guid isPermaLink="false">https://medium.com/p/10005f3f3583</guid>
            <category><![CDATA[gpio]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Richard Youngkin]]></dc:creator>
            <pubDate>Wed, 03 Nov 2021 15:59:01 GMT</pubDate>
            <atom:updated>2021-11-03T15:59:01.160Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Pulse Width Modulation on a Raspberry Pi using C and Golang</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKPxuDXF4bUKLWN9cq519g.png" /><figcaption>Image Credit: Author</figcaption></figure><p>This article provides some details about hardware and software based PWM on the Raspberry Pi, specifically the 3B+ with the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">Broadcomm BCM2835 board</a>. This article has an accompanying application, <a href="https://github.com/youngkin/gpio">PWM Explorer</a>, that can be used to experiment with PWM settings and capabilities.</p><h3>Overview</h3><p>I was writing an <a href="https://youngkin.github.io/post/sunfoundergpionotesrgbled">article</a> as a companion to the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.1_blinking_led_c.html">SunFounder RGB LED project</a> to cover some areas that were missing in that project such as what is PWM, how does it work, and why the code was written as it was. I had no idea what PWM was or what I was doing or why. To fill the gap I started researching PWM and found numerous articles about PWM (references 2, 3, 4, and also software libraries like <a href="https://github.com/WiringPi/WiringPi">WiringPi</a> (C), <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a>(Go), <a href="https://www.airspayce.com/mikem/bcm2835">BCM2835 by Mike McCalley</a> (C)and <a href="https://abyz.me.uk/rpi/pigpio/pdif2.html">pigpio</a> (Python &amp; C). So with my focus still on controlling an RGB LED via GPIO and PWM I started writing programs in C and Go. I quickly had difficulty in several areas:</p><ol><li>Terminology is used inconsistently across articles and the libraries. For example, some used the terms <em>Cycle</em> and <em>Range</em> for the same thing.</li><li>The libraries were documented to varying degrees. Coupled with a lack of common terminology it was difficult to figure out how to use them.</li><li>Going hand in hand with figuring out how to use the libraries, it was difficult to understand how different parameters affected the behavior of the hardware, in this case an RGB LED.</li></ol><p>My intent in writing this is to:</p><ol><li>Provide an overview of PWM and its main concepts.</li><li>Provide a glossary that links the various PWM terms to a consistent definition.</li><li>Explain how the various PWM settings interact with each other (not just <em>duty cycle</em>).</li><li>Provide the information needed (sometimes via external references) to install a GPIO test bed on a Raspberry Pi 3B+.</li><li>Provide programs, written in Go and C, that demonstrate how to effectively use <a href="https://github.com/WiringPi/WiringPi">WiringPi</a> and <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a>.</li><li>Provide an application that can be used to experiment with the various PWM parameters in real time.</li><li>Provide hard to find information on some of the concepts and PWM settings (e.g., minimum/maximum PWM frequencies).</li></ol><p>Lest anyone think I’m presenting myself as an expert in GPIO and PWM, I’m not. Despite my best attempts to summarize what I’ve learned, I’m sure I’ve made mistakes or made things more confusing. Any mistakes I’ve made are my own. If anyone comes across any mistakes topics that could be clarified, I’d appreciate comments so I can modify this article.</p><p>I’m not writing this to be a definitive source about all things PWM. There are better resources for that. See the <strong>References</strong> section below for resources that I found particularly helpful.</p><p>Now to the outline of this article. The sections are as follows:</p><ol><li><strong>Prerequisites</strong> covers areas like how to get the software libraries used in this article as well as things like the hardware needed by the <em>PWM Explorer</em> application to illustrate behavior.</li><li><strong>What is PWM?</strong> provides a very basic introduction to PWM. It provides definitions of common terms and the aliases used in the articles and software libraries.</li><li><strong>Overview of PWM on a Raspberry Pi 3B+</strong> provides an overview of how GPIO and PWM are implemented on a Raspberry Pi.</li><li><strong>Exploring PWM on a Raspberry Pi </strong>provides a description of the various PWM settings, how they interact with each other, some hard to find tidbits about the PWM settings, and an overview of the application, <em>PWM Explorer</em>, that can be used to drive PWM on a Raspberry Pi to see how the settings interact with each other in real time.</li><li>A <strong>Summary</strong> to wrap things up.</li><li>And a set of useful <strong>References</strong>.</li></ol><h3>Prerequisites</h3><p>If you don’t have one, you’ll need a Raspberry Pi. I used a Raspberry Pi 3B+ with the ‘Stretch’ version of the Raspbian OS. The Raspberry Pi website has instructions on how to <a href="https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up">setup a new Raspberry Pi from scratch</a> if you decide to go that way vs. buying a complete kit.</p><p>Other items you’ll need include:</p><ul><li>a <a href="https://www.amazon.com/dp/B082KBF7MM/ref=sspa_dk_detail_4?psc=1&amp;pd_rd_i=B082KBF7MM&amp;pd_rd_w=1tGTV&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=fX8JB&amp;pf_rd_r=44DE0RS1E9FD42RBYC7R&amp;pd_rd_r=47cbdc7f-7834-455f-9429-ef74a438bd45&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFVVkdZVUZRNUw3ODkmZW5jcnlwdGVkSWQ9QTA4MzI4MzYyU0VLNzBJM0cxRUVMJmVuY3J5cHRlZEFkSWQ9QTA0Mjk1NTMzSzNSWlNFUjU0NURBJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">breadboard</a> <em>(You may find </em><a href="http://wiki.sunfounder.cc/index.php?title=Breadboard_Basics_%E2%80%93_Types"><em>this tutorial on breadboards</em></a><em> helpful)</em>,</li><li>some <a href="https://www.amazon.com/dp/B08HZ26ZLF/ref=syn_sd_onsite_desktop_19?psc=1&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUExRFpLWElCRjg1MUNMJmVuY3J5cHRlZElkPUEwMjMyMTE1M01aOFE3U1BQS09YSiZlbmNyeXB0ZWRBZElkPUEwODE5NTMxMktEMTlZRjEyQjBJNiZ3aWRnZXROYW1lPXNkX29uc2l0ZV9kZXNrdG9wJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">jumper wires</a>,</li><li><a href="https://www.amazon.com/EDGELEC-Tri-Color-Multicolor-Diffused-Resistors/dp/B077XGF3YR/ref=asc_df_B077XGF3YR/?tag=hyprod-20&amp;linkCode=df0&amp;hvadid=242051162351&amp;hvpos=&amp;hvnetw=g&amp;hvrand=11064062033670066895&amp;hvpone=&amp;hvptwo=&amp;hvqmt=&amp;hvdev=c&amp;hvdvcmdl=&amp;hvlocint=&amp;hvlocphy=9028749&amp;hvtargid=pla-430228081645&amp;psc=1">a 220 Ohm resistor, and a RGB LED</a>.</li><li>You should also consider getting a <a href="https://www.amazon.com/dp/B082PRVRYR/ref=sspa_dk_detail_2?psc=1&amp;pd_rd_i=B082PRVRYR&amp;pd_rd_w=8mKhr&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=e9psa&amp;pf_rd_r=S09F37DF2G5FW8B8GX4B&amp;pd_rd_r=c065c120-e60b-45e9-b93b-f581f048cf46&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFCMzhUQ09COFI2VlMmZW5jcnlwdGVkSWQ9QTA5NjU2ODUxRDkxNEYwSTYwV09KJmVuY3J5cHRlZEFkSWQ9QTAxOTg1MTUyRUhEUlc2VzQ2VDQ4JndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">40 pin female to female with a T-Type adapter</a> to attach the GPIO outputs to the breadboard. You can use only jumper wires, but the T-Type adapter will make things easier and will help prevent damage to the GPIO pins on the Raspberry Pi. If you elect not to buy the 40 pin cable with T-Type adapter you’ll need to buy <a href="https://www.amazon.com/SinLoon-Breadboard-Arduino-Circuit-40-Pack/dp/B08M3QLL3Q/ref=pd_sbs_7/143-0445142-7950409?pd_rd_w=sVLrc&amp;pf_rd_p=8b76d7a7-ab83-4ddc-a92d-e3e33bfdbf03&amp;pf_rd_r=CDM5TGJT03VKF0ZFB577&amp;pd_rd_r=8e58fd82-8503-41cf-b8f2-c78eaeb78d25&amp;pd_rd_wg=tT1U0&amp;pd_rd_i=B08M3QLL3Q&amp;psc=1">male-to-female jumper wires</a>. Buying all these things separately will cost more than a kit however.</li></ul><p><a href="https://www.amazon.com/dp/B06WP7169Y/ref=sspa_dk_detail_5?psc=1&amp;pd_rd_i=B06WP7169Y&amp;pd_rd_w=OZVyf&amp;pf_rd_p=887084a2-5c34-4113-a4f8-b7947847c308&amp;pd_rd_wg=0V0IH&amp;pf_rd_r=623YJTBQ2CN2B2GYXQG5&amp;pd_rd_r=faa61f0f-3aec-4cf0-8e7e-d44eb1b3b92f&amp;spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyUVlDQzMzVVZBMFYxJmVuY3J5cHRlZElkPUEwMzExNzk4MUhGSjFSS0VKTlBROCZlbmNyeXB0ZWRBZElkPUEwMzYwNjg2UUdMRU44N0YzNzIwJndpZGdldE5hbWU9c3BfZGV0YWlsJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==">Here’s a simple kit that has all of the above</a>. I’m finding the <a href="https://www.amazon.com/gp/product/B09BMVT4CB/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&amp;psc=1">Sunfounder Raspberry Pi Ultimate Starter Kit</a> especially useful. <em>NOTE: The Ultimate Starter Kit and the Raphael Kit are the same product.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hQNO9rrJDq2150_y.png" /><figcaption>Image Credit: Author</figcaption></figure><p>You will also need some basic C and Go programming knowledge as well as familiarity with logging on to a Raspberry Pi terminal, or into the desktop GUI that comes with some OS versions. Depending on the approach you take, you may need to connect a keyboard and monitor to the Raspberry Pi. I simply SSH into the Pi. You’ll also need familiarity with how to use an editor like vim or nano.</p><p>To compile and run the C program you’ll need the <a href="https://github.com/WiringPi/WiringPi">WiringPi</a> library. It’s easy to get:</p><pre>sudo apt-get install wiringpi</pre><p>Then test the installation using:</p><pre>pi@pi-node1:~/go/src/github.com/youngkin/gpio/rgbled $ gpio -v<br>gpio version: 2.50<br>Copyright (c) 2012-2018 Gordon Henderson<br>This is free software with ABSOLUTELY NO WARRANTY.<br>For details type: gpio -warranty</pre><pre>Raspberry Pi Details:<br>  Type: Pi 3B+, Revision: 03, Memory: 1024MB, Maker: Sony<br>  * Device tree is enabled.<br>  *--&gt; Raspberry Pi 3 Model B Plus Rev 1.3<br>  * This Raspberry Pi supports user-level GPIO access.</pre><p>In the above you’ll notice gpio version: 2.50. If you’re using a Rasberry Pi 4, use the instructions given in the Sunfounder <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/check_the_wiringpi_c.html">Checking the WiringPi</a>.</p><p>WiringPi is unique in that it includes a command line tool, gpio, as shown above, that can be used to manage, control, and query the GPIO board. This can be very handy. See the <a href="http://wiringpi.com/the-gpio-utility/">gpio reference</a> for more information on what it can do and how to use it.</p><p>If you’re interested in Go development on a Raspberry Pi you’ll need to install the development environment onto the Raspberry Pi. <a href="https://www.jeremymorgan.com/tutorials/raspberry-pi/install-go-raspberry-pi/">Here’s a simple source</a> that explains how to accomplish this. This source is a little dated, but the only significant issue is with the version of Go to install. The source shows installing Go <strong>1.14.4.linux-arm64.tar.gz</strong> and <strong>1.14.4.linuxarmv6l.tar.gz</strong>. The current versions are <strong>1.17.1.linux-arm64.tar.gz</strong> and <strong>1.17.1.linuxarmv6l.tar.gz</strong>. For the Raspberry Pi 3B+ the correct choice will be <strong>1.17.1.linuxarmv6l.tar.gz</strong>. The other is intended for 64 bit systems like the Raspberry Pi 4 series. You can find current ARM versions of Go at the <a href="https://golang.org/dl/">Golang download site</a>.</p><p>For Go development you’ll also need the <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> library.</p><p>If you want to veer away from the cookbook style of the Sunfounder docs you’ll need some basic knowledge of Linux . For example, I won’t be explaining what <strong>root privileges</strong> are.</p><p>Finally, I wrote an application that supports experimenting with the various PWM settings on the Raspberry Pi 3B+. There are 2 options for getting the code. First, you can clone or fork the <a href="https://github.com/youngkin/gpio.git">project</a> from GitHub. If you do that you’ll need to have experience with git and have it installed on the Raspberry Pi. See this <a href="https://linuxize.com/post/how-to-install-git-on-raspberry-pi/">article on installing git</a> for more details. After installing git you can download the project by running:</p><pre>git clone https://github.com/youngkin/gpio.git</pre><p>If you would like to contribute the project please fork the respository instead. As an alternative to using git you can also download a <em>zip</em> file of the project by navigating to the <a href="https://github.com/youngkin/gpio.git">project’s URL</a>, clicking on the <em>Code</em> button above and to the right of the file listing, and selecting <em>Download ZIP</em>.</p><h3>What is PWM?</h3><p>At it’s most basic, PWM is used to simulate an analog signal using a digital source (like a GPIO pin). As an example, an LED’s brightness and/or color can be modified by varying the voltage supplied to the LED. A variety of analog devices, such as a motor’s speed, can be controlled in the same way. PWM simulates varying voltages by varying the length of the digital power pulse within a given duration.</p><p>In addition to what’s presented here, <a href="https://www.kompulsa.com/introduction-pwm-pulse-width-modulation-works/">Introduction to PWM: How Pulse Width Modulation works</a> describes some of the same concepts described here as well as a few more examples of how PWM can be used. The <strong>References</strong> section has links to more sources of PWM information.</p><p>The follow sections cover the main points:</p><ul><li><strong>Terminology</strong> defines terms that will be used throughout the document</li><li><strong>Primary concepts</strong> describes the major concepts</li></ul><h4>Terminology</h4><p>My research into PWM involved reading several articles as well as examining the code of several PWM software libraries in various languages. These various sources aren’t completely consistent in the terminology they use. Here are some of the common terms, their aliases, and definitions. See the diagram below for a visual representation of the terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*6c_nQoYstL7qxZWA.png" /><figcaption>PWM timing diagram — Image Credit: Author</figcaption></figure><ul><li><strong>Frequency</strong> — Per <a href="https://en.wikipedia.org/wiki/Frequency">Wikipedia</a>, <em>frequency is the number of occurrences of a repeating event per unit of time</em>. In electronics an event is the peak of a wave to the next peak of the wave (analog). In digital terms an event is from the leading edge of one pulse to the leading edge of the next pulse. Frequency is measured in Hertz, which is the number of repeating events per second.</li><li><strong>Period</strong> — Also from Wikipedia, <em>period is the duration of time of one cycle in a repeating event.</em> Period is measured in seconds. So period is how long something takes vs. frequency which is how many times an event occurs in a given duration of time. This makes period the reciprocal of the frequency and vice versa, ie., <em>unit of time per event</em> vs. <em>events per unit of time</em>. In the above diagram the period is 10 milliseconds (ms). So the frequency in the above diagram is 1/.01 or 100. Since frequency is measured in Hertz, or events/second, the frequency in the above diagram is 100Hz.</li><li><strong>Clock source</strong> — Also called a clock, it sets the rate at which the clock advances.</li><li><strong>PWM clock</strong> — Sometimes also called a clock so this gets a bit confusing. The PWM clock’s underlying input is the clock source. Different hardware devices, such as motors and servos, only work within specific period ranges. Often the source clock is too fast for these devices. The PWM clock is created by dividing the clock source’s frequency with a number that will result in the PWM clock operating at a frequency that’s appropriate for a given device. Different devices will need different PWM clock speeds. The number used as the denominator in this calculation is frequently called the <strong>divisor</strong> in software libraries and the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">BCM2835 Data Sheet</a>.</li><li><strong>Pulse</strong> — From the “P” in PWM. This is the minimum length of time a PWM pin’s output is set to high or low. Its minimum length is governed by the speed of the PWM clock. I’ll use pulse throughout this document, mostly because it’s in the name.</li><li><strong>Range</strong> — Range can be thought of as a counter that counts PWM clock pulses. The ratio of range to PWM clock frequency can be thought of as the frequency of the signal sent to a PWM pin. I’ve also seen the term cycle length used as as an alias for range.</li><li><strong>Pulse width</strong> — Pulse width is the duration of a pulse. In the various software libraries I’ve seen it called <em>width</em>, <em>value</em>, <em>data</em>, and <em>duty length</em>.</li></ul><h3>Primary concepts</h3><ul><li><strong>Duty cycle</strong> is the ratio of Pulse Width to Range, i.e., Pulse-Width/Range. For a range of 10 and a pulse of 5, the duty cycle is 5/10 or 50%. Duty cycle regulates the output voltage of a PWM device. For a 50% duty cycle and an input voltage of 5 volts, the output voltage will be 2.5 volts.</li><li><strong>Software vs. Hardware PWM</strong> — For the purposes of this article there are 2 ways to generate a PWM signal, software-based and hardware-based (<a href="https://stackoverflow.com/questions/50427275/raspberry-how-does-the-pwm-via-dma-work">there is one more way</a>). Hardware-based PWM is generated by a dedicated hardware PWM device that can be configured to generate a PWM signal as described above. Hardware-based PWM produces a very uniform signal with regard to timing. A uniform signal is required, for example, to produce a flicker-free light source such as an LED. Software-based PWM is directly implemented in the executing program using a while(true) for loop that never ends which controls the amount of time a pin is allowing current to flow (pulse) vs. the amount of time the pin isn’t allowing current to flow. In this case the uniformity of the signal is determined by the accuracy of a language’s sleep() function and the OS (Linux) scheduler. A less uniform signal, for example, may result in a flickering light source. There is a more complete description of <a href="https://raspberrypi.stackexchange.com/questions/100641/whats-the-difference-between-soft-pwm-and-pwm">the difference between soft PWM and PWM</a> and associated pros and cons on the Raspberry Pi Stack Exchange site.</li><li><strong>Balanced vs. Mark/Space</strong> refers to the method used to determine how the PWM output signals are to be generated. There are 2 algorithms, balanced and mark/space. Balanced indicates that the duty cycle will be evenly spread across the range. That is to say, the pulse width will be split into a set of shorter pulses that are distributed across the range. In contrast, in mark/space, the pulse is generated as a single signal called a “mark”. The time remaining in the range, range-pulseWidth , is called the “space”. No signal is present in the space duration. Mark/Space is often good enough, but as periods get longer so does the absolute time difference between the mark and space durations. For large ratios of range/PWMClockFrequency, e.g., 1 (<em>which equates to 1Hz since the denominator unit is frequency</em>) and a duty-cycle of 50%, the space will be 500 milliseconds and the mark will be 500 milliseconds. This difference is large enough to be discernable in the behavior of the device. For example a motor might surge or a light flicker. In contrast, balanced mode will smooth out these differences. For the same 1Hz range and 50% duty-cycle, balanced mode might produce 500 1 millisecond signals every 2 milliseconds (1/(500 * .002) = 1 = 1Hz). The same 50% duty-cycle is produced, but the output signal is much smoother. Hardware implementations like the BCM2835 support both algorithms. It is possible to support both algorithms in software, but depending on the algorithms are implemented they may consume a significant amout of CPU.</li></ul><h3>Overview of PWM on a Raspberry Pi 3B+</h3><p>Physically PWM is implemented via the BCM2835’s GPIO pins. The BCM2835 board has 40 pins, a subset of which are GPIO pins. Of the <a href="https://pinout.xyz/">GPIO pins</a> there are 4 hardware PWM pins, 13, 19, 12, and 18. The remaining GPIO pins, as well as the hardware GPIO pins, can be used for software PWM.</p><p>There are several clock sources available on the BCM2835 board. The clock source used by the GPIO libraries in this article is called the oscillator. It’s frequency as documented in several references is 19.2MHz with a period of about 52 nanoseconds (1 / 19,200,000 = ~0.000000052 seconds).</p><p>The BCM2835 board also implements something called a channel. A hardware PWM pin is controlled by a channel. The PWM Clock, range, and pulse width are specified for a channel. All hardware pins connected to that channel will share the same range, pulse-width, and duty-cycle. The BCM2835 board has 2 channels. GPIO pins 18 and 12 on one channel, 13 and 19 on the other. This means that a signal that’s sent to either pin that share a channel will go to both pins. For example, sending a signal on GPIO12 will also be shared with GPIO18 and vice versa.</p><h3>Exploring PWM on a Raspberry Pi</h3><p>The setup for this exercise is similar to a combination of the <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.1_blinking_led_c.html">SunFounder Blinking LED</a> and <a href="https://docs.sunfounder.com/projects/raphael-kit/en/latest/1.1.2_rgb_led_c.html">Sunfounder RGB LED</a> projects. If you’re familiar with wiring a breadboard the diagrams below may be all you need to get started. Otherwise, it may be worthwhile looking at the Sunfounder LED projects and an <a href="http://wiki.sunfounder.cc/index.php?title=Breadboard_Basics_%E2%80%93_Types">introduction to breadboards</a><a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/#fn:10">10</a>. The resistor used in both diagrams is 220 Ohms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*ObQIsuYxUFzB7zCBeOoSjw.jpeg" /><figcaption>Image Credit: <a href="http://www.oomlout.co.uk/">oomlout</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OQSRDpELm2VsjVz6.png" /><figcaption>Breadboard wiring for software PWM — Image Credit: Author</figcaption></figure><p>This first setup will be used to demonstrate software PWM on a non-PWM pin. The black wires are the ground. The upper black wire connects the board <em>GND</em> pin to the ground bus on the breadboard. The lower black wire connects the ground bus to the negative leg on the red LED (negative is the shorter leg). The red wire is for positive current. It connects GPIO6 to the positive leg on the red LED (positive is the longer leg). Note the 220 Ohm resistor bridging the red wire and the positive pin on the LED. This is required to avoid burning out the LED.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3H_d2q0rrAr3ZJM-.png" /><figcaption>RGB Breadboard setup for hardware PWM — Image Credit: Author</figcaption></figure><p>This next setup will be used to demonstrate hardware and software PWM on a hardware PWM pin. Looking down at the the breadboard the RGB LED the pins are set up as follows:</p><ul><li>The red pin is at the top of the RGB LED. It’s connected to GPIO pin 13 with the red wire.</li><li>The ground is the next one down. It’s connected to the ground bus with the black wire. As with the red LED above, the longer leg is the ground.</li><li>The green pin is 1 down from the ground. It’s connected to GPIO pin 18 with the white wire.</li><li>The blue pin is at the bottom of the RGB LED. It’s connected to GPIO pin 19 with the blue wire.</li></ul><p>As with the previous diagram, a 220 Ohm resistor bridges the GPIO pins to the red, green, and blue pins of the LED.</p><p>This setup shows the green pin on the LED (white wire) connected to the GPIO hardware PWM pin 18. A different hardware PWM pin may be used such as 12, 13, and 19. Also, the use of an RGB LED isn’t required. Any type of LED will work. It will have to be wired up in a similar manner however, i.e., the LED positive lead should be connected to a hardware PWM pin (white wire) and the LED’s ground lead (the longest lead) to the board’s ground.</p><p>If you do choose to use an RGB LED pin it’s important to note that only 2 of the colors can be controlled by hardware PWM. The pins need to be on different PWM channels. In the diagram above the red and blue pins attached to GPIO pins 13 and 19 (blue and red) to demonstrate this limitation. Recall that GPIO pins 13 and 19 share a channel. As a result, a signal sent to one pin be propagated to the other. To get the true RGB LED colors software PWM is required, along with a maximum of 2 hardware pins on different channels. While hardware pins can be used, it’s also possible to use all non-hardware pins.</p><p>It’ll be easier to play with the different combinations of PWM settings when both of the above setups are wired up at the same time. It allows for any of the GPIO pins to be used by <em>PWM Explorer</em>, with the exception that for hardware PWM the LED(s) must be installed on hardware PWM pins (GPIO pins 13, 19, 18, and 12). If more than one hardware pin is used they must be on different channels.</p><h3>Driving PWM using PWM Explorer</h3><p>PWM Explorer supports C and Go. Choosing C you can experiment with both Mark/Space and Balanced PWM Modes. The Go library I used, <a href="https://github.com/stianeikeland/go-rpio">go-rpio</a>, only supports Mark/Space.</p><p>As described in the <strong>Prerequisites</strong> section above, I wrote an application, called <em>PWM Explorer</em>, to experiment with PWM on a Raspberry Pi. This software can be used to drive PWM on both PWM and non-PWM pins. It also supports changing the various PWM parameters like divisor, range, and pulse width to provide visual feedback on the effect of these parameters on the behavior of the LEDs connected to the pins. This software is available on my <a href="https://github.com/youngkin/gpio">gpio GitHub repository</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YFeHbdmb_dzc7oDm.jpg" /><figcaption>PWM Explorer — Image Credit: Author</figcaption></figure><p>The diagram above is a screenshot of the main program and has labels with brief descriptions of the various sections of the user interface. It’s a text based UI so that it can be run on a Raspberry Pi that doesn’t have the desktop capability installed. It can be run at the command line by navigating to the installation directory under the gpio/pwmdemo/pwmexplorer directory and running sudo /usr/local/go/bin/go run main.go. sudo is needed because some of the GPIO access requires root permissions. In addition to the main UI application there are 2 supporting programs in the gpio/pwmdemo/pwmexplorer/apps directory, freqtest.go and freqtest.c. These are the actual implementations of the code required to interact with the PWM capabilities on the Raspberry Pi 3B+ using the go-rpio and WiringPi libraries. They are written in Go and C respectively. The C program must be built prior to running PWM Explorer. This is accomplished by changing to the gpio/pwmdemo/pwmexplorer/apps directory and running gcc -o freqtest freqtest.c -lwiringPi -lpthread.</p><p>There are a variety of PWM parameters supported. These are:</p><ol><li><strong>PWM Pin</strong> — this item allows you to choose a PWM hardware pin to use. The pins available in the dropdown are specific to the language chosen. C uses the WiringPi library which uses its own pin numbering scheme. Go uses the standard GPIO pin numbers</li><li><strong>Non-PWM Pin</strong> — this item allows you to specify a PWM pin to use, even a hardware pin. PWM Pin and Non-PWM Pin are mutually exclusive and the program will prevent you from specifying both. As with PWM Pin above, the numbering scheme is specific to the language, C or Go, chosen. The program offers no protection against using the wrong pin numbering scheme so be careful what you specify. If the pin chosen doesn’t behave as expected it may be that you used the wrong pin numbering scheme.</li><li><strong>Clock Frequency/Clock Divisor</strong> — this item is used to set the PWM clock frequency. The go-rpio library supports specifying the PWM clock frequency directly. The C WiringPi library uses the concept of divisor defined above to set the PWM clock frequency. You can calculate the divisor to use by dividing the Raspberry Pi 3B’s oscillator clock’s frequency of 19,200,000 Hertz by the desired PWM clock frequency. For example. to get a 100kHz PWM clock frequency divide 19,200,000 by 100,000. This calculation gives the Clock Divisor to use, 192 in this case. To avoid confusion, when C is the chosen language the label will be <em>Clock Divisor</em>. When Go is the chosen language this items label will be <em>Clock Frequency</em>.</li><li><strong>PWM Mode</strong> — this item is used to specify whether Mark/Space or Balanced modes will be used. Note: some combinations of language, pin type (PWM vs. non-PWM), and PWM Type (hardware/software) don’t support Balanced mode. When this is the case a message will be displayed in the <em>Messages</em> area. The Go go-rpio library doesn’t support balanced mode.</li><li><strong>Range</strong> — the desired range as defined in the <strong>Terminology</strong> section above.</li><li><strong>Pulse Width</strong> — the desired pulse width as defined in the <strong>Terminology</strong> section above.</li><li><strong>PWM Type</strong> — this item is used to specify whether hardware or software PWM is to be used.</li></ol><p>Depending on the terminal size some <em>Help</em> and <em>Code</em> text may not be visible. To address this, both the <em>Help</em> and <em>Code</em> sections are scrollable.</p><h4>Experimenting with PWM Parameters</h4><p>As was stated earlier, the WiringPi and go-rpio libraries both use the Raspberry Pi 3B’s Oscillator clock which has a frequency is 19.2MHz. This is fixed and cannot be changed. But besides the pins chosen, the Clock Frequency/Divisor, PWM Mode, Range, Pulse Width, and PWM Type can all be modified. All of these interact with one another either directly or indirectly. In this section I will explain these relationships and how they interact. You can use the PWM Explorer to follow along and directly see the effects that I’ll explain.</p><p>This section uses an LED to demonstrate the effect of the various parameters on a device. There is a property of the human eye that needs to be understood. The human eye perceives linear changes in in brightness in a logarithmic fashion. Specifically, at the lower end of a pulse width setting (lower voltage) changes in a given setting will produce what looks like a more significant result than the same change at the higher end (higher voltage)<a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/#fn:18">18</a>. The PWM Explorer doesn’t compensate for this.</p><h4>PWM Clock Frequency / Clock Divisor</h4><p>The first thing to decide is what frequency you want the PWM clock to run at. It’s frequency is specified directly when using Go and via the divisor when using C. Choosing this frequency is impacted by the type of PWM device being used, e.g., an LED or a motor. This article doesn’t cover how to calculate this frequency, but there are sources that do (see references 3 &amp; 4). Instead I’ll focus on the general impact of clock frequency on LED devices.</p><p>You may or may not be aware that the human eye can detect flickering starting at about 60Hz and below. Flickering is more apparent using peripheral vision. Given this, a PWM clock frequency to Range, PWMClockFrequency / Range, below 60Hz isn’t ideal unless you’re trying to create a blinking LED. Assuming the range can’t be modified, choosing the right Clock Frequency/Divisor will directly impact whether an LED appears to be a steady light source, flickering, or blinking.</p><p>Here are some settings to try this out <em>(these assume the LED is wired up to GPIO pin 18)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*MIwCErYjSjcbsXj1WR1NCA.png" /><figcaption>Image Credit: Author</figcaption></figure><p>Using the above settings will result in a 30Hz frequency at the pin. As this is well below 60Hz flickering will be apparent. Changing the PWM Clock Frequency/Clock Divisor will result in a pin frequency of 62.5Hz. The result will be that there is no apparent flickering.</p><p><strong>Note:</strong> The “General Purpose Clock Divisors” on the BCM2835 have a register width of 12 bits (see the <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">Broadcom spec for the BCM2835</a>, page 108, DIVI field bits 23 thru 12). This means the maximum value of the Clock Divisor is 4095 (0 to 2^12-1). The go-rpio further states that PWM Clock frequencies below 4688Hz will result in “unexpected behavior” (rpio.go, see comments for SetFreq() function). Other sources state that 9.6Mhz is the highest available PWM Clock frequency (19.2Mhz/2). I’ve seen unexpected results with both frequencies below 4688Hz and above 9.6Mhz.</p><h4>Range</h4><p>Range effectively determines the frequency of the signal at the GPIO pin. This means that the frequency at the pin is defined by the ratio of PWM Clock Frequency/Range. Another thing range determines is the resolution of the signal going to the device. Recall that Duty Cycle is the ratio of Pulse Width to Range. Starting with a lower value of range, say 4, limits duty cycle to 0%, 25%, 50%, 75%, or 100%. To say it a different way, with a Range of 4 the only values for Pulse Width that make sense are 0, 1, 2, 3, 4. This in turn limits things like the range of LED brightness or blinking that’s available.</p><p>Since range impacts frequency at the pin <em>and</em> the resolution, it is important to choose the correct PWM clock frequency, Range, and Pulse Width in combination. Starting with a low PWM Clock frequency limits the choice of range which in turn limits the available duty cycles.</p><p>As an example let’s choose 2 extremes. For the first, let’s choose a PWM Clock frequency of 5kHz and a range of 5. The resolution is 5. This means are only 5 available duty cycles including full-on and full-off. As described above this limits the available brightness settings for a light like an LED.</p><p>Here are the settings to try this example <em>(the settings for the second example are in parentheses)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*Q43c8YRJ1S6JPdnWskVG6w.png" /><figcaption>Image Credit: Author</figcaption></figure><p>Then change to Pulse Width to 5. This will be the brightest setting of the LED. While it is noticably brighter than a Pulse Width of 1, due to the narrow range it’s not that much brighter.</p><p>At the other extreme let’s configure an LED for an extremely smooth transition from off to full brightness. This will require a higher resolution. Let’s go crazy and decide that we’d like to have 10,000 steps of brightness available. This translates to a range of 10,000. To avoid visible flickering we need to have at least a 60Hz signal at the GPIO pin. Since the ratio of PWM Clock Frequency/Range determines the signal frequency at the pin, we will need a PWM Clock frequency of at least 600kHz. A range of 10000 times a minimum pin signal frequency of 60Hz is 600kHz (10,000 * 60 = 600,000). To check our work, PWM Clock Frequency / Range, 600,000 / 10,000 = 60 (Hz).</p><h4>Pulse width</h4><p>At higher GPIO pin frequencies pulse width effects the brightness of an LED. At lower GPIO pin frequencies pulse width is visible as the length of time the LED is on vs. the blink rate. Let’s again use extreme examples to illustrate this.</p><p>For the first example let’s use a PWM clock frequency of 1MHz and a range of 10,000. The frequency at the GPIO pin will be 100Hz 1,000,000/10,000), fast enough that no blinking or flickering will be visible. The range of 10,000 is likewise high enough that we won’t be able to discern discrete steps in the brightness of the LED.</p><p>Here are the settings for the first example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*dYRZx-slWz1KUOVmYqWmAg.png" /><figcaption>Image Credit: Author</figcaption></figure><p>For the second example change the Clock Frequency (Go) to 5000, Clock Divisor (C)to 3840, the Range to 10000, and the Pulse Width to 5000. The LED will flash for a very short period of time and will repeat flashing about once every 2 seconds (Clock Frequency/Range, 5000/10000 = 0.5Hz or once every 2 seconds). Now change the Pulse Width to 5000. Now the LED will be on for 1 second and off for 1 second. This changed the duty cycle from 2% to 50% with the corresponding change in the duration of the LED flash. This example shows how to create a blinking light using PWM, just choose a PWM Clock Frequency and range that result in a very low GPIO pin frequency, well below 60Hz.</p><h4>PWM Mode</h4><p>The available PWM modes are balanced and mark/space. Recall that with mark/space the signal is either on or off (high or low) for a fixed duration within the range. For example, with a duty cycle of 50% and a range of 10, the signal will be on for 5 consecutive seconds and off for 5 consecutive seconds. As explained above, balanced mode will spread this 50% duty cycle evenly across the range which will make the effects of the duty cycle less apparent, except for a dimming of the LED (e.g., a 10ms pulse, every 10ms, 500 times over 10 seconds).</p><p>To illustrate this behavior set the Clock Frequency to 4688 (Go), Clock Divisor to 4095 (C), the PWM Mode to markspace, the Range to 1000, the Pulse Width to 10, and the PWM Type to hardware. This results in a blinking LED at a pin frequency of about 4.69Hz, or almost 5/second. Now change the PWM Mode to balanced. The language must be C to use balanced mode as go-rpio only supports mark/space. Now the blinking is no longer apparent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*cQTAfdg7azyfFS6T8i77yA.png" /><figcaption>Image Credit: Author</figcaption></figure><h4>PWM Type</h4><p>The available PWM Types are <em>hardware</em> and <em>software</em>. The examples above used hardware PWM only. This is because true balanced mode is only available on hardware. In addition, the software PWM as implemented in Go and C is more akin to balanced mode and definitely not mark/space. Both the Go and C versions have a hardcoded 100MHz clock. Some of the examples in previous sections rely on mark/space behavior, especially the PWM Mode section.</p><h4>Other things to try</h4><p>To see how the above works with non-PWM pins, try some or all of the above on non-hardware PWM pins using a PWM Type of software. Monitoring CPU usage during these tests might show some differences between CPU usage for hardware vs. software PWM.</p><h4>PWM Explorer code</h4><p>The code in the <a href="https://github.com/youngkin/gpio">PWM Explorer</a> GitHub Repository is extensively commented. To avoid repeating what is best illustrated directly in the code there’s not much to say here. The structure of both programs is substantially similar although there are differences is how the Go and C libraries are used to accomplish the same task.</p><h4>Key takeaways</h4><ol><li>On the Raspberry Pi there are only 4 hardware PWM pins and 2 channels. There are 2 pins per channel. This reduces the number of effective hardware PWM pins to 2.</li><li>Care must be taken when specifying the Clock Frequency or Clock Divisor. The acceptable range for PWM Clock frequency is 4688Hz to 9.6Mhz.</li><li>Range determines both the frequency at the GPIO pin and the resolution of the signal to a device like an LED or motor. The first, frequency, is significant because at lower pin frequencies the on/off states of the pin become very apparent, as in a blinking LED light. The second, resolution, is important because it defines how fine grained the control of the device will be. For example, at low resolutions there are only a limited set of LED brightnesses that can be chosen and the differences are very apparent. At higher resolutions small changes in pulse width will result in a very small, hardly discernable, change in brightness. This is important when implementing something like a dimmer where the change in brightness from off to fully on should not change in large, discernable steps of brightness. I.e., a smoother transition through the range is desired.</li><li>For higher resolutions (Range) a higher PWM clock frequency should be chosen. This ensures that the GPIO pin frequency won’t drop too low, e.g., below the 60Hz frequency needed to avoid a flickering LED light.</li><li>At higher GPIO pin frequencies (e.g., above 60Hz) changing the pulse width will cause the LED to appear dimmer or brighter.</li><li>At lower GPIO pin frequencies (e.g., below 60Hz, and especially below 10Hz) pulse width can be used to cause obvious pulsing, as in a blinking LED light. The length of time the light is on is directly proportional to the pulse width.</li><li>Choice of PWM mode also impacts the “smoothness” of the signal. Even at low GPIO frequencies, which would normally cause an LED to blink, balanced mode will reduce that effect, often to the point of rendering it unnoticable.</li><li>PWM type (software vs. hardware) can affect the consistency of the period of a PWM signal to the point that even above 60Hz an LED might noticably flicker. It can also result in an inordinate amount of CPU load needed to support the desired clock rate.</li><li>Software PWM can be used, but the resulting signal can be too ragged to be used in some devices.</li><li>Setting a range that is greater than the PWM Clock frequency may seem odd, but it can be used effectively to create a low frequency, pulsing signal that can be used for, among other things, causing an LED to blink.</li></ol><h3>Summary</h3><p>Hopefully by now you have enough knowledge to start effectively using PWM on a Raspberry Pi 3B+, or perhaps on other Raspberry Pi models or even on other platforms entirely. Specifically:</p><ul><li>We’ve gone through the various terms so you should now be able to read most of the literature on PWM and understand the concepts and terms used in those sources.</li><li>If you followed along setting up and experimenting with PWM on your Raspberry Pi you now have a full, working, GPIO test bed installed on your Raspberry Pi.</li><li>You should have an understanding of the various PWM settings and how they interact with each other.</li><li>If you used the <em>PWM Explorer</em> application you have valuable hands-on experience with using various combinations of PWM settings. You can continue to use the <em>PWM Explorer</em> to experiment with various settings when you have questions or to test assumptions.</li><li>By reading the Go and/or C code you now know how to effectively use the go-rpio and/or WiringPi libraries. Even if you decide to use other libraries, like <a href="https://abyz.me.uk/rpi/pigpio/pdif2.html">pigpio</a>, you should understand the terminology well enough to use them effectively, or at least have a good start on learning how to use them.</li></ul><h3>References</h3><ol><li><a href="https://github.com/youngkin/gpio">PWM Explorer</a> is an application that accompanies this article that can be used to experiment with various PWM settings. It demonstrates PWM using both Go and C libraries.</li><li><a href="https://www.allaboutcircuits.com/technical-articles/introduction-to-microcontroller-timers-pwm-timers/">Introduction to Microcontroller Timers: Periodic Timers</a> is a good general introduction to timers. PWM hardware is one type of periodic timer. It is useful to read this introduction.</li><li><a href="https://www.allaboutcircuits.com/technical-articles/introduction-to-microcontroller-timers-pwm-timers/">Pulse-width Modulation (PWM) Timers in Microcontrollers</a> is a good detailed discussion about PWM timers. It’s an excellent read if you want more detail than presented here.</li><li><a href="https://www.iot-programmer.com/index.php/books/22-raspberry-pi-and-the-iot-in-c/chapters-raspberry-pi-and-the-iot-in-c/60-raspberry-pi-and-the-iot-in-c-pulse-width-modulation-servos-and-more">Raspberry Pi And The IoT In C — Pulse Width Modulation, Servos And More</a> is a detailed book about programming GPIO on the Raspberry Pi. There is a chapter devoted to PWM.</li><li><a href="https://github.com/WiringPi/WiringPi">WiringPi</a> is a C library for GPIO programming</li><li><a href="https://github.com/stianeikeland/go-rpio">go-rpio</a> is a Go library for GPIO programming</li><li><a href="https://www.airspayce.com/mikem/bcm2835/">bcm2835 by Mike McCalley</a> is another C library for GPIO programming.</li><li><a href="https://abyz.me.uk/rpi/pigpio/pdif2.html">pigpio</a> is primarily a Python library. It also has a C library. It has the distinction of performing hardware PWM on any GPIO pin. I’m not sure how it does this.</li><li><a href="https://projects.raspberrypi.org/en/projects/raspberry-pi-setting-up">Setting up your Raspberry Pi</a> is the official documentation for getting started with a Raspberry Pi including things like required hardware as well as how to install the OS and other important details.</li><li><a href="http://wiki.sunfounder.cc/index.php?title=Breadboard_Basics_%E2%80%93_Types">Breadboard Basics — Types</a> is a useful introduction to breadboards and how to use them.</li><li><a href="http://wiringpi.com/reference/">WiringPi library reference guide</a> documents the main WiringPi functions. The rest of the website also has some useful information.</li><li><a href="https://en.wikipedia.org/wiki/Frequency#CITEREFSerwayFaughn1989">Frequency page on Wikipedia</a> discusses frequency and period</li><li>A <a href="https://www.sensorsone.com/frequency-to-period-calculator/">Frequency to Period Calculator</a> is handy for quick calculations, or validation, of frequency to period conversion (period = 1/frequency).</li><li>The <a href="https://www.raspberrypi.org/app/uploads/2012/02/BCM2835-ARM-Peripherals.pdf">full Broadcom spec for the BCM2835</a>, starting at page 138, for more details about how PWM is implemented on the BCM2835.</li><li>There’s a detailed discussion about <a href="https://www.raspberrypi.org/forums/viewtopic.php?t=150254">Which pin(s) on RPi 3B is PWM capable</a>. Specifically regarding the effect of sharing 2 PWM channels for 4 PWM pins. The Broadcom spec<a href="https://youngkin.github.io/post/pulsewidthmodulationraspberrypi/#fn:14">14</a> also discusses this in section 9.4 on page 139, but in a less obvious way.</li><li>There is a 3rd way to generate PWM signals, <a href="https://stackoverflow.com/questions/50427275/raspberry-how-does-the-pwm-via-dma-work">DMA or Direct Memory Access</a>. It won’t be discussed here in this article.</li><li><a href="https://pinout.xyz/">RaspberryPPi Pinout</a> is a good source that describes each pins’ role, physical pin number, and for GPIO pins the GPIO pin number for the BCM2835 board. It has tabs that can be used to highlight which pins serve which purpose, e.g., PWM pins.</li><li><a href="https://jared.geek.nz/2013/feb/linear-led-pwm">Linear LED PWM</a> provides guidelines/formulas for getting linear scaling when changing the brightness of an LED via PWM. Googling “LED PWM linear brightness” brings up several other articles as well.</li><li><a href="https://raspberrypi.stackexchange.com/questions/53854/driving-pwm-output-frequency">Driving PWM output frequency</a> provides some interesting information and discussion on Raspberry Pis with 26 and 40 GPIO pins.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10005f3f3583" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/raspberry-pi-pulse-width-modulation-for-dummies-10005f3f3583">Raspberry Pi Pulse Width Modulation for Dummies</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Secure Clients and Servers in Golang Using HTTPS]]></title>
            <link>https://medium.com/better-programming/create-secure-clients-and-servers-in-golang-using-https-aa970ba36a13?source=rss-80d16197df23------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa970ba36a13</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Richard Youngkin]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 20:37:34 GMT</pubDate>
            <atom:updated>2020-09-25T20:37:34.353Z</atom:updated>
            <content:encoded><![CDATA[<h4>Write secure web applications in Go and understand the details</h4><figure><img alt="Padlock on metal gate" src="https://cdn-images-1.medium.com/max/1024/1*dPgg1rD2lJOxovKOSpwIuQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@yogesh_7?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Yogesh Pedamkar</a> on <a href="https://unsplash.com/@yogesh_7?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Overview</h3><p>The purpose of this article is to show how to write secure web services and clients using <a href="https://golang.org/">Go</a> and HTTPS. In researching how to accomplish this, I came across numerous articles and gists. However, none of them provided the complete picture I needed to implement a robust client or server. Most of them only provided terse code examples with equally terse examples regarding how to create the certificates needed for the code to work. Others were oriented to gRPC or plain TLS over TCP. I also wanted to understand what I was doing, not just the syntax. The point of this article is to provide not only the <em>how</em> but also the <em>why</em>s behind the <em>how</em>.</p><p>If you’re already familiar with HTTPS, TLS, and public/private keys, you can skip this next section, <strong>Security Overview</strong>, and move directly to <strong>Create Certificates and Keys</strong>.</p><h3>Security Overview</h3><p>Security is paramount to ensure the privacy and wellbeing of customers. They want to be certain that the information they provide, like passwords and credit card numbers, is going to the expected service provider. Likewise, it is sometimes necessary for service providers to ensure that they are communicating with the expected customer.</p><p>There are two characteristics of secure communications: trust and encryption.</p><p>Trust is the foundation of security. Without trust, there can be no assurance that the parties to a conversation are not bad actors.</p><p>Encryption is required to ensure that bad actors can’t listen in on a conversation and gain access to sensitive information or perform harmful actions.</p><p>The following requirements must be met to ensure trust and security:</p><ul><li>Trusted authorities must exist that can vouch for the identity of a client or a server.</li><li>Trusted sources of encryption technology that can be used by clients and servers to encrypt their communications must also exist.</li><li>There must be support in the code for the associated techniques and technologies that are used to implement client and server applications.</li></ul><p>The umbrella for all these things is called the <a href="https://en.wikipedia.org/wiki/Public_key_infrastructure">public key infrastructure(PKI)</a>. There are four components to PKI that implement the requirements outlined above:</p><h4>Public key encryption</h4><p>A public key can be safely shared by the owner with another party and provides the other party with the ability to encrypt and decrypt a conversation. The owner of a public key has a corresponding private key that is not shared. A public key can only decrypt information that was encrypted with the corresponding private key. Likewise, the private key is required to decrypt information that was encrypted with a public key. This asymmetric characteristic of the encryption guarantees that information can be securely shared between known parties to a conversation.</p><h4>Certificates</h4><p>Certificates contain the identity of the holder as well as the certificate owner’s public key. A certificate also includes information about the trusted authority that issued the certificate.</p><h4>Certificate authorities (CA)</h4><p>Certificate authorities are the trusted source of identity information. They can also issue certificates or delegate that authority to a registration authority.</p><h4>Registration authority (RA)</h4><p>A registration authority is a trusted source of certificates. Any certificates issued by an RA will also contain the certificate of the CA that authorized them to issue certificates. This is required to ensure the trust requirement can be met. In other words, RAs themselves are only trusted because they can prove that they’re trusted by a CA.</p><h3>Create Certificates and Keys</h3><p>The basis for proving identity and encrypting information is a certificate and a corresponding certificate authority. For the purposes of this article, we’ll need both. There are two ways to go about obtaining these, the hard way and the easy way. The hard way is appropriate for real-world applications. It involves registering a domain (e.g., youngkin.com), obtaining DNS services for that domain, and obtaining a certificate for that domain. While not difficult, it will require a fair amount of work, and you’ll probably have to spend some money to register the domain.</p><p>An easier way to provide a realistic experience is to create your own CA and obtain a certificate from this CA. This article uses CA-signed certificates vs. self-signed certificates in order to create that more realistic experience. I found creating a CA, requesting certificates, and having the CA sign those certificates helpful in understanding the entire process.</p><p>Usually, servers access CA certificates installed on the machine. This article will demonstrate how to register a CA certificate programmatically.</p><p>There are at least a couple of tools available to help us with the easy way, <a href="https://github.com/square/certstrap">certstrap</a> and <a href="https://github.com/OpenVPN/easy-rsa">Easy-RSA</a>.</p><p>The definitive command-line tool for working with certificates is called openssl. It can be used to create CAs, RAs, and certificates, as well as do many other useful things (see the References section below for more details). It can also be used to create what are called <em>self-signed certificates</em>. <a href="https://linuxize.com/post/creating-a-self-signed-ssl-certificate/">Creating a Self-Signed SSL Certificate</a> is a good resource for how to do this. While it’s oriented to Linux, there are versions of openssl available on Windows and Mac machines. I recommend installing the Libre fork of openssl. The reasoning behind this is well described in a <a href="https://security.stackexchange.com/questions/112545/what-are-the-main-advantages-of-using-libressl-in-favor-of-openssl">Stack Exchange question/answer</a>. To verify whether you have Libre openssl run the following:</p><p>$ openssl version<br>LibreSSL 2.8.3</p><p>Output like the above indicates Libre openssl is being used.</p><p>Several files will be created during the certificate generation process, some with .crt and .key suffices. You may also see the suffix .pem when reading about certificates. It’s worth noting that .pem files are equivalent to .crt and .key files. PEM is a file format. .crt and .key are hints as to what the file contains (certificates and keys), but these files all use the PEM format. See <a href="https://stackoverflow.com/questions/62823792/how-to-get-crt-and-key-from-cert-pem-and-key-pem">this StackOverflow discussion</a> for more details about this.</p><h3>Install Software to Create the CA and Certificate(s)</h3><p>As mentioned above, there are at least two options available to easily create a CA and a CA’s registered certificates. This article will use certstrap for no other reason than it was written in Go. However, Easy-Rsa is a good alternative.</p><p>Before starting, download the appropriate executable from the <a href="https://github.com/square/certstrap/releases">certstrap releases</a> page on GitHub. I placed mine in my ~/bin directory which is in my PATH. You’ll also need to make it executable (chmod +x &lt;downloadedfilename&gt;).</p><p>We’ll follow the <a href="https://github.com/square/certstrap">usage instructions</a> from the project’s README. At the end of this section, we will have created a CA, a certificate for our server, and a certificate for our client. I keep all my certificates in a directory called ~/certs. All the following commands will be run from that directory. When prompted for the pass phrase, just hit enter (i.e., no pass phrase).</p><h3>Create the CA</h3><pre>~/certs certstrap init --common-name &quot;ExampleCA&quot;         <br>Enter passphrase (empty for no passphrase):<br>Enter same passphrase again:<br>Created out/ExampleCA.key<br>Created out/ExampleCA.crt<br>Created out/ExampleCA.crl</pre><p>init directs certstrap to create a new CA. --common-name (CN) specifies the name for our CA, which is named <em>ExampleCA</em>. Three files are created:</p><ul><li>ExampleCA.key is the private key for <em>ExampleCA</em></li><li>ExampleCA.crt is the certificate for <em>ExampleCA</em></li><li>ExampleCA.crl is the certificate revocation list (CRL) for that CA. It contains a list of revoked certificates issued by the associated CA.</li></ul><p>A <em>common name</em> or CN is typically the fully qualified domain name (FQDN) of the host associated with a certificate (<a href="https://jamielinux.com/docs/openssl-certificate-authority/sign-server-and-client-certificates.html">not strictly true for client certificates</a>).</p><p>See <a href="https://jamielinux.com/docs/openssl-certificate-authority/certificate-revocation-lists.html">this source</a> for information on certificate revocation lists.</p><h3>Create the Certificates for the Client and Servers</h3><pre>~/certs certstrap request-cert --domain  &quot;localhost&quot;       <br>Enter passphrase (empty for no passphrase):<br>Enter same passphrase again:<br>Created out/localhost.key<br>Created out/localhost.csr</pre><pre>~/certs certstrap request-cert --domain  &quot;client&quot;<br>Enter passphrase (empty for no passphrase):<br>Enter same passphrase again:<br>Created out/client.key<br>Created out/client.csr</pre><p>localhost is used as the domain for the server since, as noted above, a valid FQDN of the host is required for servers. localhost suffices for this purpose. Using the --domain flag will create a <em>subject alternative name</em> (SAN) in addition to the CN in the certificate signing request (CSR) and in the certificate itself. SANs are the current standard for specifying a number of methods for addressing a service, including by FQDN or domain name.</p><p>There’s an alternative to --domain, and that’s --common-name. We used --common-name to create the CA above. --common-name will only generate a CN. Starting in Go 1.15, certificates must contain a SAN entry or the https request will fail. Certificates with only a CN will not be accepted. If Go 1.15 or higher is used and --common-name is used to generate the CSR, you will likely see the following error from the client:</p><pre>Get &quot;https://localhost&quot;: x509: certificate relies on legacy Common Name field, use SANs or temporarily enable Common Name matching with GODEBUG=x509ignoreCN=0</pre><p>As noted in the error message, this problem can be overcome by prefixing the client command with GODEBUG=x509ignoreCN=0.</p><h3>Sign the Certificates for the Client and Servers</h3><pre>~/certs certstrap sign localhost --CA ExampleCA  <br>Created out/localhost.crt from out/localhost.csr signed by out/ExampleCA.key</pre><pre>~/certs certstrap sign client --CA ExampleCA   <br>Created out/client.crt from out/client.csr signed by out/ExampleCA.key</pre><p>Please note that all certificates and associated keys were placed in the ./out directory.</p><p>Certificates must be signed by a trusted authority (in this case, the CA) in order to be valid. Signing is a guarantee by the CA that the owner of the certificate is who they say they are. The --CA flag above directs certstrap to have the certificates signed by our ExampleCA.</p><p>At this point, we have certificates and keys for the CA, the client, and the server.</p><h3>Write the Client and Server</h3><p>All code in this article is available at GitHub in my <a href="https://github.com/youngkin/gohttps">gohttps</a> repository.</p><p>We’ll write both a simple server that does no validation against a client’s certificate and a more advanced server that is capable of a variety of options when validating a client’s certificate. Finally, we’ll develop a client that can talk to both servers.</p><p>Before moving on, we need to briefly discuss how HTTPS is implemented. HTTPS traffic is encrypted by the TLS layer. TLS is the successor to SSL and works on top of TCP/IP. It does a number of things including:</p><ul><li>Negotiates the TLS session. This involves negotiating the version of TLS and the encryption suite to be used.</li><li>Validates the server’s identity</li><li>If required, validates the client’s identity</li><li>Handles all traffic encryption</li></ul><p>Go’s HTTP package includes a TLS configuration struct that is used to implement a client’s and server’s HTTPS communication expectations. This will be a focus in the following sub-sections.</p><p>TLS requires a reliable transport mechanism. TCP and UDP are the two choices, but UDP is not reliable. See <a href="https://security.stackexchange.com/questions/170833/why-does-tls-require-tcp">Why Does TLS Require TCP</a> for more discussion on this topic.</p><h3>A Simple Server</h3><p>See <a href="https://github.com/youngkin/gohttps/blob/master/simpleserver/server.go">GitHub</a> for the complete implementation of the simple server.</p><p>The simplest HTTPS interaction between a client and a server is one where the client validates the server’s credentials and all traffic is encrypted. The client only requires access to the certificate for the CA that signed the server’s certificate. The server neither knows nor cares about the client’s identity. This is a pretty common use case.</p><p>Here’s a breakdown of the implementation of a very simple HTTPS server. The first thing to do is to create and configure the http.Server struct:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4058c66448bec9dbf22932be5ffaa82/href">https://medium.com/media/a4058c66448bec9dbf22932be5ffaa82/href</a></iframe><p>Addr simply specifies the listening address for the server. ReadTimeout and WriteTimeout set the timeouts for reads and writes respectively. As the comment indicates, ReadTimeout is set to five minutes to allow time for the entry of the machine’s user’s password. OSx sometimes prompts for this when curl is used and the certificate is password protected. In this article, none of the certificates are password protected.</p><p>Strictly speaking, the timeout fields aren’t needed in a simple server such as this. That said, robust servers will include them. See <a href="https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts/">The complete guide to Go net/http timeouts</a> for more details.</p><p>In the context of this article, TLSConfig is the most interesting field in the Server struct. This is where all the TLS options are configured. In this case, only ServerName is required. ServerName must match the hostname in the server’s certificate.</p><p>The server needs a handler function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df044b381dad44225f1b8d26c6746aba/href">https://medium.com/media/df044b381dad44225f1b8d26c6746aba/href</a></iframe><p>There isn’t much to this handler function; it provides just the common “Hello, World!” response.</p><p>The final step is for the server to begin listening for requests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37cabb22233a5b140568264119695475/href">https://medium.com/media/37cabb22233a5b140568264119695475/href</a></iframe><p>Instead of the ListenAndServe() call in an HTTP server, an HTTPS server uses ListenAndServeTLS(). *serverCert and *srvKey are the server’s certificate and private key files respectively. The filenames containing these are passed in on the command line (more on that below). As you may recall, localhost.crt and localhost.key are the certificate and key files we created for the servers.</p><h3>A More Advanced Server</h3><p>See <a href="https://github.com/youngkin/gohttps/blob/master/advserver/server.go">GitHub</a> for the complete implementation of this more advanced server.</p><p>The primary difference between the simple server above and a more secure server is the addition of the capability to require, or require and validate, a client’s certificate.</p><p>As before, an http.Server struct is required:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cacf97e8d5134711b561611f60ef37d/href">https://medium.com/media/4cacf97e8d5134711b561611f60ef37d/href</a></iframe><p>Notice in this version the TLSConfig field is being configured by a function, getTLSConfig(). There’s a bit more to this TLSConfig than in the simple server case. Here’s the code for the function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4515e270e2fabeee7340171bec2df9c8/href">https://medium.com/media/4515e270e2fabeee7340171bec2df9c8/href</a></iframe><p>Let’s break this down by sections. First, let’s take a look at the function signature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91d245b746fc5b6958c95c69c4b51330/href">https://medium.com/media/91d245b746fc5b6958c95c69c4b51330/href</a></iframe><p>The arguments are as follows:</p><ol><li>host — This is the server’s hostname. It must match the name provided in the host’s certificate. In our case, this is the SAN.</li><li>caCertFile — This is the certificate file name for the CA that signed the client’s certificate, in this case ExampleCA.crt. The CA’s certificate is required in this server because we created an unknown CA, i.e., not a CA that’s normally configured in the OS (e.g., the KeyChain in OSx). So we need to add it here.</li><li>certopt — As can be seen, this is of type tls.ClientAuthType. There are five authorization types for authorizing/validating a client’s certificate:</li></ol><ul><li>tls.NoClientCert — A client certificate will not be requested and is not required. This is the default value.</li><li>tls.RequestClientCert — A client certificate will be requested, but it is not required and it won’t be validated.</li><li>tls.RequireAnyClientCert — A client certificate is required, but any valid client certificate is acceptable. It will not be validated against the CA’s certificate.</li><li>tls.VerifyClientCertIfGiven — A client certificate will not be requested, but if present, it will be validated against the CA’s certificate.</li><li>tls.RequireAndVerifyClientCert — A client certificate will be required and will be validated against the CA’s certificate.</li></ul><p>Now that we know what the function’s arguments are, let’s take a look at the function body:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ff0a2dd5d4e63c75f83e0c929532e98/href">https://medium.com/media/3ff0a2dd5d4e63c75f83e0c929532e98/href</a></iframe><ul><li>Line 3 — We define an x509.CertPool. This is a pool of certificates that will be used below. It will contain the certificate of the CA that signed the client’s certificate.</li><li>Line 4 — We check the value of the certOp. Any value above tls.RequestClientCert will require clients to provide a certificate.</li><li>Lines 5–8 — In order to validate client certificates a CA certificate, needs to be loaded into the caCertPool. These lines read the CA certificate file and handle any errors.</li><li>Lines 9 -10 — We create a new x509.CertPool and add the CA’s certificate to the pool.</li><li>Line 15 — The ClientAuth field is used to specify the level of client certificate authorization and validation that’s required. The values and definitions were given above in the discussion about certOpt.</li><li>Line 16 — The ClientCAs field is used to specify the CAs that will be used to validate client certificates. Its value is set from the caCertPool that was created on lines 9 and 10. The GoDoc for this field contains the following: “ClientCAs defines the set of root certificate authorities that servers use if required to verify a client certificate by the policy in ClientAuth.”</li><li>Line 17 — MinVersion sets the minimum TLS version to accept when negotiating versions with the client. TLS versions below 1.2 are considered insecure. See <a href="https://www.rfc-editor.org/rfc/rfc7525.txt">RFC 7525</a> for details.</li></ul><h3>Create the Client</h3><p>See <a href="https://github.com/youngkin/gohttps/blob/master/client/client.go">GitHub</a> for the complete implementation of this client.</p><p>As stated earlier, this client can successfully communicate with either the simple or advanced server. Let’s take a look at the significant code.</p><p>The first thing to do is to configure the client’s certificate and key, if present.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb6ff336fd0137aefdd22e65f5832af5/href">https://medium.com/media/eb6ff336fd0137aefdd22e65f5832af5/href</a></iframe><p>If provided, the code will create an x509 keypair from the client’s certificate and private key. This keypair will be used when negotiating the TLS connection, and for encrypting and decrypting communications between the client and server.</p><p>Next, as with the advanced server, we’ll create the certificate pool that will contain the certificate of the CA that signed, in this case, the server’s certificate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9d9ebae102097c116d8858605633f2c/href">https://medium.com/media/e9d9ebae102097c116d8858605633f2c/href</a></iframe><p>Then we create an http.Transport with the client’s certificate/keypair and the certificate pool containing the CA. This http.Transport will be used to configure the http.Client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe333ad2c9b44eb4a37f72614ab491d6/href">https://medium.com/media/fe333ad2c9b44eb4a37f72614ab491d6/href</a></iframe><p>http.Transport contains a tls.Config. As with the servers, the Certificates field is populated with the client’s certificate. There is a new field here, the RootCAs field. The GoDoc describes this field as follows: “RootCAs defines the set of root certificate authorities that clients use when verifying server certificates. If RootCAs is nil, TLS uses the host’s root CA set.”</p><p>This is everything that needs to be done to prepare the client to interact with an HTTPS server. The remaining code prepares and sends the request and processes the response.</p><h3>Putting It All Together</h3><p>If you’ve cloned or forked the <a href="https://github.com/youngkin/gohttps">gohttps</a> repository, you’ll notice that it has the following directory structure:</p><pre>gohttps+<br>       |<br>       +- advserver<br>       +- client<br>       +- simpleserver</pre><p>The source files for the client and each of the servers are in their respective directories. The programs can be built and run from these directories.</p><p>The certificates and keys referenced in the command lines below match the names of the ones generated in the <strong>Create Certificates and Keys</strong> section above.</p><h3>Start Server</h3><h4>Simple server command line (no client validation)</h4><pre>./simpleserver -host &quot;localhost&quot; -srvcert &quot;/path/to/localhost.crt&quot; -srvkey &quot;/path/to/localhost.key&quot;</pre><h4>Advanced server command line with full client certificate validation (-certopt 4).</h4><pre>./advserver -host &quot;localhost&quot; -srvcert &quot;/path/to/localhost.crt&quot; -cacert &quot;/path/to/ExampleCA.crt&quot; -srvkey &quot;/path/to/localhost.key&quot; -port 443 -certopt 4</pre><h3>Run the Client</h3><h4>Using curl</h4><p>curl request with no client certificate validation:</p><pre>curl -vi -d &quot;World&quot; --cacert /path/to/ExampleCA.crt <a href="https://localhost/">https://localhost</a></pre><p>curl request with full client certificate validation:</p><pre>curl -d &quot;World&quot; -vi --cert /path/to/client.crt  --key /path/to/client.key --cacert ./out/ExampleCA.crt <a href="https://localhost/">https://localhost</a></pre><h4>Using the client program</h4><p>Command line for full client certificate validation by the server:</p><pre>./client -clientcert &quot;/path/to/client.crt&quot; -clientkey &quot;/path/to/client.key&quot; -cacert &quot;/path/to/ExampleCA.crt&quot;</pre><p>Command line for no client certificate validation by the server:</p><pre>./client -cacert &quot;/path/to/ExampleCA.crt&quot;</pre><p>As noted in the section on creating certificates, above, if the client and server certificates aren’t created with the --domain flag, you may see the following error:</p><pre>Get &quot;https://localhost&quot;: x509: certificate relies on legacy Common Name field, use SANs or temporarily enable Common Name matching with GODEBUG=x509ignoreCN=0</pre><p>Prefixing the previous commands with GODEBUG=x509ignoreCN=0 will resolve the error. See the section on creating certificates for more details on how to avoid this problem.</p><h3>Conclusion</h3><p>Thanks for following along. We covered a lot in this article, including:</p><ul><li>If you had no background in PKI and certificates hopefully you learned enough to get you started on a journey to learn more about the subject.</li><li>A brief description of the different software tools available to work with certificates and keys. For this article we used certstrap.</li><li>How to use certstrap to create a CA as well as client and server certificate signing requests, certificates, and keys</li><li>How to write a simple and a more advanced HTTPS server in Go, covering the specifics in detail</li><li>How to write an HTTPS client in Go, again covering the specifics in detail</li><li>Running the server programs and accessing the running processes using both curl and the client program</li></ul><p>Feel free to use the code in the <a href="https://github.com/youngkin/gohttps">gohttps repository</a> for your own learning, experimentation, or as the basis to create your own clients and servers.</p><h3>References</h3><ul><li><a href="https://github.com/jcbsmpsn/golang-https-example">The TLS Connection Options</a> GitHub project is a good resource to quickly create working HTTPS clients and servers. It was my primary source for information about this topic when I was first getting started in creating HTTPS clients and servers. It also covers solutions to some common problems.</li><li><a href="https://bbengfort.github.io/programmer/2017/03/03/secure-grpc.html">Secure gRPC with TLS/SSL</a> — Although geared to gRPC, the basic TLS underpinnings are the same as with HTTPS. This article filled in some gaps about how to configure TLS in Go.</li><li><a href="https://www.smashingmagazine.com/2017/06/guide-switching-http-https/">The Complete Guide To Switching From HTTP To HTTPS</a> provides a detailed, practical, discussion about almost all aspects of the technology behind HTTPS, how to request certificates, and how to configure various web servers to support HTTPS. It’s worth at least a quick perusal to see if there’s anything of interest.</li><li><a href="https://en.wikipedia.org/wiki/Public_key_infrastructure">Public Key Infrastructure(PKI)</a> is a mix of technology and trusted organizations that provide the underpinnings of secure communication.</li><li><a href="https://en.wikipedia.org/wiki/Transport_Layer_Security">TLS</a> is an encryption protocol used to secure communications over the Internet.</li><li><a href="https://en.wikipedia.org/wiki/HTTPS">HTTPS</a> is a secure implementation of the HTTP protocol.</li><li><a href="https://jamielinux.com/docs/openssl-certificate-authority/index.html">OpenSSL Certificate Authority</a> is a good resource about creating CAs and certificates using openssl.</li><li><a href="https://linuxize.com/post/creating-a-self-signed-ssl-certificate/">Creating a Self-Signed SSL Certificate</a> is a good resource for creating self-signed certificates. These weren’t used in this article, but it’s good to know that it’s possible to do this.</li><li><a href="https://github.com/square/certstrap">Certstrap GitHub repo</a></li><li><a href="https://github.com/OpenVPN/easy-rsa">Easy-RSA GitHub repo</a></li><li><a href="https://geekflare.com/openssl-commands-certificates/">21 OpenSSL Examples to Help You in Real-World</a> is a good reference containing commonly used openssl commands.</li><li><a href="https://www.ssllabs.com/ssltest/index.html">QualSys SSL Server Test</a> is a web page you can use to test HTTPS access to an HTTPS server and receive an evaluation of how well it implements best practices.</li><li><a href="https://prod.idrix.eu/secure/">Idrix</a> has a nice service to test SSL certificates. For example:</li></ul><p>curl -vi –cert ./ClientCert.crt –key ./ClientCert.key <a href="https://prod.idrix.eu/secure/">https://prod.idrix.eu/secure/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa970ba36a13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/create-secure-clients-and-servers-in-golang-using-https-aa970ba36a13">Create Secure Clients and Servers in Golang Using HTTPS</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Free Blog Site Using GitHub Pages and Hugo]]></title>
            <link>https://medium.com/@RichYoungkin/create-a-free-blog-site-using-github-pages-and-hugo-1f037609b670?source=rss-80d16197df23------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f037609b670</guid>
            <category><![CDATA[hugo]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[blogging]]></category>
            <dc:creator><![CDATA[Richard Youngkin]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 21:03:09 GMT</pubDate>
            <atom:updated>2020-09-01T21:33:34.926Z</atom:updated>
            <content:encoded><![CDATA[<h4>Want to create your own blog but don’t want to get tied into any of the big hosted solutions?</h4><figure><img alt="GitHub Pages" src="https://cdn-images-1.medium.com/max/1024/1*UWhWqdSRVdfF6WWxUg6oYA.jpeg" /></figure><h3>Overview</h3><blockquote>Prerequisites:<br>1. A basic knowledge of git and GitHub.<br>2. Git version 2.24.3 or higher<br>3. Mac development machine — Windows and Linux are also supported. Much of what’s described here is applicable to both of these. But the exact steps I followed were performed on a Mac.<br>4. For significant customizations beyond what’s available natively in Hugo and the chosen Hugo theme, a basic understanding of HTML and CSS will be required. More information on customizations can be found in the <a href="http://localhost:1313/post/createafreeblogsite/#appendix">Appendix</a> below</blockquote><p>This article is a fairly detailed tutorial on how to create a full featured website/blog using Hugo and GitHub Pages. If you just want a quick overview of how to use Hugo I recommend going to the <a href="https://gohugo.io/getting-started/quick-start/">Hugo Quickstart page</a>. If you want a quickstart on setting up a Hugo/GitHub Pages site I recommend going to the <a href="https://gohugo.io/hosting-and-deployment/hosting-on-github/">Hugo GitHub Pages quickstart page</a>.</p><p>At its core GitHub Pages is a combination of a GitHub repository and a published web site. One consequence of this is that any commit to the master branch of the repository is immediately published. One way to create a GitHub Pages website is to also create an associated “development” GitHub repository. This is what is described here.</p><p>Hugo is an Open Source static website generator. It is quite powerful and the websites that can be created with Hugo can be quite sophisticated. Hugo is the base engine used to interpret how to create a website based on a predefined template. Hugo calls these templates themes. “Skin” is another word for theme. A theme is a combination of HTML and CSS. The HTML is used for site layout. CSS is used to define colors, fonts, font size, and other non-layout related attributes that define how the website looks. This combination is quite powerful. The website’s page definitions themselves, i.e., the website’s content, are defined using standard Markdown syntax.</p><p>Hugo also comes with an HTML server that can be used during development to provide immediate feedback on any changes that are made to web pages. Hugo can be used in 2 ways:</p><ol><li>Development mode — In this mode Hugo is using its HTML server to render pages as they are being modified during development. Running the server during development provides immediate feedback when changes are made to the content.</li><li>Build mode — Hugo will also generate a complete static website based on a theme’s layout, CSS, and the markdown files that define the content. The output of this mode is what will be published.</li></ol><p>The Hugo themes as well as the website’s page definitions are stored in what I above called the “development” repository. This is the primary authoring space. The Hugo web server operates against this repository. Through the magic of Git Submodules, the final set of committed changes to the master branch in the development repository are immediately made available in the GitHub Pages repository.</p><blockquote>Brief segue on <a href="https://github.blog/2016-02-01-working-with-submodules/">Git Submodules</a>:</blockquote><blockquote>Git Submodules are a way of including one, <strong>hosted</strong>, GitHub repository in another, <strong>hosting</strong>, repository. The entire content of the hosted repository is available in the hosting repository as if it was just a normal subdirectory in the hosting repository. Changes to the hosted repository can be made in the context of the hosting repository. Committing any such changes are immediately available in the hosted repository.</blockquote><p>In the context of Submodules, the GitHub Pages repository is the <strong>hosted</strong> repository. It contains the published content of the website. In contrast, the repository containing the Hugo theme(s) and the development versions of the content is the <strong>hosting</strong> repository. When the website content is ready for publishing Hugo is used to generate the static website. Hugo generates the content into the submodule associated with the, <strong>hosted</strong>, GitHub Pages repository. When ready, the changes are committed in the <strong>hosting</strong> repository and they become immediately available, and thereby published, in the GitHub Pages repository.</p><h3>Initial GitHub setup</h3><p>The two repositories, the GitHub Pages repository and the hosting development repository, need to be created. There are 2 options for the GitHub Pages repository:</p><ol><li>Personal or Organizational</li><li>Project</li></ol><p>See the <a href="https://help.github.com/articles/user-organization-and-project-pages/#user--organization-pages">GitHub Pages help documentation</a> for more details about the differences. This article describes how to create a Personal GitHub Pages repository.</p><p>Creating the GitHub Pages repository is fairly straightforward, but there is one very important restriction on its name. The repository’s name must be of the form &lt;github_username&gt;.github.io. For example, smith.github.io where smith is the associated user’s account name. This will be the URL of the website. So the GitHub pages repository is just a normal GitHub repository, just with a very specific name. We’ll use this repository name, smith.github.io in the rest of the article when referring to the GitHub Pages repository. See the <a href="https://pages.github.com/">GitHub Pages quickstart guide</a> if you need more details on how to create a repository.</p><p>The second step is to create the repository where the website development/authoring will take place. This is just a normal GitHub repository. For the purposes of this article, we’ll use myblog.dev.repo for the name of the development repository. See the <a href="https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-new-repository">GitHub documentation</a> if you need more details about how to create a repository.</p><h3>Install Hugo</h3><p>There are a number of ways to install Hugo:</p><ul><li>There are binary releases available on the <a href="https://github.com/gohugoio/hugo/releases">Hugo downloads page</a>.</li><li>On a Mac using Homebrew is the simplest, brew install hugo.</li><li>On Linux, with Homebrew installed, brew install hugo.</li><li>There are a couple of ways to install on Windows using Chocolatey:</li><li>choco install hugo[-extended] -confirm</li><li>scoop install hugo[-extended]</li></ul><p>Docker images are also available. For more details on installing Hugo see the <a href="https://gohugo.io/getting-started/installing/">Hugo documentation</a>.</p><h3>Create a basic site</h3><h4>Initialize the new site</h4><p>The first thing to do is to clone the development/authoring repository on to your local machine:</p><pre>git clone git@github.com:smith/myblog.dev.repo.git</pre><p>With the GitHub repositories setup and Hugo installed it’s time to initialize the website. Hugo provides this capability through the hugo command line:</p><ol><li>Change directories into the root of the myblog.dev.repo repository</li><li>Run hugo new site .</li><li>hugo new site is telling Hugo to create a new site. The final parameter in the command, the ., is telling Hugo which directory to create the new site. In this case we’re going to create it in our development/authoring repository, myblog.dev.repo.</li></ol><p>hugo new site &lt;dirname&gt; creates the following directory structure:</p><pre>site_root<br>  |--layout<br>  |--content<br>  |--static<br>  |--data<br>  |--themes<br>  |--config.toml<br>  +--archetypes</pre><p>The directories and files that we’re interested in for this article are:</p><ul><li>content - this is where content under development is located, i.e., the various markdown files for a site’s pages.</li><li>static - content that doesn’t change, such as images</li><li>themes - Where the site’s theme(s) are located</li><li>config.toml - The basic configuration for the site, e.g., the site’s name</li><li>archetypes - Template(s) used by the hugo new &lt;contentdir/contentfile.md&gt; command to create new content markdown files</li></ul><h4>Pick and install the site’s theme</h4><p>The next step is to choose a theme to use. See the <a href="https://themes.gohugo.io/">Hugo themes page</a> and select the one that looks best to you. The Hugo <a href="https://themes.gohugo.io/gohugo-theme-ananke/">Ananke theme</a> is a popular one. I chose the <a href="https://themes.gohugo.io/hugo-theme-cleanwhite/">Clean White theme</a>. Once you’ve picked a theme you need to add it to the development/authoring repo. Like with the GitHub Pages repo, this is accomplished via a git submodule:</p><pre>git submodule add &lt;theme-github-url&gt; &lt;target-directory&gt;</pre><p>I chose a customized version of the Clean White theme:</p><pre>git submodule add git@github.com:youngkin/hugo-theme-cleanwhite-rsy.git themes/hugo-theme-cleanwhite-rsy</pre><p>The &lt;target-directory&gt; should be a subdirectory of themes. themes is where Hugo expects loaded themes to be located.</p><blockquote>I’ll discuss my reasons for customizing the Clean White theme, as well as describe what I did, later in this article.</blockquote><p>Some basic customization of a Hugo generated website is specified in the config.toml file. For now we’ll just tell Hugo to use our chosen theme.</p><pre>echo &#39;theme = &quot;&lt;theme-name&gt;&quot;&#39; &gt;&gt; config.toml</pre><p>In my case I used</p><pre>echo &#39;theme = &quot;hugo-theme-cleanwhite-rsy&quot;&#39; &gt;&gt; config.toml</pre><p>The theme name is the name of the directory where you placed the theme.</p><h4>Test the new site locally</h4><p>Now it’s time to create some content and test everything we’ve done so far. The first step is to create some content:</p><pre>hugo new post/testpage.md</pre><p>The new page will be located at content/post/testpage.md, post being the parent directory given in the previous command. This command places all content in the content directory. content is one of the directories Hugo uses as the source of content when generating the static web site. The file will look something like this:</p><pre>---<br>title: &quot;Testpage&quot;<br>date: 2020-08-27T13:43:09-06:00<br>draft: true<br>---</pre><p>You can inspect the generated file. The generated content comes from the archetypes/default.md file which is the template used for all new content. The content between the --- lines is “front matter” for the page. Text after the 2nd --- line is the body of the web page.</p><blockquote>“Front matter” is the Hugo term for the information at the top of the page used to create a page’s rendered title as well as some other metadata that is placed in the associated HTML file’s &lt;meta&gt; tags in the page’s head section. Don’t worry too much if you don’t understand all this.</blockquote><p>The next step is to test the installation by starting the Hugo web server and navigating to the development site:</p><pre>hugo server -D</pre><p>Near the bottom of the logged output you’ll see a line like this:</p><pre>Web Server is available at http://localhost:1313/ (bind address 127.0.0.1)</pre><p>Copy the URL into a browser and you should see the home page of the new site. Depending on the theme chosen, you should see something like this:</p><figure><img alt="My new Hugo site" src="https://cdn-images-1.medium.com/max/800/1*3aRkymyNmub2mVneD42BDA.jpeg" /><figcaption>My new Hugo Site</figcaption></figure><h3>Authoring a site</h3><p>Now we’re ready to start creating the actual site that we want to publish. The first thing you might want to do is delete the content/post/testpage.md file created previously. This was created just to test the installation and is no longer needed.</p><h3>Configuration</h3><p>As mentioned above, the basic configuration for a Hugo website is specified in the config.toml file. Hugo’s <a href="https://gohugo.io/getting-started/configuration/">Getting Started documentation</a> covers configuration in detail. The configuration for this blog is a basic, but functional, configuration. It looks like this (<em>remember, </em><em>smith is our fictional GitHub account name, you’ll need to replace it with your own account name</em>):</p><pre>baseurl = &quot;https://smith.github.io&quot;<br>title = &quot;Rich Youngkin&quot;<br>theme = &quot;hugo-theme-cleanwhite-rsy&quot;<br>languageCode = &quot;en-us&quot;<br>paginate = 5000 #frontpage pagination</pre><pre>[markup]<br>  [markup.goldmark]<br>    [markup.goldmark.renderer]<br>      unsafe = true</pre><pre>[params]<br>  header_image = &quot;images/main_go_wideandtall_darklayer.jpeg&quot;<br>  title = &quot;Software Engineering&quot;<br>  slogan = &quot;$ grep -rni \&quot;The how&#39;s and why&#39;s\&quot; .&quot;<br>  SEOTitle = &quot;Rich Youngkin Blog&quot;<br>  keyword = &quot;Rich, Youngkin, Raspberry, Pi, Docker, Kubernetes, Go, Golang, Microservice&quot;<br> <br>  # Sidebar settings<br>  sidebar_about_description = &quot;Father, Husband, Skier, Cyclist, and, oh yeah, Software Developer&quot;<br>  sidebar_avatar = &quot;images/MeAtJackson.jpeg&quot;<br>  about_me = true</pre><pre>  featured_tags = true <br>  featured_condition_size = 2 # How many posts have to have a given tag to be featured (greater-than)</pre><pre>  image_404 = &quot;images/404-bg.jpg&quot;<br>  title_404 = &quot;We couldn&#39;t find what you were looking for...&quot;</pre><pre>  omit_categories = false</pre><pre>  [[params.addtional_menus]]<br>  title =  &quot;ABOUT&quot;<br>  href =  &quot;/top/about/&quot;</pre><pre>  [params.social]<br>  rss            = true<br>  email          = &quot;rich.youngkin@gmail.com&quot;<br>  linkedin       = &quot;https://www.linkedin.com/in/richard-youngkin-0749763&quot;<br>  github         = &quot;https://github.com/youngkin&quot;<br>  medium         = &quot;https://medium.com/@RichYoungkin&quot;<br>  stackoverflow  = &quot;https://stackoverflow.com/users/2646870/rich&quot;<br>  reddit         = &quot;https://www.reddit.com/user/elevation5280&quot;</pre><p>Taken line-by-line, here’s what each one means:</p><ul><li>baseurl - This is the URL of the published web site. For a GitHub Pages site it must be of the form https://&lt;your-github-id-here&gt;.github.io, e.g., <a href="https://smith.github.io./">https://smith.github.io.</a></li><li>title - This is the text displayed in the top left, header, area of every page on the site. It is a button control that will take you to the home page. Typically it’s your name.</li><li>theme - The theme used by the site</li><li>language - The <a href="https://en.wikipedia.org/wiki/IETF_language_tag">IETF language tag</a> specifying the primary language of the website. The language code, e.g., en, can have a suffix specifying an optional country code or region to subdivide the language into various dialects. en-us means United States English. en-gb means Great Britian English.</li><li>paginate - how many blog entry summaries to display on the home page</li><li>[markup] - this is a section that specifies the Markup/down syntax used. It’s optional. The Goldmark renderer is used by default. Blackfriday was the previous renderer and can still be used if specified. Goldmark has more capability than Blackfriday, but by default it won’t render HTML tags due to security concerns. I wanted to use HTML tags in my pages, primarily for image scaling and placement, as well as customizing text rendering. I had originally swapped out Goldmark for Blackfriday but later decided that I might like the extra functionality provided by Goldmark. To get the HTML tag support I needed, I had to add this [markup] section and set unsafe = true. See the <a href="https://gohugo.io/getting-started/configuration-markup">Hugo Configure Markup document</a> for more details.</li><li>[params] - These are the basic parameter settings available</li><li>header_image - the background image to use as the default in the headers of all pages. It is the only image that will be used for the home and about pages</li><li>title - This is the text used in the title, or banner, displayed at the top of every web page.</li><li>slogan - This is a subtitle displayed just below the title in the header of all web pages</li><li>SEOTitle &amp; keyword - These have something to do with search engine optimization. I included them in the hope that this would make my site more visible. More <a href="https://moonbooth.com/hugo/seo/">information can be found in this tutorial</a>.</li><li>sidebar_about_description, sidebar_avatar, &amp; about_me - The sidebar contains a concise “about me” biography. You can use the description to provide a short bio and the avatar to provide an image. about_me controls whether the sidebar is shown.</li><li>featured_tags &amp; featured_condition_size - These are used to specify whether you want to display tags used to describe pages to show up in a tag cloud on each page. feature_condition_size specifies the minimum number of articles that must have a given tag before that tag shows up in the tag cloud. It is important to note that tags will only be displayed when feature_condition_size + 1 articles with a given tag exist.</li><li>image_404 &amp; title_404 - These specify how a 404 Not Found page looks. One is the image, the other is the textual title.</li><li>omit_categories - Categories are like a higher level tag. For example, New Mexico, Colorado, Utah, Wyoming, Idaho, and Montana might all be tags for articles pertaining to those U.S. states. There might be a category “Best Ski Areas in the World” that could be used to group those tags into a higher level grouping. Defined Categories can be included in the navigation bar at the top of each page. omit_categories controls whether categories will be displayed in the top navigation bar.</li><li>[[params.additional_menus]] - This allows the specification of additional menu items to be put in the top navigation bar, for example an “About” page.</li><li>[params.social] - This entire sub-section is used to put badges associated with different social media sites on the Hugo generated site. There are other social media sites available such as twitter and facebook.</li></ul><h3>Archetypes</h3><p>Archetypes are templates used by Hugo when new web pages are created via the hugo new &lt;some-post-file&gt; command. They are useful because there is a “front matter” section at the top of each page describing some basic characteristics like the page title, description, and date. Without archetypes this “front matter” would have to be manually typed or copied on each new web page. While Hugo installs a default archetype at archetypes/default.md, you’ll probably want to create your own. I have a file located at archetypes/post.md. The name post.md is meaningful to Hugo. It is the archetype Hugo will use, if present, when generating posts. There are other archetype file names and locations that are meaningful to Hugo. You can find more detail about archetypes at the <a href="https://gohugo.io/content-management/archetypes/">Hugo Archetypes</a> page.</p><p>My archetypes/post.md file looks like this:</p><pre>---<br>title: &quot;{{ replace .Name &quot;-&quot; &quot; &quot; | title }}&quot;<br>#description: &lt;descriptive text here&gt;<br>date: {{ .Date }}<br>draft: true<br>toc: false<br>image: &quot;&quot;<br>tags: []<br>categories: []<br>---</pre><pre># Descriptive text here...<br>&lt;!--more--&gt;</pre><p>Here’s what each line means:</p><ul><li>--- - these lines delineate the “front matter” section of the page</li><li>title: &quot;{{ replace .Name &quot;-&quot; &quot; &quot; | title }}&quot; - specifies that the page’s title will be generated from the file name after replacing dashes (&#39;-&#39;) with spaces. This is a quick, handy, way to generate titles automatically. For example, My-New-Post.md becomes “My New Post” in the page’s title.</li><li>description - specifies text to be used in an article’s summary on the home page. This text will not be displayed in the article. It is related to the # Descriptive text here... line a little lower in the file.</li><li>date - replaced with the date the post was created. The generated date can be changed if you want to modify it, for example after updating the page. There are more sophisticated things you can do with dates, such as published date, last modified date, expiration date, etc. Those all have special meanings. See the <a href="https://gohugo.io/getting-started/configuration/#configure-dates">Hugo documentation</a> for more details.</li><li>draft - specifies whether a page is in draft or publish state. Pages in draft state can be seen when viewing the site running on the Hugo web server, but they will not be visible from a published web site such as GitHub Pages.</li><li>toc - If true, this will create a table of contents at the top of the article. This is a customization. See the appendix, comments section, below for details.</li><li>image - specifies the image to display at the top of the page. If not specified, the header_image in config.toml will be used.</li><li>tags - specifies a comma separated list of low level subject groupings. Taking my example from above, U.S. states might be an appropriate subject grouping for pages pertaining to U.S. states. For example, tags: [&quot;Colorado&quot;, &quot;Utah&quot;, ...].</li><li>categories - specifies a specifies a comma separated list of high level subject groupings. Again, taking my example from above, some U.S. states can be put in the category of “Best Ski Areas in the World”.</li><li># Descriptive text here... &amp; &lt;!--more--&gt; - These lines are used as an alternative to the description line in the “front matter” section. This can be used if the amount of descriptive text desired is more than can be comfortably put in the description line. &lt;!--more..&gt; is used to indicate the end of this type of descriptive text. Unlike description above, this text does appear in the article. An alternative to both the description line and these lines is to not specify either. In this case the first 70 words of the article will be used in the article summary.</li></ul><h3>Writing</h3><p>Now that we have our repositories setup, Hugo installed, our initialized Hugo development repository, and a basic understanding of Hugo website and page configuration, we can start authoring content. All content is written using Markup syntax. See the <a href="https://www.markdownguide.org/tools/hugo/">Hugo Markdown Guide</a> for more information and syntax details. As noted in the Configuration section above, using the Goldmark unsafe option allows you to use standard HTML tags in the content if desired.</p><h3>Publishing content to GitHub Pages</h3><p>At some point you’re going to be ready to make your site live. To do this you’ll want to generate the static content to be published from the development content. This development content is generally found in the content and static directories that were created when the site was initialized. The output of the generation process is generally placed in the public directory, but this can be modified. For our purposes we’re just going to let Hugo take this default behavior.</p><h3>Linking the development repository to the GitHub Pages repository</h3><p><strong>This step only needs to be done once.</strong></p><p>Before you can publish to your GitHub Pages site, you need to link your development repository, myblog.dev.repo in our case, to your GitHub Pages repository. We’re using smith.github.io as the GitHub Pages repository name. To do the linking we’ll use Git Submodules as discussed previously. The command to use is:</p><pre>git submodule add -b master git@smith.github.io.git public</pre><p>The important parts of the command are:</p><ul><li>-b master - This links to the hosted repository’s master branch</li><li>public - This links the hosting, i.e., this repository’s public directory, with the hosted repository. So any changes in the public directory, when committed, will be pushed to the GitHub Pages repository, smith.github.io.git.</li></ul><p>To illustrate the linking of the development repository to the GitHub Pages repository do the following:</p><pre>git remote -v</pre><p>The output should look something like this:</p><pre>origin	https://github.com/smith/smith.github.io.git (fetch)<br>origin	https://github.com/smith/smith.github.io.git (push)</pre><h3>Publishing the site</h3><p>When you’re ready to publish the site you’ll need to generate the static content. This is done by running:</p><pre>./deploy.sh</pre><p>This file is a slightly modified version of the deploy.sh file described on the Hugo <a href="https://gohugo.io/hosting-and-deployment/hosting-on-github/">Hosting on GitHub</a> tutorial. The deploy.sh script looks like this:</p><pre>#!/bin/sh</pre><pre># If a command fails then the deploy stops<br>set -e</pre><pre>printf &quot;\033[0;32mDeploying updates to GitHub...\033[0m\n&quot;</pre><pre># Create commit message<br>msg=&quot;rebuilding site $(date)&quot;<br>if [ -n &quot;$*&quot; ]; then<br>	msg=&quot;$*&quot;<br>fi</pre><pre># Build the project.<br>echo &quot;&quot;<br>echo &quot;&quot;<br>echo &quot;Committing changes to $(pwd)&quot;<br>hugo -D</pre><pre># Go To Public folder<br>cd public</pre><pre># Add &#39;public&#39; (Github Pages repo) changes to git and commit/push.<br>echo &quot;&quot;<br>echo &quot;&quot;<br>echo &quot;Committing changes to $(pwd)&quot;<br>git add .<br>git commit -m &quot;$msg&quot;<br>git push origin master</pre><pre># Add this repos changes to git and commit/push. First &#39;cd&#39; out of public<br>cd ..<br>echo &quot;&quot;<br>echo &quot;&quot;<br>echo &quot;Committing changes to $(pwd)&quot;<br>git add .<br>git commit -m &quot;$msg&quot;<br>git push origin master</pre><p>deploy.sh does several things:</p><ol><li>It builds the static content via hugo -D</li><li>It stages everything in the project-root/public directory for commit via git add .</li><li>It commits everything in the project-root/public directory via git commit -m &quot;&lt;commit message&gt; (the “commit message” is generated by the script)</li><li>It pushes the changes to master via git push origin master</li><li>It stages everything in the project-root directory for commit via git add .</li><li>It commits everything in the project-root directory via git commit -m &quot;&lt;commit message&gt;</li><li>It pushes the changes to master via git push origin master</li></ol><blockquote><strong>CAUTION!!!!!</strong> Everything in public and the project root directories is staged for commit. This means that all additions or changes you made will be committed. This can be an issue if you have new temporary files that you have no intention of committing. If you don’t want this behavior you can modify the script to comment out the git add . commands.</blockquote><h3>The finished product</h3><p><a href="https://youngkin.github.io/post/createafreeblogsite/">This web site!</a> The source code is available on GitHub for:</p><ul><li><a href="https://github.com/youngkin/hugoblog">The blog source code</a></li><li><a href="https://github.com/youngkin/hugo-theme-cleanwhite-rsy">The modified Clean White theme</a></li><li><a href="https://github.com/youngkin/youngkin.github.io">The published GitHub Pages repo</a></li></ul><h3>References</h3><ul><li><a href="https://gohugo.io/getting-started/quick-start/">Hugo Quickstart page</a></li><li><a href="https://gohugo.io/hosting-and-deployment/hosting-on-github/">Hugo GitHub Pages quickstart page</a></li><li><a href="https://github.blog/2016-02-01-working-with-submodules/">Git Submodules</a></li><li><a href="https://help.github.com/articles/user-organization-and-project-pages/#user--organization-pages">GitHub Pages help documentation</a></li><li><a href="https://pages.github.com/">GitHub Pages quickstart guide</a></li><li><a href="https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-new-repository">GitHub documentation</a></li><li><a href="https://github.com/gohugoio/hugo/releases">Hugo downloads page</a></li><li><a href="https://gohugo.io/getting-started/installing/">Hugo installation documentation</a></li><li><a href="https://themes.gohugo.io/">Hugo themes page</a></li><li><a href="https://themes.gohugo.io/gohugo-theme-ananke/">Ananke theme page</a></li><li><a href="https://themes.gohugo.io/hugo-theme-cleanwhite/">Clean White theme page</a></li><li><a href="https://gohugo.io/getting-started/">Hugo’s Getting Started documentation</a></li><li><a href="https://en.wikipedia.org/wiki/IETF_language_tag">IETF language tag spec</a></li><li><a href="https://gohugo.io/getting-started/configuration-markup">Hugo Configure Markup document</a></li><li><a href="https://moonbooth.com/hugo/seo/">SEO tutorial</a></li><li><a href="https://gohugo.io/content-management/archetypes/">Hugo Archetypes</a></li><li><a href="https://gohugo.io/getting-started/configuration">Hugo Configuration</a></li><li><a href="https://www.markdownguide.org/tools/hugo/">Hugo Markdown Guide</a></li></ul><h3>Appendix</h3><p>This appendix describes some additional changes I made that you might also want to consider.</p><h3>Add Support for Comments</h3><p>Any good blog needs to support comments. My basic requirements for commenting were:</p><ol><li>Free — Blogs with comments are great, but I’m not willing to pay for it.</li><li>Hosted — I didn’t want to have to stand-up my own comments server</li></ol><p>Hugo does come with out-of-the-box support for <a href="https://disqus.com/">Disqus</a>. Disqus does have a <a href="https://disqus.com/pricing/">free option</a>, but it’s ad supported. I don’t like ads. So I did a <a href="https://talk.hyvor.com/blog/disqus-alternatives/"><em>little</em> research on free alternatives</a>. Sharp eyed readers will notice this article is published by <a href="https://talk.hyvor.com/">Hyvor</a>, one of the free alternatives. I also looked at using <a href="https://retifrav.github.io/blog/2019/04/19/github-comments-hugo/">GitHub comments</a>. I chose not to use GitHub comments due to the requirement that commenters have a GitHub account. Using GitHub comments also felt a bit clunky for sevearl reasons:</p><ol><li>The comments section of each article was a link to an associated GitHub issue. This link wasn’t always obvious</li><li>Following the link takes the commentor to GitHub, away from the blog. This felt disjointed.</li><li>The blog author has to create an associated GitHub issue for each blog page.</li></ol><p>So despite the potential for bias in the Hyvor article, it seemed to cover the bases so I went with Hyvor as my commenting platform. If you think you’d like to use GitHub for comments, <a href="https://retifrav.github.io/blog/2019/04/19/github-comments-hugo/">GitHub comments for a Hugo-based blog</a> describes how to accomplish this.</p><h4>Hyvor</h4><p>Using Hyvor as a commenting platform is straightforward:</p><ol><li>Get a <a href="https://talk.hyvor.com/docs/account">Hyvor account</a></li><li>Configure your Hyvor account</li><li><a href="https://talk.hyvor.com/docs/install">Add(Install) Hyvor to your blog</a></li><li><a href="https://talk.hyvor.com/docs/appearance">Customizing the appearance</a> and other aspects of how comments will be used</li></ol><p>Completing the first step is simply a matter of registering your account. Just fill in the details on the <a href="https://auth.hyvor.com/signup/">Sign Up For Hyvor</a> page.</p><p>The second step, configuring my Hyvor account, was a little less straightforward, at least for me. Once you’re logged into the Hyvor site you’ll be placed on your account page. On that page is a Website URL entry. This is where you put the top level URL for your blog (e.g., <a href="https://smith.github.io/">https://smith.github.io</a>). However from here, things are a bit more murky. You’ll need to go to your console to do more. To do that you click on the text “Hyvor Talk” at the bottom of the page:</p><figure><img alt="Hyvor Account Page" src="https://cdn-images-1.medium.com/max/420/1*g3ErX1a2DjRW999t6cjskw.jpeg" /><figcaption>Hyvor account page</figcaption></figure><p>This will take you to another page containing a “Go to Console” button.</p><figure><img alt="Navigate to console" src="https://cdn-images-1.medium.com/max/600/1*9KuTt0ZVAwxVQVDw3Q_WPQ.jpeg" /><figcaption>Navigate to console</figcaption></figure><p>Click on the button and your console will look something like this:</p><figure><img alt="Hyvor console" src="https://cdn-images-1.medium.com/max/700/1*xtgJNr-3-I3MdP2iV-lblA.jpeg" /><figcaption>Hyvor Console</figcaption></figure><p>Hyvor assigns the Website ID. You fill in the rest. I added an additional Website domain, localhost, so I could test on my local machine.</p><p>The third step involves adding Hyvor to your blog. To do this click on “Install” in the left-hand navigation section. Then click on the “Manual Install” option. After doing this you should see 2 steps described in the resulting page.</p><figure><img alt="Hyvor manual install" src="https://cdn-images-1.medium.com/max/900/1*BkGonKS1ZcWJH4j9C3tYLg.jpeg" /><figcaption>Hyvor Manual Install</figcaption></figure><p>You’ll need to “cut &amp; paste” the code from step one of this page into your theme’s layouts/partials/comments.html file <em>(You should be able to ignore step 2)</em>. When done it should look something like this:</p><pre>&lt;!-- disqus end --&gt;<br>&lt;div id=&quot;disqus-comment&quot;&gt;&lt;/div&gt;<br>{{ if .Site.Params.disqus_proxy }}<br>&lt;script src=&quot;{{ &quot;js/iDisqus.js&quot; | relURL }}&quot;&gt;&lt;/script&gt;<br>&lt;script&gt;<br>var disq = new iDisqus(&#39;disqus-comment&#39;, {<br>    forum: &#39;{{ .Site.DisqusShortname}}&#39;,<br>    api: &#39;{{ .Site.Params.disqus_proxy }}&#39;,<br>	site: &#39;{{ .Site.Params.disqus_site }}&#39;,<br>    mode: 1,<br>    timeout: 5000,<br>    init: true<br>});<br>&lt;/script&gt;<br>{{ else if .Site.DisqusShortname }}<br>{{ template &quot;_internal/disqus.html&quot; . }}<br>{{ else if .Site.Params.hyvor }}<br>&lt;div id=&quot;hyvor-talk-view&quot;&gt;&lt;/div&gt;<br>&lt;script type=&quot;text/javascript&quot;&gt;<br>    var HYVOR_TALK_WEBSITE = XXXXXXX; // DO NOT CHANGE THIS<br>    var HYVOR_TALK_CONFIG = {<br>        url: false,<br>        id: false<br>};<br>&lt;/script&gt;<br>{{ end }}</pre><p>Specifically note the {{ else if .Site.Params.hyvor }} block. Except for the value of HYVOR_TALK_WEBSITE, which should be your specific assigned value, this is the block you pasted into the comments.html file. It’s pasted just prior to the {{ end }} line. .Site.Params.hyvor refers to a parameter in your config.toml file in the [params] section, e.g.:</p><pre>[params]<br>  #header_image = &quot;images/MeAtJackson.jpeg&quot;<br>  header_image = &quot;images/main_go_wideandtall_darklayer.jpeg&quot;<br>  title = &quot;Software Engineering&quot;<br>  slogan = &quot;$ grep -rni \&quot;The how&#39;s and why&#39;s\&quot; .&quot;<br>  SEOTitle = &quot;Rich Youngkin Blog&quot;<br>  keyword = &quot;Rich, Youngkin, Raspberry, Pi, Docker, Kubernetes, Go, Golang, Microservice&quot;</pre><pre>  # Comments<br>  hyvor = true<br> <br>  # Sidebar settings</pre><p>The pertinent change is the block starting with # Comments. hyvor = true enables Hyvor commenting.</p><p>The bottom of each blog post will now look something like this:</p><figure><img alt="Comments section" src="https://cdn-images-1.medium.com/max/700/1*TwjQOCalMTCaCLMGAhNOqg.jpeg" /><figcaption>Comments Section</figcaption></figure><p>To get exactly this appearance do this from the Hyvor Console:</p><ol><li>To match the blog’s theme colors, click on the “Appearance” entry in the left-hand navigation section of your Hyvor Console. Then click on “Accent Color” and in the resulting color picker in the bottom left enter the hex color code #555555. Then click “Save”.</li><li>To remove the emoji reactions, click on the “Community” entry in the left-hand navigation section of your Hyvor Console. The second item in settings, just under “Comments Note”, is “Reactions”. Turn this off and click “Save”.</li></ol><h3>Optional Table of Contents</h3><p>I wanted to have the option to include a table of contents on selected articles. As mentioned above, I added a toc item in the archetypes/post.md file:</p><pre>---<br>title: &quot;{{ replace .Name &quot;-&quot; &quot; &quot; | title }}&quot;<br>#description: &lt;descriptive text here&gt;<br>date: {{ .Date }}<br>draft: true<br>toc: false<br>image: &quot;&quot;<br>tags: []<br>categories: []<br>---</pre><pre># Descriptive text here...<br>&lt;!--more--&gt;</pre><p>If toc is set to true then Hugo will generate a table of contents for the associated article. I changed the original themes/hugo-theme-cleanwhite/layouts/_default/single.html file <strong>FROM</strong>:</p><pre>&lt;!-- Post Content --&gt;<br>&lt;article&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;div class=&quot;row&quot;&gt;</pre><pre>            &lt;!-- Post Container --&gt;<br>            &lt;div class=&quot;<br>                col-lg-11 col-lg-offset-1<br>                col-md-10 col-md-offset-1<br>                post-container&quot;&gt;</pre><pre>                {{ if not (eq (.Param &quot;showtoc&quot;) false) }}<br>                &lt;header&gt;<br>                    &lt;h2&gt;TOC&lt;/h2&gt;<br>                &lt;/header&gt;<br>                {{.TableOfContents}}<br>                {{ end }}<br>                {{ .Content }}</pre><p><strong>TO:</strong></p><pre>&lt;!-- Post Content --&gt;<br>&lt;article&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;div class=&quot;row&quot;&gt;</pre><pre>            &lt;!-- Post Container --&gt;<br>            &lt;div class=&quot;<br>                col-lg-11 col-lg-offset-1<br>                col-md-10 col-md-offset-1<br>                post-container&quot;&gt;</pre><pre>                {{ if (.Params.toc) }}<br>                &lt;header&gt;<br>                    &lt;h2&gt;Contents&lt;/h2&gt;<br>                &lt;/header&gt;<br>                {{.TableOfContents}}<br>                {{ end }}<br>                {{ .Content }}</pre><p>Specifically the block starting with {{ if not (eq (.Param &quot;showtoc&quot;) false) }} ... was changed to the block starting with {{ if (.Params.toc) }} .... So instead of looking for the showtoc parameter in config.toml, .Params.toc directs the HTML template to look in the “front matter” at the top of an article for a toc entry.</p><h3>Theme Customizations</h3><p>I used the <a href="https://themes.gohugo.io/hugo-theme-cleanwhite/">Clean White theme</a>, but I wanted a different look for:</p><ul><li>Title and Description (looking for “green screen” feel)</li><li>Sidebar Tags and social networking “badges” — too dim, wanted to darken</li><li>Post summaries — these appear under each post Title on the home page. They’re a brief summary of the post. I wanted these to be slightly darker.</li><li>Wanted to change some fonts</li></ul><p>Here’s what I changed:</p><ul><li>I copied <a href="https://github.com/zhaohuabing/hugo-theme-cleanwhite">Clean White theme GitHub repository</a> to <a href="https://github.com/youngkin/hugo-theme-cleanwhite-rsy">my own copy</a></li><li>I modified themes/hugo-theme-cleanwhite-rsy/static/css/hux-blog.min.css</li><li><strong>Note:</strong> I “pretty printed” this file with the Atom css-clean package to make it easier to visualize in this article, but it needs to be unchanged in the blog source in order for the web site to render properly</li></ul><h4>Change the Blog Header</h4><p>I wanted to change the text fonts, font size, and color in the <strong>Navigation Bar</strong>, <strong>Blog Title</strong>, and the <strong>Blog Subtitle</strong>.</p><figure><img alt="Blog header" src="https://cdn-images-1.medium.com/max/1024/1*Woms_xYct6D7uuIgMw_JwQ.png" /><figcaption>My blog header</figcaption></figure><p>I changed the text color in the <strong>Blog Title</strong> to green by changing the color: #00FA9A element. Here’s the context for the changes:</p><pre>.intro-header .page-heading,<br>.intro-header .post-heading,<br>.intro-header .site-heading {<br>  padding : 85px 0 55px;<br>  color   : #00FA9A;<br>}</pre><p>I changed the text color in the <strong>Navigation Bar</strong> to green by changing the color: #00FA9A element. Here’s the context for the changes:</p><pre>.navbar-custom .navbar-brand {<br>    padding     : 20px;<br>    color       : #00FA9A;<br>    line-height : 20px;<br>  }</pre><pre>  ...</pre><pre>    .navbar-custom .nav li a {<br>    padding : 20px;<br>    color   : #00FA9A;<br>  }</pre><p>I changed the text rendering (font and font-color) for the <strong>Blog Subtitle</strong> (‘slogan’ in config.toml) by changing color: #FFD700,font-size: 25px, and adding font-family: Courier New, monospace;. Here’s the context for the changes.</p><pre>.intro-header .page-heading .subheading,<br>.intro-header .site-heading .subheading {<br>  display     : block;<br>  margin      : 10px 0 0;<br>  color       : #FFD700;<br>  font-family : -apple-system,<br>                &quot;Helvetica Neue&quot;,<br>                Arial,<br>                &quot;PingFang SC&quot;,<br>                &quot;Hiragino Sans GB&quot;,<br>                STHeiti,<br>                &quot;Microsoft YaHei&quot;,<br>                &quot;Microsoft JhengHei&quot;,<br>                &quot;Source Han Sans SC&quot;,<br>                &quot;Noto Sans CJK SC&quot;,<br>                &quot;Source Han Sans CN&quot;,<br>                &quot;Noto Sans SC&quot;,<br>                &quot;Source Han Sans TC&quot;,<br>                &quot;Noto Sans CJK TC&quot;,<br>                &quot;WenQuanYi Micro Hei&quot;,<br>                SimSun,<br>                sans-serif;<br>  font-family : Courier New,<br>                monospace;<br>  font-size   : 25px;<br>  font-weight : 300;<br>  line-height : 1.7;<br>  line-height : 1.1;<br>}</pre><h4>Change the Post Summaries</h4><figure><img alt="Blog summary section" src="https://cdn-images-1.medium.com/max/700/1*-JpW2bOBk5Eq7ibDXhKLjw.jpeg" /><figcaption>Blog Summary Section</figcaption></figure><p>The summary text and post date were a light gray. To improve the contrast I changed the .post-meta and .post-content-preview colors to #555555.</p><pre>.post-meta{<br>    font-family:Lora,&#39;Times New Roman&#39;,serif;<br>    color:#555555;<br>    font-size:16px;<br>    font-style:italic;<br>    margin-top:0}</pre><pre>...</pre><pre>.post-content-preview{<br>    font-size:13px;<br>    font-style:italic;<br>    color:#555555<br>    }</pre><h4>Change the Sidebar</h4><p>In the Sidebar I wanted to change the text and border color of the “FEATURED TAGS”, the text color of the short bio, and the background color of the social networking ‘badges’.</p><figure><img alt="My sidebar" src="https://cdn-images-1.medium.com/max/349/1*rW_wMRx74LnRLQ0gMFaWVw.png" /><figcaption>My Sidebar</figcaption></figure><p>The color of the “About Me” short bio and the social badges was too light for my tastes. I changed these colors to a darker gray by changing .sidebar-container {...} and .sidebar-container a {...} color elements to #555555. Here’s the context for these changes:</p><pre>.sidebar-container {<br>  color     : #555555;<br>  font-size : 14px;<br>}</pre><pre>.sidebar-container h5 {<br>  padding-bottom : 1em;<br>  color          : gray;<br>}</pre><pre>.sidebar-container h5 a {<br>  color           : gray!important;<br>  text-decoration : none;<br>}</pre><pre>.sidebar-container a {<br>  color : #555555!important;<br>}</pre><p>As above, the text and border color of the “Featured Tags” was too light for me. I changed this to a darker gray by changing the .sidebar-container .tags a {...} border-color to #555555 and the .tags a {... color: ... border:...} color and border elements to #FFD700 and 1px solid rgba(255,215,0,0.8) respectively. Here’s the context for these changes:</p><pre>.sidebar-container .tags a {<br>  border-color : #555555;<br>}</pre><pre>...</pre><pre>.tags a {<br>  display         : inline-block;<br>  margin          : 0 1px;<br>  margin-bottom   : 6px;<br>  padding         : 0 10px;<br>  color           : #FFD700;<br>  border          : 1px solid rgba(255,215,0,0.8);<br>  border-radius   : 999em;<br>  text-decoration : none;<br>  font-size       : 12px;<br>  line-height     : 24px;<br>}</pre><h3>Image manipulation</h3><p>I wanted to modify some of the images used in the site, primarily the background images used in the page headers. I used <a href="https://www.gimp.org/">GIMP</a> to manipulate the blog images. I mostly changed the following:</p><ul><li>Resized the images to fit within the page</li><li>Added a dark layer over the top of the images to increase contrast with the blog header elements (i.e., navigation bar, title, subtitle)</li><li>I mostly used #4d4d4d and #373737 as the colors, a mode of normal, and an Opacity of 80%</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f037609b670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install MySQL on a Raspberry Pi]]></title>
            <link>https://medium.com/better-programming/how-to-install-mysql-on-a-raspberry-pi-ad3f69b4a094?source=rss-80d16197df23------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad3f69b4a094</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Richard Youngkin]]></dc:creator>
            <pubDate>Wed, 29 Apr 2020 15:14:17 GMT</pubDate>
            <atom:updated>2020-04-29T15:15:18.459Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Install MariaDB on a Raspberry Pi</h3><h4>The MySQL alternative for a Raspberry Pi</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1XoFLM4-HGouxOLs9gw1A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jankolar?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kolar.io</a> on <a href="https://unsplash.com/s/photos/database-administrators?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This is the sixth and final article in the <a href="https://medium.com/better-programming/develop-and-deploy-kubernetes-applications-on-a-raspberry-pi-cluster-fbd4d97a904c">Develop and Deploy Kubernetes Applications on a Raspberry Pi Cluster</a> series. It marks the transition from a purely Raspberry Pi focus to software development more generally. With the installation of a database, we will have a full-featured platform that meets our requirements for application development and deployment.</p><p>This article covers how to install and configure <a href="https://mariadb.org/">MariaDB</a>, a feature-equivalent alternative to MySQL, on a Raspberry Pi. Installing is relatively straightforward. Configuring the database is somewhat more involved but still quite manageable.</p><h3>Overview</h3><p>Most significant applications depend on a database of some sort. As of 2019, <a href="http://highscalability.com/blog/2019/3/6/2019-database-trends-sql-vs-nosql-top-databases-single-vs-mu.html">Relational databases made up about 60% </a>of applications’ database platforms. Of those, MySQL is one of the most popular. MariaDB is also quite popular. MariaDB and MySQL do most everything other relational databases do. Like MySQL, MariaDB is relatively easy to use and free.</p><p>Why not just install MySQL? Well, it turns out that there isn’t a MySQL package available for installation on a Raspberry Pi using apt-get, which is the preferred way of installing and managing software on Debian and several other Linux distributions. At least I couldn’t find one.</p><p>MariaDB was created by the original developers of MySQL from a MySQL fork. <a href="https://hackr.io/blog/mariadb-vs-mysql">See this resource</a> for a discussion of the pros and cons of MySQL vs. MariaDB. Per the developers of MariaDB: “MariaDB versions function as a ‘drop-in replacement’ for the equivalent MySQL version.”</p><p>There is a <a href="https://mariadb.com/kb/en/mariadb-vs-mysql-compatibility/">compatibility guide available on the MariaDB website</a>.</p><h4>A short regression…</h4><p>The second article in this series, <a href="https://medium.com/better-programming/how-to-set-up-a-raspberry-pi-cluster-ff484a1c6be9">How to Set Up a Raspberry Pi Cluster</a>, describes the cluster topology I intended to set up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*JS7YYdyWznjjHIyc29cbCw.png" /><figcaption>My cluster topology — images courtesy of HiClipart, Comcast, BlackBox, and Cleanpng</figcaption></figure><p>If you’ve been following along with this series, you may have already set up your own Raspberry Pi cluster along similar lines. Throughout the rest of this article, I’ll refer back to this diagram.</p><h3>Install MariaDB</h3><p>You need to make a decision when installing MariaDB: Will you want to install the server or the client? Most likely you’ll want both on your cluster. For flexibility, plus troubleshooting support, I elected to install the client on all hosts in my cluster as well as on my MacBook Pro in the external network. As far as the server goes, I elected to put it on the kubemaster host (AKA Pi Router). I had several reasons for this:</p><ul><li>It’s a Raspberry Pi 4B+ vs. 3B+ for the rest. I reasoned that the more powerful machine would be the best place to install it.</li><li>I experimented with a MySQL (yes, MySQL) database located on my MacBook to see if that made a performance difference. It didn’t.</li><li>Perhaps the primary reason I had for installing MariaDB on kubemaster is that it’s accessible from both the cluster and external networks.</li></ul><p>Installation is simple. The MariaDB installation comes with both client and server components. To install:</p><pre>sudo apt-get install mariadb-server -y</pre><p>-y directs apt-get to automatically answer yes to all prompts. Leave it off if you want more control over the installation.</p><p>As stated above, this command will also install the MariaDB client. To login for the first time, you’ll have to use the root user. Access via the root user is protected, so you’ll have to use sudo:</p><pre>sudo mysql -uroot</pre><p>Having to use sudo isn’t optimal. We’ll see how to address this in the next section.</p><p>There is an option to improve the security of the basic installation performed above. This is accomplished using the mysql_secure_installation tool. You can use it to set an appropriate root password as well as optionally configure some other settings that can make the installation more secure. You run it as follows:</p><pre>sudo mysql_secure_installation</pre><p>Follow the prompts as appropriate for your requirements.</p><p>Installing the client software on other hosts in the network is straightforward. On a Mac, you can use <a href="https://brew.sh/">Homebrew</a>:</p><pre>brew install mysql-client</pre><p>On Raspberry Pi hosts, run:</p><pre>sudo apt-get install mysql-client</pre><p>Even if you follow all the steps above, you’ll still be pretty limited in what you can do, including logging in as root without using sudo. We’ll cover how to address that next.</p><h3>Configure MariaDB</h3><p>At this point, you have a running MariaDB server and the client software you need to administer and interact with it. Initially, only the root user is configured, and you have to use sudo to login. In addition, remote access isn’t enabled and will have to be configured.</p><h4>Complete setting up the root user</h4><p>This step will make it possible not to have to use sudo to log into MariaDB. Log in to MariaDB as we had to do in the previous section:</p><pre>sudo mysql -uroot<br>Welcome to the MariaDB monitor.  Commands end with ; or \g.<br>Your MariaDB connection id is 67<br>Server version: 10.3.22-MariaDB-0+deb10u1 Raspbian 10</pre><pre>...</pre><p>Next, we need to modify root&#39;s permissions:</p><pre>MariaDB [(none)]&gt; GRANT ALL PRIVILEGES on *.* <br>  TO &#39;root&#39;@&#39;%&#39; <br>  IDENTIFIED BY &#39;&lt;yourpasswordhere&gt;&#39;;<br>Query OK, 0 rows affected (0.001 sec)</pre><pre>MariaDB [(none)]&gt; FLUSH PRIVILEGES;<br>Query OK, 0 rows affected (0.001 sec)</pre><p>The first command configures root access from any machine in the network (that’s with &#39;root&#39;@&#39;%&#39; does). IDENTIFIED BY &#39;&lt;yourpasswordhere&gt;&#39; is used to set root&#39;s password (if you still need to do that). FLUSH PRIVILEGES makes the changes effective immediately.</p><p>To ensure this all worked, log out of the session and login again without using sudo:</p><pre>mysql -uroot -hlocalhost -p</pre><p>You should be prompted for a password. Enter root&#39;s password. If you’re logged in, go ahead and logout:</p><pre>quit;</pre><p>If you’re having trouble, revisit the above steps and make sure you did everything.</p><h4>Configure remote access</h4><p>If you’re planning on accessing the server from any remote hosts, or even the local host’s IP address, you’ll need to configure MariaDB to allow that. To accomplish this you’ll need to edit /etc/mysql/mariadb.conf.d/50-server.cnf (the actual file name may be different, but the location should be the same). This is the configuration file for MariaDB. The top few lines of the file should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2b44d64707663f342c8c91da90784f5/href">https://medium.com/media/a2b44d64707663f342c8c91da90784f5/href</a></iframe><p>Notice the last line above, the line specifying the bind-address. If this is not commented out, and it won’t be, then you’ll only be able to connect to MariaDB from localhost or 127.0.0.1. To allow connectivity from elsewhere in the network, like the other hosts in the cluster, you’ll need to comment that line out as shown above and restart the server:</p><pre>sudo systemctl restart mysql</pre><p>Restarting is required to reload the modified configuration.</p><p>You can verify this step succeeded by logging back into MariaDB but using the host’s non-local IP address. You can accomplish the same thing by logging on from a different host. My host’s address is 10.0.0.100:</p><pre>mysql -uroot -h10.0.0.100 -p&lt;yourpasswordhere&gt;</pre><p>If this doesn’t work, go back and recheck the steps above, including restarting MariaDB.</p><h4>Add another user and configure for remote access</h4><p>So now you should be able to log in as root from the local machine as well as from other hosts. Next, you’ll want to add a user for your application and set up the required access rights. In this case, we’re going to add the user app1 with a password of app1 (of course, you would never specify a password to match the user ID in the real world because that’s extremely insecure).</p><p>As root, log into the server (sorry, you have to use sudo for this):</p><pre>sudo mysql -h10.0.0.100 -uroot -p&lt;yourpasswordhere&gt;     <br>                                                       <br>Welcome to the MySQL monitor.  Commands end with ; or \g.<br>Your MySQL connection id is 180084<br>Server version: 5.5.5-10.3.17-MariaDB-0+deb10u1 Raspbian 10</pre><pre>... </pre><p>Type in the following commands:</p><pre>mysql&gt; use mysql;</pre><pre>mysql&gt; CREATE USER &#39;app1&#39;@&#39;%&#39;<br>  IDENTIFIED BY ‘app1’;</pre><pre>mysql&gt; GRANT ALL<br>  ON *.*<br>  TO &#39;app1&#39;@&#39;%&#39;<br>  WITH GRANT OPTION;</pre><pre>mysql&gt; FLUSH PRIVILEGES;</pre><p>use mysql; indicates we want to perform the following commands from the mysql database. This is the main system database, where things like user information are stored. CREATE USER &#39;app1&#39;@&#39;%&#39; obviously creates the user. As with root above, @ indicates which host the user will be allowed to log in from. Specifying the &#39;%&#39; wildcard indicates that the user app1 will be allowed to log in from any host. As above, IDENTIFIED BY specifies the password.</p><p>GRANT ALL specifies that this user will be able to do most any operation, including creating databases and tables, as well as granting permissions to others to do the same. This is also a bit of a security issue and not something you’d want to do in practice.</p><p>FLUSH PRIVILEGES reloads the privileges configuration.</p><p>As with root, you should now be able to log into the server as app from anywhere in the cluster.</p><p>That’s it, you’re all done! MariaDB is fully configured and ready to use.</p><h3>Summary</h3><p>In this article, we’ve installed and configured MariaDB. The next step is to use the cluster as an application deployment platform.</p><p>This marks the end of Raspberry Pi focus of the <a href="https://medium.com/better-programming/develop-and-deploy-kubernetes-applications-on-a-raspberry-pi-cluster-fbd4d97a904c">Develop and Deploy Kubernetes Applications on a Raspberry Pi Cluster</a> series. Follow-on articles will be more focused on an application. The goals for this application are:</p><ol><li>Be relatively simple, easy to understand, and of production quality. It should be a little more than a simple application template and a little less than a full-featured application. This might be a tough balancing act.</li><li>Demonstrate best practices for the non-functional characteristics of applications, the so-called <a href="https://towardsdatascience.com/architecting-for-the-ilities-6fae9d00bf6b"><em>-ilities</em></a>, or <a href="https://en.wikipedia.org/wiki/List_of_system_quality_attributes">quality attributes</a> of an application. Some of these are supported directly by the platform, i.e., Kubernetes and Helm. Others have to be designed and implemented into the application, for example, metrics and logging.</li><li>Effective use of ReSTful principles</li><li>Automated testing and continuous integration</li><li>Deployment to Kubernetes via Helm</li><li>Written in Go</li></ol><p>I’ve already made good progress on an application that partially addresses these goals. It’s still a work in progress, but it’s a good start. If you want to have a sneak peek, it’s currently <a href="https://github.com/youngkin/mockvideo/tree/master">available on GitHub</a>. If you’re ambitious and have your cluster set up, the README can help guide you through other prerequisites and the deployment steps. If you’re even more ambitious, read the code, create issues, submit PRs, and so on.</p><p>Thanks for following along! Stay tuned for the next series of articles discussing application development and deployment best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad3f69b4a094" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-install-mysql-on-a-raspberry-pi-ad3f69b4a094">How to Install MySQL on a Raspberry Pi</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>