<?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 Erik van Zijst on Medium]]></title>
        <description><![CDATA[Stories by Erik van Zijst on Medium]]></description>
        <link>https://medium.com/@erikvanzijst?source=rss-2f01e04f8696------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Iqr3S3TgSMQeV4XCx-02fw.jpeg</url>
            <title>Stories by Erik van Zijst on Medium</title>
            <link>https://medium.com/@erikvanzijst?source=rss-2f01e04f8696------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 01:00:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erikvanzijst/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[The Open Silicon revolution]]></title>
            <link>https://medium.com/@erikvanzijst/the-open-silicon-revolution-fce5d6fcccb1?source=rss-2f01e04f8696------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce5d6fcccb1</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[integrated-circuits]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[fpga]]></category>
            <dc:creator><![CDATA[Erik van Zijst]]></dc:creator>
            <pubDate>Thu, 12 May 2022 13:44:28 GMT</pubDate>
            <atom:updated>2022-05-12T13:44:28.143Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>I did a talk on open source hardware and silicon chip design at the <a href="https://www.nluug.nl/activiteiten/events/vj22/programma/index.html">NLUUG</a>.</p><p>Those who lived through computing in the 80s and 90s have seen first hand the revolution Open Source Software has had on our industry (and indirectly many others).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fj011awS2CxQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dj011awS2CxQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fj011awS2CxQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0462542d70325e730f4c1b3d04208741/href">https://medium.com/media/0462542d70325e730f4c1b3d04208741/href</a></iframe><p>During the age of commercial UNIX and Gates’ Microsoft, building a software product often meant writing most of it from scratch, or paying for dozens of proprietary libraries with questionable documentation and portability. An industry model inhibiting innovation and slowing progress, while benefiting the software giants that had helped establish it.</p><p>Since then, the OSS revolution has thoroughly and spectacularly reshaped our industry. Nearly every software program today, free or commercial, sits on top of a mountain of OSS code. From your browser to your phone, and from Instagram to Ingenuity, NASA’s helicopter currently roaming Mars, none of it could have been developed at the pace and cost it can today.</p><p>However, all software ultimately runs on hardware and today’s hardware industry, especially digital design and chip manufacturing, is sadly still mostly held hostage by a model much like 20th century software.</p><p>Modern silicon chips are fantastically complex products, often containing millions or billions of transistors, each shaped, laid out and interconnected at absurdly small scale, and manufactured by machines costing tens to hundreds of millions of dollars apiece.</p><p>Like software, digital designs are built by gluing together external libraries called “IP blocks”. From a USB circuit to HDMI, and from RAM to entire embedded CPU cores.</p><p>Unfortunately, most of these hardware libraries or IP blocks are not freely available on github, pypi, or npm and are not pulled into a new project with a quick cli install command, but are licensed in binary form, prohibitively expensive for hobbyists and startups to flourish. This is the case also for the software that “compiles” digital logic designs to lithography masks for silicon wafers.</p><p>This talk explores advances in the Open Silicon / Open Hardware movement which might be at a pivotal moment on its path to disrupting the status quo and bringing critical mass to high quality, open tools and IP blocks.</p><p>I show how the first fully open source chip manufacturing toolchain for use with a real chip foundry has been released, and show an actual die fabricated with it. I touch on the importance of open source FPGA tooling and I will highlight how RISC-V, a fully open instruction set architecture (ISA) might ultimately be to ARM what Linux was to commercial UNIX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqPdX65lVLwOo7uttHfQFg.jpeg" /></figure><p>Slide deck and additional resources for the talk are at: <a href="https://erikvanzijst.github.io/opensilicon/">https://erikvanzijst.github.io/opensilicon/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce5d6fcccb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DIY 8-bit handheld multiplayer gaming device]]></title>
            <link>https://medium.com/@erikvanzijst/diy-8-bit-handheld-multiplayer-gaming-device-cc30baae7372?source=rss-2f01e04f8696------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc30baae7372</guid>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[makers]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[retro]]></category>
            <dc:creator><![CDATA[Erik van Zijst]]></dc:creator>
            <pubDate>Thu, 24 Mar 2022 23:00:39 GMT</pubDate>
            <atom:updated>2022-03-24T23:50:32.082Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<p>Building a super basic 8-bit, retro handheld gaming device with wireless infrared multiplayer capability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kA8sg8c96T1B8fTVwr_zg.jpeg" /></figure><p>After wrapping up my earlier <a href="https://medium.com/@erikvanzijst/custom-16x16-matrix-display-pcb-96c40290c8bc">Arduino-run Tetris project</a> using a breadboard for a controller, I wanted to take a stab at packing it all onto a custom PCB and creating a super basic handheld gaming device, leveraging my existing code and matrix LED displays.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fyx9ZlABf7WM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dyx9ZlABf7WM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fyx9ZlABf7WM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3a5dd0e5023139ab963de46a00d56b0/href">https://medium.com/media/f3a5dd0e5023139ab963de46a00d56b0/href</a></iframe><p>This post offers a summary of the design and construction of this project for which I had used Twitter as a more detailed lab notebook.</p><h3>Erik van Zijst on Twitter: &quot;I&#39;ve been building a super basic retro video game type thingie; mostly just to see if I could even do it.Custom design, schematic, PCB, assembly and firmware, and so far it has all mostly worked. pic.twitter.com/JNku679oNg / Twitter&quot;</h3><p>I&#39;ve been building a super basic retro video game type thingie; mostly just to see if I could even do it.Custom design, schematic, PCB, assembly and firmware, and so far it has all mostly worked. pic.twitter.com/JNku679oNg</p><h3>Display</h3><p>I wanted to carry the matrix panels from the other project, except that I wanted the display to be a little bigger and so I added 2 more panels for a total resolution of 24x16, or 384 discrete LEDs.</p><p>I didn’t want to use an off the shelf LCD display. It would have been great for gaming, but I felt I hadn’t pushed the custom display far enough yet. On the Arduino about half of all cycles went to driving the screen. This screen would be 50% larger and so I wanted to find a more efficient design.</p><p>Matrix displays don’t have individual pins for each LED. Instead, the LEDs are connected in a grid pattern, exposing only the row and column terminals. Only a single row or column can be addressed at a time and so to display a steady image covering the entire display, you need to quickly scan over the rows/columns, refreshing them faster than the eye can see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*NReKZ8Zo3prtrVdDJDRp4A.jpeg" /></figure><p>One performance improvement over the Arduino project is using a parallel bus to the display. On the Arduino, the column bits for the currently active row were clocked out in serial over a single line to a 16 bit shift register. Going to 24 cols would make that 50% slower.</p><p>Instead, if we divide the screen in 3 logical sections; columns [0–7], [8–15] and [16–23] and we use an 8 lane bus, we can clock out 8 bits in a single instruction. By giving each section a dedicated 1-byte register or octal-latch chip on the board, we can write distinct values to each section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dul6ZIEnVf6wLVKj8lGbBA.png" /><figcaption>Instead of serially, column values are pushed out 8 bits at a time over an 8 lane bus</figcaption></figure><p>We put the value for the columns [0–7] on the bus, then toggle the clock line of the first latch. Then put the value for columns [8–15] on the bus, toggle the second latch, and repeat for the third.</p><p>If we create a frame buffer data structure that reflects this segmentation (uint8_t screen[16][3]), we can clock out 24 column bits in just 9 register operations (VPORT3.OUT is the 8 bit data bus):</p><pre>VPORT3.OUT = screen[row][0];     // put 8 bits on the bus<br>VPORT2.OUT |= SEGCLK0;           // bring clk of latch #1 high<br>VPORT2.OUT &amp;= ~SEGCLK0;          // bring clk of latch #1 low<br><br>VPORT3.OUT = screen[row][1];     // put 8 bits on the bus<br>VPORT2.OUT |= SEGCLK1;           // bring clk of latch #2 high<br>VPORT2.OUT &amp;= ~SEGCLK1;          // bring clk of latch #2 low<br><br>VPORT3.OUT = screen[row][2];     // put 8 bits on the bus<br>VPORT2.OUT |= SEGCLK2;           // bring clk of latch #3 high<br>VPORT2.OUT &amp;= ~SEGCLK2;          // bring clk of latch #3 low</pre><h3>Microcontroller</h3><p>For the microcontroller I wanted something close to an Arduino so I’d be able to benefit from the enormous community and freely available libraries and components.</p><p>An actual ATmega328 didn’t have enough IO pins. The display would be needing a lot more pins and I wanted more buttons. There’s the <a href="https://www.arduino.cc/en/Main/arduinoBoardMega2560">ATmega2560</a> which is basically an Arduino with more IO pins, but I picked the <a href="https://www.microchip.com/en-us/product/ATxmega256C3">ATxmega256c3</a> instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3G2mI49AKBi3RE0tTePsNw.jpeg" /><figcaption>The Atmel XMEGA in 64 pin QFP package</figcaption></figure><p>The XMEGA is still an 8 bit AVR chip, but it runs at double the clock speed (32MHz), has more sophisticated IO port registers and depending on the variant, more peripherals like on-chip USB and hardware CRC.</p><p>It also has IrDA (infrared) support for one UART. It would be awesome to try and use that for wireless multiplayer support between 2 devices.</p><h3>Battery powered</h3><p>Because we’re building a handheld device, it needs to be battery powered. Since we’ll also have a USB port that can deliver power, it’d be great if it would only draw from the battery if USB is not connected and run off USB otherwise.</p><p>USB provides 5V, so I opted to use four standard 1.5V AA batteries in series to get into the same ballpark as USB. AA batteries come with different chemistries and voltage curves. Starting at 1.5V for a typical fresh Alkaline battery (but ranging from 1.2V for NiCd to 1.6V for NiZn), the actual voltage drops substantially under load and during discharge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KiIwxQlX9Ar7Ht9h1nSyNg.jpeg" /><figcaption>Typical alkaline battery discharge curve</figcaption></figure><p>The xmega needs a stable 3.3V and so we need decent voltage regulation. I picked a <a href="https://www.ti.com/product/LM3671">step-down DC-DC converter</a> that can take in up to 5.5V and provide 600mA at 3.3V output.</p><p>While 600mA is sufficient to also power the display (one row of 24 LEDs at 0.15mA each is 360mA), 3.3V probably is not. At least not for green and blue LEDs that have a large voltage drop. Because I want to be able to use green LED panels, I chose to run the LEDs directly off the board’s unregulated power supply, relying on 24 <a href="https://www.onsemi.com/pdf/datasheet/nsi45015w-d.pdf">constant current drivers</a>.</p><p>The board would have two power nets: 3.3V and unregulated ~3–5.5V.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0FUSx73jCEX0BL_InHEKw.png" /><figcaption>Automatic switching between USB and battery power</figcaption></figure><h3>PCB assembly</h3><p>I decided to go with a 4 layer PCB and all SMT components this time. At 240x76mm it’s quite large and with 4 layers, it got really expensive at <a href="https://oshpark.com/">OSHPark</a> ($289.30) so instead I used <a href="https://jlcpcb.com/">JLCPCB</a> who quoted $41 for a 5 board batch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vteZqU4A88OYRLiBDw6mkw.png" /><figcaption>KiCad PCB layout</figcaption></figure><p>This was also the first time ordering a stencil and solder paste, as I would do the assembly myself using my rework station’s hot air gun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DwlRp8aIh86q8vC8LeaLA.jpeg" /><figcaption>PCBs manufactured by JLCPCB</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_RnCTA_LwkKrHUamEnVVYQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6T7bWreIeBKwmv9T4DGi3Q.jpeg" /><figcaption>Black solder mask</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7aDn_1pNov3V53ABSyhddA.jpeg" /><figcaption>Fancy silkscreen art on the back</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8LEQjxoqBmQosZKDkqbENQ.jpeg" /><figcaption>The target PCB surrounded by other PCBs to provide a level surface for the stencil</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Md_R1q89gOQcLT6HnTYzqw.jpeg" /><figcaption>Stencil aligned over the PCB and secured with masking tape</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MklhBY2vnWRCctrtCBHhzA.jpeg" /><figcaption>Solder paste applied to the stencil</figcaption></figure><p>Properly applying solder paste through a stencil is craft. After reflow, the first board had quite a few solder bridges that needed careful testing and touching up. The second and third went better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOWUFCqINSN6WiJTNbWEpQ.jpeg" /><figcaption>Solder paste applied, not too shabby!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-1ndtw4zm2LTVHCdWhwDw.jpeg" /><figcaption>This is the largest board I’ve done with a lot of components</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOupA-WFmHTMqDpaXBdOjA.jpeg" /><figcaption>Ugly solder bridges</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VlArIfVtIaHvjJlyzJE1QQ.jpeg" /><figcaption>Quite pleased with the result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lwgowm2J0NcY5oohLxU2Mw.jpeg" /><figcaption>A tiny infrared transceiver</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PJwRTRXsUQdfmjmpWWwcw.jpeg" /><figcaption>Fully assembled</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioLR9mrrjGAtdc6FpSBO7Q.jpeg" /><figcaption>The back has the USB port, on/off switch and 2 AA battery holders</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLhh4lK50VWN9OF4EZYJ0g.jpeg" /><figcaption>Power rails nominal at bringup</figcaption></figure><h3>PCB mistakes</h3><p>After I ordered the PCBs but before they arrived, I noticed a problem with the boards that KiCad’s DRC report had been trying to tell me about. I had the ground and power plane touching!</p><h3>Erik van Zijst on Twitter: &quot;TIL the importance of @kicad_pcb zone priorities to keep copper pours of different nets from overlapping and creating shorts.Shorting PWR and GND does not make for happy circuits. pic.twitter.com/uJ4RIpIO8Q / Twitter&quot;</h3><p>TIL the importance of @kicad_pcb zone priorities to keep copper pours of different nets from overlapping and creating shorts.Shorting PWR and GND does not make for happy circuits. pic.twitter.com/uJ4RIpIO8Q</p><p>Luckily I discovered it before applying power to the board and the fact that it was on the top layer meant I could “fix it” with a knife.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aaNTDSPdLUfbvRES7Ve7qw.png" /><figcaption>Making a cut between the overlapping ground and power planes</figcaption></figure><p>The next self-inflicted problem was me ordering the wrong package flip flops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvRbq2Xrq2fnuGuFMH2wrg.jpeg" /><figcaption>Make sure you order the package that matches your footprint</figcaption></figure><p>However, after I had ordered the properly sized <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT273.pdf">74LV273</a> and reworked the board, it didn’t work and I noticed it wasn’t even the right chip to begin with!</p><p>In the design I had used the <a href="https://www.ti.com/lit/ds/symlink/sn74lv573a.pdf">LV573</a> which has a very different pinout and that meant waiting for another DigiKey order.</p><p>Comically, even with the proper 54LV573 chip, things still didn’t work and at this point I realized the first mistake had occurred months earlier when creating the schematic symbol. I don’t know where I got ~CLR for pin 1 from, as it should be ~OE. As such, it needs to be tied low and not high as on my board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eyDfUQXoOnyd5IDtJ5xcvw.png" /><figcaption>Incorrect pin 1 on the custom schematic symbol</figcaption></figure><p><a href="https://twitter.com/erikvanzijst/status/1279169028318085122">Sadly this wasn’t the first schematic symbol I got wrong</a>, but luckily it was easily patched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igIfzRwoGecv3VrzK8Ou4g.jpeg" /><figcaption>Pin 1 of the octal latch IC bent up</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YoAFPmdby2YWa8Bp5hNLiA.jpeg" /><figcaption>Bodge wire from pin 1 to ground</figcaption></figure><h3>Back plate</h3><p>To give the large PCB a bit more rigidity, I laser-cut a wooden back plate. By using two layers, I could create embedded recesses for the through-hole parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYwUwBvsGrb2ISicwKbKSw.jpeg" /><figcaption>Two-part laser-cut back plate</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-HZJW-gqMueLBCaBFcyTVQ.jpeg" /><figcaption>Gluing together top and bottom parts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmQZNO_vcASxiUJnC7LDRA.jpeg" /><figcaption>Recesses for the through-hole parts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVtWK8RwXGF7q7cYa_Alxg.jpeg" /><figcaption>Final assembly</figcaption></figure><h3>Tetris firmware</h3><p>For the firmware I was hoping to start by just copying the Tetris code I had written on the Arduino earlier.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FME2BUL09KOY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DME2BUL09KOY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FME2BUL09KOY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3edab4da8a9e051f068987d2c8ec3781/href">https://medium.com/media/3edab4da8a9e051f068987d2c8ec3781/href</a></iframe><p>Unfortunately, because the XMEGA is sufficiently different from the ATmega in terms of its peripheral memory mapping, GPIO capabilities, header files and other components, Arduino code does not run as-is. By extension, the Arduino IDE cannot be used, nor any Arduino software libraries.</p><p>This was a bummer, as Arduino compatibility was a factor in choosing the XMEGA microcontroller over, say, one of the many 32-bit ARM-based microcontrollers, many of which run at higher clock speeds too.</p><p>That said, Microchip/Atmel provide tools to bootstrap initial code for peripheral configuration, clock setup and pin assignment. I used <a href="https://start.atmel.com/">Atmel START</a> to generate a gcc/Makefile-based project archive as a starting point that I modified and built upon with my own tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CP5F3P7bqutDMwJnmRbmQA.png" /><figcaption>Atmel START generates custom firmware templates online</figcaption></figure><h3>8-bit sound</h3><p>I included a piezo buzzer on the board so I could add some authentic retro style 8-bit sound effects. A piezo buzzer is different to a speaker in that it does not contain a coil or magnet, but a piezoelectric material that deforms when exposed to an electric field. Like a capacitor, it does not conduct DC current and can be connected directly to an IO pin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SF0wMVxXx5N7sA85cI4gew.jpeg" /><figcaption>A piezo buzzer next to the PDI programming header</figcaption></figure><p>To create a tone, we toggle the IO pin at the frequency of the desired note. To do this, we configure a hardware timer to trigger an interrupt routine toggling the pin at the two times the frequency of the note with a square wave. This works for single notes, but is impractical for chords.</p><p><a href="https://robsoncouto.com/">Robson Cuoto</a> had collected a <a href="https://robsoncouto.com/">bunch of tunes tunes</a> to be played in this manner on Arduino, from which I lifted the Tetris melody.</p><h3>IrDA: multiplayer over infrared</h3><p>As the XMEGA comes with IrDA pulse modulation support for a UART, I decided to add an IrDA transceiver module to the board. Not knowing anything about infrared communication, I picked a <a href="https://www.vishay.com/docs/82633/tfbs4711.pdf">component</a> largely at random. It would be a stretch goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMHEFb3ZVYlzs3TLnYUZmw.jpeg" /><figcaption>The tiny, tiny Vishay TFBS4711 IrDA transceiver</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBViMlpfdPx4jNUs0tZXGQ.jpeg" /><figcaption>Mounted vertically at the very edge of the board, the transceiver faces directly forward</figcaption></figure><p>Getting this to work was a real challenge and worthy of a separate blog post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPI7TXX00E1kIqJURZ7Obw.jpeg" /><figcaption>Infrared light made visible on a digital camera</figcaption></figure><p>Because the infrared sensor is mounted directly next to the LED, effectively creating a loopback channel, a copy of each transmitted frame comes back in through the receiver. To make bidirectional communication work, we need to be able to distinguish these frames from those from the other device.</p><p>Next is the problem of collisions. When both stations start a transmission at the same time, everything gets corrupted and so stations need to coordinate who can safely transmit when.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*3yauNXQ_MOqTlQzI0jjMUg.gif" /><figcaption>Data gets corrupted easily over infrared</figcaption></figure><p>Think CB radio. You wait until the channel is clear and press the mic button to speak. You say “over” to signal you’re done transmitting.</p><p>Following this model, I ended up writing a simple protocol to synchronize two stations into a pattern of taking strict turns transmitting and receiving.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6w0VUgVN1GWCSEB43Qt3nw.jpeg" /><figcaption>Debugging bidirectional infrared communication</figcaption></figure><p>When it’s a station’s turn, it can send a stream of data frames, followed by a special marker frame to indicate it’s done. This tells the peer it should switch to TX mode, while we move to RX, keeping the state machines synchronized while avoiding collisions.</p><p>If a station has nothing to send, it just sends the end-of-packet frame to hand back over.</p><p>During the game, the 16x10 Tetris field is stored as a bitmap of 16 uint16_t’s (ignoring the last 6 bits of each word) and at every turn it just sends the entire bitmap. At 115200 baud, transmitting such 32 byte packet, followed by receiving the peer’s response takes ~10ms, for ~100 real-time screen updates per second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-DIpU_Kl4c3Qv1NdmSnCwA.jpeg" /><figcaption>Stations take turns sending 32 byte packets at 115200 baud</figcaption></figure><h3>Gameplay</h3><p>The firmware boots up with a selection between single player or multiplayer. In single player mode the player is awarded points for completed lines, with the game speeding up as the score increases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t5GiMxAaMe9wvX3gZp2PZg.jpeg" /><figcaption>Classic single player Tetris with previews (right) and hold function (left)</figcaption></figure><p>The player can see the next 4 upcoming bricks and has a “hold” feature to temporarily save a brick for later use. The game stores the highest score in EEPROM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*sQiLeKyaLunipUvQ_x7EKQ.gif" /><figcaption>High scores are stored in EEPROM</figcaption></figure><p>Mulitplayer games are quick with a winner and a loser. Whenever a line is completed, it gets added to the bottom of the opponent’s board, quickly filling up the screen. Whenever the connection is temporarily lost, the game pauses. With the transceiver’s rather limited &lt; 0.7m range and narrow angle, this is not unimportant.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fyx9ZlABf7WM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dyx9ZlABf7WM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fyx9ZlABf7WM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3a5dd0e5023139ab963de46a00d56b0/href">https://medium.com/media/f3a5dd0e5023139ab963de46a00d56b0/href</a></iframe><h3>Resources</h3><p>The entire projects is MIT-licensed as Open Source Hardware and Software and hosted on GitHub, which includes the <a href="https://www.kicad.org/">KiCad</a> schematic and PCB layout files. Also included is the full single and multiplayer firmware.</p><p><a href="https://github.com/erikvanzijst/handheld">GitHub - erikvanzijst/handheld</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc30baae7372" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom 16x16 matrix display PCB]]></title>
            <link>https://medium.com/@erikvanzijst/custom-16x16-matrix-display-pcb-96c40290c8bc?source=rss-2f01e04f8696------2</link>
            <guid isPermaLink="false">https://medium.com/p/96c40290c8bc</guid>
            <category><![CDATA[makers]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Erik van Zijst]]></dc:creator>
            <pubDate>Fri, 17 Jul 2020 05:58:06 GMT</pubDate>
            <atom:updated>2020-08-14T05:01:47.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4eNpDFDD_ZXIwXTSQynq0w.jpeg" /></figure><p>For a previous project I explored what it would take to create a text marquee on an 8x8 LED matrix display without microcontroller, using only 7400 chips, an old EEPROM and breadboard components.</p><p><a href="https://medium.com/@erikvanzijst/matrix-displays-ffbf660fe90e">Matrix Displays</a></p><p>That worked, but 8x8 is very small to do anything interesting and so I wanted to give it another go, create a larger 16x16 panel, design a custom PCB and ultimately hook it up to a microcontroller this time to write some games for it.</p><h3>LED matrix panels</h3><p>Matrix displays typically don’t have individual pins for each LED. Instead, internally the LEDs are connected in a grid pattern, exposing only the row and column terminals. Either the row pins are all anode and the column pins cathode, or vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t05EPueorgED8m9qYWidEA.jpeg" /></figure><p>For reasons unknown to me, the pin-out tends to be rather randomized and unintuitive.</p><p>You can uniquely address only one entire row or column at a time and so to display a steady image covering the entire display, you need to quickly scan over the rows/columns, refreshing them faster than the eye can see.</p><p>For this project I was going to connect 4 panels, creating a 16x16 screen with 256 single-color pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSGUsyaAr5j3XfRXOGU87w.jpeg" /><figcaption>KiCad schematic of four displays wired together</figcaption></figure><h3>Row shift registers</h3><p>While it would be possible to pick a microcontroller with enough gpio pins to directly connect all 32 row and column pins, we can only draw one row or column at a time and so it makes sense to use a shift register to select the active row.</p><p>Like a running light, we set one bit to high and continuously shift that in a circle, connecting the register’s output back to its input. The register’s output pins then connect to the matrix’s anode rows, lighting up one row at a time.</p><p>Shift registers like these are made up internally of a string of d-type flip flops, the input of each connected to the output of the previous. All clock lines are connected together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*roqXW0LfWdZGcryyKDKujQ.gif" /><figcaption>serial-in, parallel-out shift register (<a href="http://www.electronics-tutorials.ws/">www.electronics-tutorials.ws</a>)</figcaption></figure><p>To reach all 16 rows, I daisy-chained two 8-bit <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT595.pdf">74HC595</a>’s and instead of creating a circle, I expose the data line of the first as an input of the display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-uDZZ-BxP5QBQOQksmAd4A.jpeg" /></figure><p>This way, when we start at the top of the screen, we pull ROWSDI high, toggle ROWCLK and write a 1 to the first bit (QA) of the first register. For the next 15 clock ticks we keep ROWSDI low.</p><p>As these shift registers also contain a storage register parallel to the shift register, we actually need to pulse LATCH after performing a shift to make the result visible on the outputs.</p><h3>Column shift registers</h3><p>Now that we can supply power to a single row at a time, we do a similar thing for the columns, where we can sink individual row LEDs to ground, closing their circuit and lighting them up.</p><p>For this we can also use shift registers. With a row selected, we then load up a binary pattern into the column shift registers where a 0 or low connects the output to ground. Again, we need 16 bits wide.</p><p>We expose the data and clock lines as COLSDI and COLCLK respectively, bringing the running total to 4 wires to control the matrix. We also expose a single, shared output enable (~OE) pin and latch (LE / LATCH) pin. Adding a dedicated ground and power lines this gives a total of 8 wires.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_QTqZKNyhV-yEKnQBZmlg.jpeg" /><figcaption>External interface to the display</figcaption></figure><p>Because of the shared LATCH we can stage the selection of the next row, as well as the column bit patterns sequentially and then apply it to the displays with a single, atomic operation.</p><h3>Constant current and the TLC59026</h3><p>LEDs being non-ohmic need a current limiting component to prevent them from burning out.</p><p>If we run the circuit at 3.3 volts and the LEDs forward voltage drop is 2V, we could use 16 identical 130Ω<strong> </strong>resistors to limit the current through each LED to 10mA. However, not all individual resistors and LEDs are the same and so slight differences in tolerance could lead to subtly different brightness levels.</p><p>It would also make it harder to support different input voltages for the board. At 5V we would need 300Ω<strong> </strong>resistors which, at a fully lit screen, would dissipate 480mW in heat, 1.7 times as much as the LEDs themselves.</p><p>A better approach in this case is to use a <a href="https://www.allaboutcircuits.com/technical-articles/the-basics-behind-constant-current-led-drive-circuitry/"><em>constant current</em> driver</a>, a component that fixes the total amount of current in a circuit, regardless of the resistance of the load.</p><p>The <a href="https://www.ti.com/lit/ds/symlink/tlc59025.pdf">TLC59026</a> is a chip that combines a 16 bit shift register with adjustable constant current driver, aimed specifically at circuits like ours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdneIkewIPrA8ovxp06WXQ.jpeg" /></figure><p>The current is set through the value of R-ext which is independent of the supply voltage:</p><pre>I = (1.21V / R) × 15.5</pre><p>I’m using 2.2K for about 9mA per LED. Since all components can operate on 3.3V as well as 5V, we’ll be able to use the board both on 3.3V Raspberry Pi’s, as well as 5V Arduinos.</p><h3>MOSFETs</h3><p>We’re nearly there. If we’d build the circuit as described, we’d likely run into problems with the 595 shift registers not being powerful enough to supply up to 144mA to a row of 16 LEDs. In fact, the 74HC595 is rated to supply up to 35mA maximum and 144mA will likely cause damage.</p><p>Instead, we can use the 595’s output to switch a transistor which in turn supplies power to the row.</p><p>I have a stack of general purpose<a href="https://www.onsemi.com/pub/Collateral/PN2222-D.PDF"> PN2222</a> NPN bipolar junction transistors (BJT) which are effectively current amplifiers. The input current through the base gets amplified on the output side. This is fine for low current applications, but at higher currents a Field Effect Transistor (FET) is generally a better choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*o4RodOpEeS-LwXFRwjFYMQ.jpeg" /><figcaption>Bipolar Junction vs Field Effect Transistors (quora)</figcaption></figure><p>Both BJTs and FETs apply junctions of P and N semiconductor material. A BJT allows current to flow from collector to emitter by sending a current between base and emitter. Higher current through the base translates to higher current from the collector.</p><p>A FET works differently and does not require any actual current flow on its input. Instead, applying a voltage to the input (gate) causes an electric field to extend across the semiconductor channel between source and drain which alters the conductivity as a function of the gate voltage.</p><p>Since a MOSFET’s gate is not electrically connected to either source or drain, but acts more like the plate of a capacitor, no current is drawn and so we also won’t need a current limiting resistor for each of our shift register outputs.</p><h3>High-side P-channel switch</h3><p>Our matrix panels are common anode, which is where we’ll need to apply the transistor. Since this is between VCC and the load (LEDs), we connect the MOSFETs source to VCC and drain to the matrix’s row anode. This configuration is known as a high-side switch. This opposed to a low-side switch where a transistor sits between a load and ground.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Q02D5Pz8Ljmhyi_zq7IbQ.jpeg" /><figcaption>Lots of MOSFETs!</figcaption></figure><p>Like BJTs, FETs come in either N-channel or P-channel and for our high-side configuration we use a <a href="https://www.diodes.com/assets/Datasheets/DMP3085LSD.pdf">DMP3085LSD</a> dual P-channel MOSFET in SO-8 package with a gate threshold voltage of -1V to -3V. This is the voltage differential between source and gate that drives the transistor to saturation (fully open).</p><p>This is a negative voltage because the source is connected to VCC and so to achieve a voltage differential, we need to apply a lower voltage to the gate to activate the transistor. With VCC at 3.3V and the gate at ground, the -3.3V will fully open it. When we have a high signal on the gate, there is zero voltage differential and the transistor will be closed.</p><p>This means that the signals from our 595&#39;s are now inverted and so instead of a single high bit, we need a single low bit to activate a screen row. We’ll do this in the firmware.</p><h3>KiCad PCB layout</h3><p>As a novice not knowing where to source symbols and footprints, I created my own custom schematic symbol for the dual MOSFET package. A decision that would come back to bite me later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maQkjzI4tEKrYrzZccwP-w.jpeg" /><figcaption>KiCad PCB layout design</figcaption></figure><p>I decided to keep the PCB as compact as I could, with the chips underneath the matrix panels and the female connector pins recessed so as to not protrude.</p><p>The panels themselves come in different sizes and since I could not find a KiCad symbol, footprint, nor 3D model for my 37.90mm x 37.90mm variant, I butchered a 32mm x 32mm symbol I found online and hoped for the best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i1n09Gnybae1sf3jIWFD0Q.jpeg" /><figcaption>KiCad render</figcaption></figure><p>I sent the design off to <a href="https://oshpark.com/">OSH Park</a>, selected <a href="https://docs.oshpark.com/services/afterdark/">After Dark</a> (transparent solder mask on black substrate) and, not to repeat an earlier mistake, kept the copper pours on the outside of the board for maximum effect.</p><h3></h3><p>Beginner&#39;s mistake on my part.If you&#39;re gonna go for maximum &quot;After Dark&quot; effect (and you should, cause it&#39;s awesome), don&#39;t do a ground pour.@oshpark #AfterDark pic.twitter.com/L0HSFzPOCa</p><p>Meanwhile I ordered the components from <a href="https://www.digikey.com/">DigiKey</a>.</p><h3>Reflow and assembly</h3><p>The boards came in and they look great.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Nm22uEHxlblQdEHRcJSEg.jpeg" /></figure><p>As my soldering skills are pretty mediocre and I do not have a hot air gun or reflow capabilities, I gave all the SMT footprints extra long pads so I would have an easier time hand soldering.</p><p>Especially the 25 mils pitch of the TLC59025 worried me. I would have picked a larger package had it been available, but alas.</p><p>At this point I was lucky enough to get some help from a coworker who runs our lab at work. While I didn’t order a stencil, she applied just the right amount of solder paste by hand and showed me how to reflow the board. The results were spectacular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NN9dubt4CODAghdfS4wfjQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQcY3WIpTke2dUPZX8o-lQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*rh1KhRMuUcB63U2UlPmhLA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bxo0FRGeMnTnq9JnZQ0gwA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CP6s9xeCZnE71u8baKwrow.jpeg" /></figure><p>I decided against soldering the matrix panels directly to the board. On the one hand because I needed clearance for the connector and the TLC59025 at the very center, but also because it would make it near impossible to get to the chips in case the board wouldn’t work. So instead I put in headers.</p><h3>Hardware bugs</h3><p>I whipped up some Python code to test the board through my 8 year old Raspberry Pi 1B’s gpio pins. Since my old Raspbian installation did not have a recent Python 3, I instead ran the scripts on my Macbook and used <a href="https://gpiozero.readthedocs.io/en/stable/remote_gpio.html">gpiozero’s remoting</a> to drive the control the pins on the RPi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vcRCdptcAsIY8I-TTJ6ZA.jpeg" /></figure><p>While remote gpio access through Python works fine, it is unbelievably slow. So slow in fact that writing a single row to the screen took about 200ms, or about 3.3 seconds for an entire screen refresh. This is so slow you can clearly see the individual rows light up.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FD_1SWLCmTog%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DD_1SWLCmTog&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD_1SWLCmTog%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd946322b8aae49fe96ef5ba679168a3/href">https://medium.com/media/bd946322b8aae49fe96ef5ba679168a3/href</a></iframe><p>Alarmingly, instead of scanning rows neatly top to bottom, it instead swapped each two consecutive rows. Something was not wired correctly, but somehow not badly enough to cause shorts or just not work altogether.</p><p>When I addressed row 1, it activated row 2 and when I addressed 2, it would activate 1. The same was true for every other pair. What each pair of rows has in common is that they are powered by a shared dual MOSFET. Since the pins from the shift registers were correctly ordered, something was wrong with the wiring of the MOSFETs.</p><p>It turns out when I created the KiCad schematic symbol I messed up the pin-out and apparently numbered pins 5–8 bottom up instead of top-down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHFauUilFZ8lJPInX4eRNQ.jpeg" /><figcaption>Pay attention when creating your own schematic symbols</figcaption></figure><p>As a happy coincidence, these four pins are really only two outputs as the FET uses two pins for a single output, probably due to its high 4.9A output rating. This effectively swapped the outputs of each MOSFET.</p><p>We cannot easily change the row scanning order due to our use of a shift register and so row 2 really will scan before row 1. However, we should be able to correct for this in firmware where we can preemptively swap the contents of each row pair. <a href="https://github.com/erikvanzijst/dotmatrix/commit/3c7690eb47ee3960831bf0bd397cd9207c36d3a1">I did fix the symbol</a>, footprint and PCB layout for any future revision.</p><h3>Firmware</h3><p>With Python on the RPi being entirely too slow to drive the screen at a reasonable frame rate, I moved to a plain C implementation on the Arduino UNO.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wUGOJk1o2tj8ZawM5_q5A.jpeg" /></figure><p>To hold the contents of the screen I used a simple array of 16 unsigned ints with each integer presenting an entire row. Since it’s a monochrome screen, each bit represents an individual LED.</p><p>The steps to draw the top row involve first bringing low ROWSDI and toggling ROWCLK. This stages a 0 on the shift registers that will activate the MOSFET for the first row. Then write out each bit of the first unsigned int to COLSDI, toggling COLCLK after each bit. Finally we toggle LE to latch the new values of all registers. The first row is now lit.</p><p>The process for the remaining 15 rows is identical, except that we bring ROWSDI high. This ensures the row shift registers only contain a single 0 that automatically moves down one row at a time.</p><pre>volatile unsigned int screen[16];<br>volatile byte row = 0;</pre><pre>SIGNAL(TIMER2_COMPA_vect) {<br>  digitalWrite(RSDI, row != 0);<br>  pulse(RCLK);</pre><pre>  shiftOut(CSDI, CCLK, LSBFIRST, screen[row]);<br>  shiftOut(CSDI, CCLK, LSBFIRST, screen[row] &gt;&gt; 8);<br>  pulse(LE);<br>  row = (row + 1) % DIM;<br>}</pre><pre>void pulse(unsigned int pin) {<br>  digitalWrite(pin, HIGH);<br>  digitalWrite(pin, LOW);<br>}</pre><p>The screen[] array is the display buffer that we can write to from the main program loop. However, because of the wiring mistake, we need to swap rows whenever we write to screen.</p><pre>// Adjust for hardware wiring error in v01:<br>#define fix(row) (row + ((row &amp; 1) ? -1 : 1))</pre><pre>void setpixel(unsigned int row, unsigned int col, bool on) {<br>  if (on) {<br>    screen[fix(row)] |= (0x8000 &gt;&gt; col);<br>  } else {<br>    screen[fix(row)] &amp;= ((0x8000 &gt;&gt; col) ^ 0xff);<br>  }<br>}</pre><h3>Microcontroller timer interrupts</h3><p>There’s no multithreading on a microcontroller, but we need to write to the display continuously at a high, fixed rate while also running whatever code to actually do something useful and a timer interrupt is a good fit for that.</p><p>The Arduino UNO’s ATmega328 has 3 internal timers that can be used for interrupt callbacks. A timer is essentially a binary counter directly hooked up to the 16MHz oscillator. It constantly increments and loops. There’s a comparator register that you can put a value in that gets matched against the timer at every tick. When it matches, your interrupt routine gets called and the timer gets reset to zero.</p><p>Of the three timers, timer 0 and 2 are just 8 bit wide, counting up to 255 and looping back 0. Timer 1 is 16 bit.</p><p>At 16MHz, counting from 0 to 255 takes only 16us, which is not very useful for most scheduling and so there’s an additional clock divider that can be put in front of it to slow down the counting. This the timer’s <em>prescalar</em> and depending on the timer can be set to 1, 8, 64, 256, or 1024.</p><p>The combination of the processor’s internal clock, the prescaler and comparator value determine the timer’s frequency.</p><blockquote><em>f</em>(Hz) = 16,000,000 / (prescalar × (comparator + 1))</blockquote><p>As an example, using a prescalar of 64 and a comparator value of 255 we get a frequency of 976.5625Hz, or about 1KHz. If we were to use that to drive our row function, we’d be painting 1000 rows per second for about 62Hz (1000 / 16) screen refresh rate.</p><p>While 62Hz is not bad, it’s actually not really flicker-free. If you swing the display around you can clearly see the flicker. Same when you try to record a video of it on your cellphone.</p><p>To choose an appropriate refresh rate we need to know how long it takes to draw one line, which for the above code is 296us, or about 5ms for an entire screen. This puts a hard cap of about 200Hz on our refresh rate. If we go higher we won’t be able to finish the interrupt routine before the next interrupt and we’ll completely starve the main program loop.</p><p>A happy medium is 125Hz where we’re burning a little over half of the ATmega’s cycles on the screen driver, leaving the other half for useful stuff.</p><p>125Hz ×16 rows = 2kHz and working backwards from 2kHz and a 64 prescaler we get a comparator value of 124.</p><p>We configure the timer in setup().</p><pre>void setup() {<br>  cli();                    // disable interrupts</pre><pre>  TCCR2A = 0;               // set entire TCCR2A register to 0<br>  TCCR2B = 0;               // same for TCCR2B<br>  TCNT2  = 0;               // initialize counter value to 0</pre><pre>  // set compare match register for 2khz increments<br>  OCR2A = 124;              // = (16*10^6) / (2000*64) - 1<br>  TCCR2A |= (1 &lt;&lt; WGM21);   // turn on CTC mode<br>  TCCR2B |= (1 &lt;&lt; CS22);    // Set CS22 bit for 64 prescaler<br>  TIMSK2 |= (1 &lt;&lt; OCIE2A);  // enable timer compare interrupt</pre><pre>  sei();                    // enable interrupts<br>}</pre><pre>SIGNAL(TIMER2_COMPA_vect) {<br>  ...<br>}</pre><p>These registers are not terribly well documented on the Arduino site, but can be found in the <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf">ATmega’s datasheet</a>.</p><h3>Logic analyzer</h3><p>To validate the timing I hooked up the logic analyzer and zoomed in on the interval during which 2 rows were drawn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hIWi94c0D2cJf30MUxTsw.jpeg" /></figure><p>Going from top to bottom it clearly shows how the interrupt routine starts by setting RSDI high and clocking RCLK (RSDI was already high, indicating that this is not the top row being drawn). Next the bit pattern for the 16 LEDs is written out on CSDI/CCLK in this case 0000 0001 0100 0101. Finally LE is clocked to latch the new values for both the row and columns simultaneously.</p><p>It also nicely confirms what we measured in the firmware, that the interrupt routine takes almost 300us, just over half the time between interrupts, leaving the rest for main program loop execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*1DmXSg5iCbT83JHryPNGkA.jpeg" /></figure><p>Zooming in further still we can see that a full high/low pulse takes about 2 × 6us. We might be able to get that down a little by bypassing the higher level digitalWrite and shiftOut functions and instead writing to the <a href="https://www.arduino.cc/en/Reference/PortManipulation">port registers</a> directly.</p><h3>Marquee</h3><p>On to doing something more interesting: scrolling text.</p><p>To get text displayed I first needed a very small font. I found a decent looking <a href="https://www.dafont.com/5x5.font">5x5 pixel font</a> that I translated into a large 2 dimensional array stored in <a href="https://www.arduino.cc/reference/en/language/variables/utilities/progmem/">program memory</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VdPOQI4er1U4uDz7ed2LLQ.jpeg" /><figcaption>Minimalist 5x5 pixel font (www.dafont.com)</figcaption></figure><p>Encoding each character as an array of 5 bytes where each byte corresponds to one row of pixels, I used the 5 high-order bits of every byte.</p><pre>const byte font[43][5] PROGMEM = {<br>  {0x1f, 0x13, 0x15, 0x19, 0x1f}, // 0<br>  {0x04, 0x0c, 0x04, 0x04, 0x0e}, // 1<br>  {0x1e, 0x01, 0x0e, 0x10, 0x1f}, // 2<br>  {0x1f, 0x01, 0x0e, 0x01, 0x1f}, // 3<br>  {0x10, 0x10, 0x14, 0x1f, 0x04}, // 4<br>  {0x1f, 0x10, 0x1e, 0x01, 0x1e}, // 5<br>  {0x1f, 0x10, 0x1f, 0x11, 0x1f}, // 6<br>  {0x1f, 0x01, 0x02, 0x04, 0x04}, // 7<br>  {0x1f, 0x11, 0x1f, 0x11, 0x1f}, // 8<br>  {0x1f, 0x11, 0x1f, 0x01, 0x1f}, // 9<br>  [...]<br>  {0x1f, 0x11, 0x11, 0x1f, 0x11}, // A<br>  {0x1f, 0x11, 0x1e, 0x11, 0x1f}, // B<br>  {0x1f, 0x10, 0x10, 0x10, 0x1f}, // C<br>  {0x1e, 0x11, 0x11, 0x11, 0x1e}, // D<br>  {0x1f, 0x10, 0x1e, 0x10, 0x1f}, // E<br>  {0x1f, 0x10, 0x1e, 0x10, 0x10}, // F<br>  [...]<br>}</pre><p>By sticking to the same ordering and offset as ASCII, it is easy to take a normal string and, using the ordinal byte values of each char as the index into the font array, convert it to an array of symbols.</p><p>To then make that scroll across the screen we can iterate over the bits left-to-right, each time shifting the corresponding screen row left by one bit and shifting in a bit from the symbol.</p><pre>void scroll(const char *msg, byte row) {<br>  byte chars[strlen(msg)][5];</pre><pre>  for (unsigned int i = 0; i &lt; strlen(msg); i++) {<br>    // space is mapped to @<br>    const int j = msg[i] == 0x20 ? 0x10 : toupper(msg[i]) - 0x30;<br>    if (j &lt; 0 || j &gt; 43) return;  // unsupported char<br>    memcpy_P(chars[i], &amp;(font[j]), 5);<br>  }<br>  scrollbytes(chars, sizeof(chars) / 5, row);<br>}</pre><pre>void scrollbytes(byte glyphs[][5], int len, byte row) {<br>  for (unsigned int pos = 0; ; pos = ++pos % (len * 6)) {<br>    for (int r = 4; r &gt;= 0; r--) {<br>      screen[fix(row + r)] &lt;&lt;= 1;<br>      screen[fix(row + r)] |= (<br>          (glyphs[pos / 6][r] &amp; (0x20 &gt;&gt; (pos % 6))) ? 1 : 0);<br>    }<br>    delay(75);<br>  }<br>}</pre><pre>void loop() {<br>  scroll(&quot;HELLO WORLD  &quot;, 5);  // scroll in the middle of the screen<br>}</pre><p>To cut corners and due to the fact that the font does not actually cover the entire ASCII character set, I limited myself to just A-Z, 0–9, a few punctuation marks and space. 43 characters in all. Hence the odd 0x30 offset and boundary checks.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSRY-_6TaAQo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSRY-_6TaAQo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSRY-_6TaAQo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdeb5957966531296fb664e33eea6909/href">https://medium.com/media/bdeb5957966531296fb664e33eea6909/href</a></iframe><h3>Tetris</h3><p>Lastly I figured I’d write a little Tetris game for it. With four push buttons for left, right, soft-drop and clockwise-rotate, I turned a breadboard into a poor man’s game controller. I then wrote a simple Tetris implementation, leveraging the marquee code to report scores.</p><p>Scoring mostly follows the original <a href="https://tetris.wiki/Scoring#Original_BPS_scoring_system">BPS scoring system.</a> The <a href="https://github.com/erikvanzijst/dotmatrix/blob/master/arduino/arduino.ino">full code</a> is up on GitHub.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FME2BUL09KOY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DME2BUL09KOY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FME2BUL09KOY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3edab4da8a9e051f068987d2c8ec3781/href">https://medium.com/media/3edab4da8a9e051f068987d2c8ec3781/href</a></iframe><h3>Future ideas</h3><p>It would be nice to see what it would take to do an RGB version, or even just add gray scale support to the current board although for the moment the bandwidth from the Arduino doesn’t seem quite high enough for that.</p><h3>Resources</h3><p>The entire project is on GitHub. The board is licensed under Creative Commons and the software uses the MIT license.</p><ul><li>KiCad board schematic, PCB layout and Tetris implementation: <a href="https://github.com/erikvanzijst/dotmatrix">https://github.com/erikvanzijst/dotmatrix</a></li><li>Gerbers on OSH Park: <a href="https://oshpark.com/shared_projects/Krtz7OJC">https://oshpark.com/shared_projects/Krtz7OJC</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96c40290c8bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A digital quartz clock from scratch]]></title>
            <link>https://medium.com/@erikvanzijst/a-digital-quartz-clock-from-scratch-a80ec5e427?source=rss-2f01e04f8696------2</link>
            <guid isPermaLink="false">https://medium.com/p/a80ec5e427</guid>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[clock]]></category>
            <category><![CDATA[circuit]]></category>
            <category><![CDATA[kicad]]></category>
            <category><![CDATA[pcb]]></category>
            <dc:creator><![CDATA[Erik van Zijst]]></dc:creator>
            <pubDate>Sun, 12 Jan 2020 03:04:56 GMT</pubDate>
            <atom:updated>2020-01-12T05:43:29.293Z</atom:updated>
            <content:encoded><![CDATA[<p>After 20+ years of programming, I wanted to get some understanding of the electronics that make my career possible.</p><p>I had built the basic individual logic gates with transistors on a breadboard, but to build anything meaningful I needed loads of them and so I bought a somewhat <a href="https://smile.amazon.com/dp/B016ME1WH2/ref=cm_sw_r_tw_dp_U_x_9wacEbH6FZVFK">random collection of logic chips</a> on Amazon which introduced me to the <a href="https://en.wikipedia.org/wiki/7400-series_integrated_circuits">7400-series</a> and the concept of datasheets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qia5j06BB3lvpVLFwCcIEw.jpeg" /><figcaption>A fairly random collection of 74xx CMOS logic chips</figcaption></figure><p>After a few <a href="https://medium.com/@erikvanzijst/knight-rider-leds-part-2-protoboard-8e199f14ee78?source=your_stories_page---------------------------">simple projects</a> I wanted to build something more useful: a quartz clock with LED display.</p><h3>No microcontroller</h3><p>A practical way to create a clock would be to hook up 7-segment LED displays to an Arduino or Raspberry Pi and write a few lines of code to drive the displays. For this project however I wanted to use just basic logic gates and no code.</p><h3>BCD and 7-Segment displays</h3><p>I started with a couple of 7-segment LED displays. Typically these have individual pins for each LED and a common cathode or anode. To display a number, you just have to figure out which LEDs to turn on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*Caxeyzx4wRYEXfQXSE1Vzw.png" /><figcaption>A 7-segment display with common cathode</figcaption></figure><p>To display the number 5, you’d bring high lines a, c, d, f and g. Number 1 would be b and c. Hard-wiring the pattern for each number takes a lot of wires and gates and so specialized ICs were developed like the <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT4511.pdf">74HC4511</a> which takes a 4 bit binary number (e.g. 0101 for 5) on its 4 input lines D, C, B and A, and brings the corresponding output lines high (a, c, d, f and g in this case).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*MULSNDLCAOF8f9BqwfeLpw.png" /><figcaption>74HC4511: BCD to 7-segment display decoder</figcaption></figure><p>This chip only supports the numbers 0 to 9 and not the true width of its 4 bit input. Any binary input over 9 produces a blank display. For example, 1111 (15) does not produce a hexadecimal “F”.</p><p>This truncated use of just the lower 10 permutations of a 4 bit binary number is known as <a href="https://www.electronics-tutorials.ws/binary/binary-coded-decimal.html">Binary Coded Decimal</a>, or BCD.</p><h3>BCD counters</h3><p>Now that we can display the numbers 0 to 9 using BCD, we can hook up a binary ripple counter to the 4511’s input. A binary counter is created by <a href="https://www.electronics-tutorials.ws/counter/count_1.html">daisy-chaining several flip-flops</a>, each dividing the frequency of its input clock by two.</p><p>This works by connecting a <a href="https://www.electronics-tutorials.ws/sequential/seq_4.html">clocked D-type flip-flop</a>’s inverted output back to its input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*5YBGdAVM8WcfEZVdivKLxQ.gif" /><figcaption>A D-type flip-flop as a frequency divider (www.electronics-tutorials.ws)</figcaption></figure><p>By connecting <em>n</em> of these in series, we get an <em>n</em>-bit binary ripple counter. An example is the <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiWi6TcptrmAhWWvJ4KHUNRA18QFjAAegQIARAC&amp;url=https%3A%2F%2Fassets.nexperia.com%2Fdocuments%2Fdata-sheet%2F74HC_HCT393.pdf&amp;usg=AOvVaw2uWTCpI9eRMuXpKkst7f_o">74HC393</a> chip which contains two separate 4 bit ripple counters, each counting from 0–15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*k4rrIclVXsgprFFbeF2uaQ.gif" /><figcaption>A 3 bit ripple counter (www.electronics-tutorials.ws)</figcaption></figure><p>For my application however I needed a BCD counter that goes to 9, not 15 and so I used the <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT390.pdf">74HC390</a> which can be wired up to provide 2 independent BCD counters.</p><p>The HC390 actually contains a divide-by-2 and a divide-by-5 stage, each with their own input clock (CP0 and CP1). By connecting the divide-by-2’s output (Q0) to the clock of the divide-by-5 stage (CP1), we get a 0–9 counter. The HC390 contains 2 of these circuits.</p><p>To get the first counter to provide a “carry” clock pulse over to the second when it loops back from 9 to 0, we need to add some circuitry that looks for the pattern 1001 (decimal 9) on the BCD output lines of the first counter. We really only need to look for a 1 on lines A and D (Q0 and Q3 on the HC390) as 9 is the only value that matches that.</p><p>We run those two lines through an AND gate (<a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT08.pdf">74HC08</a>) and connect the output to the second counter’s clock input (2CP0). Since the HC390’s clock input is negative edge triggered, the clock pulse is triggered once the AND gate’s output goes back down (when the first counter goes from 9 back to 0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qk3m3wA82chtnW4TV78vXw.jpeg" /><figcaption>Schematic for the 0–59 seconds display</figcaption></figure><p>At this point we have a 2 digit display that counts from 0–99 and so we need to add a reset signal that caps counting at 0-59 seconds. To do this, we look for the number 6 (0110) on the second counter’s BCD output. We observe that we only need to AND lines 2Q1 and 2Q2 as 6 is the first value to have its middle 2 bits high. We AND these lines and connect the output to the second counter’s master reset line (2MR) to instantly reset it to 0 when it hits 6.</p><p>It’s worth noting that technically we count from 0–6, not 0–5, but the value 6 appears for only a few 10s of nanoseconds while the reset propagates, far too short for the LED display to respond.</p><h3>Minutes and hours</h3><p>The minutes display is identical to the seconds circuit described above, as both are base-60. We have another 74HC390 dual BCD counter, the first of which has its clock line (CP0) hooked up to same signal that drives the reset (2MR) of the seconds display. This way when the seconds go from 59 to 0, the minutes counter goes up by one.</p><p>The additional 2 AND gates needed for carry and reset of the minutes section are taken from the same 74HC08 quad AND chip used for the seconds.</p><p>The hours display is a little different, as this is base-24, split across 2 decimal displays with the following rules:</p><ul><li>right (lowest) display counts from 0 to 9</li><li>loop back to 0 and send a carry signal to the left display</li><li>right counts from 0 to 9 again</li><li>loop back to 0 and send another carry signal to the left display</li><li>right display counts from 0 to 4</li><li>when the combined displays hit 24, send a reset signal to both</li></ul><p>For the left display that counts from 0 to 2 we only use the divide-by-5 counter section with clock input 2CP1 wired to the carry signal of the right display, identical to the minutes and seconds circuits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YHQrB79Fy0CuMdSb9kj5Q.png" /><figcaption>Schematic for the 0–23 hours display</figcaption></figure><p>To reset at 24, we observe that 24 in BCD is 0010–0100, which is the first value that has both 2Q2 and 1Q2 high and so we can AND these and wire the result to both reset inputs.</p><h3>Setting the time</h3><p>To manually set the time we can take over the clock signals on the counters, hook them up to push buttons to advance them one push at a time. To keep this simple I decided to mimic the interface of many 70s and 80s clock radios that typically had three buttons: one you held down to enter override mode and then one to advance the minutes and one to advance the hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3T-aNuMrw-9I1Gf8DtM42A.jpeg" /><figcaption>Vintage 1980s Digital Sonic Clock Radio FM/AM</figcaption></figure><p>While setting the time we should stop the regular clock signal, reset the seconds display to 00, disconnect the normal carry signal from seconds to minutes and minutes to hours so you can loop the minutes counter without causing the hour section to advance.</p><p>To do this, we run the clock input lines for the minutes and hours counters through a <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT157.pdf">74HC157</a> line multiplexer that allows us to switch the clock inputs from the carry signals over to manual push buttons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*amQ7VX3XHrLYqh1Xi8-5UA.png" /><figcaption>A digital multiplexer switches between different input signals (Wikipedia)</figcaption></figure><p>The 74HC157 has four 2-line inputs and one select line (S) which determines which of the input lines are active. The select line is wired up to the “set time” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTYqOPAnfMDBgZ5T6cri9A.png" /><figcaption>Time control button subsystem</figcaption></figure><p>Notice that all signals are inverted along the way. This is because the clock input of the counters is negative edge triggered, while the reset/carry signals that drive the clock of the next stage are positive edge triggered.</p><p>The “set time” button not only drives the multiplexer’s select line, it also connects to the second counter’s reset line, ensuring these are reset to “00”. Because that reset pin is also driven by the 59-to-60 trigger, I needed an OR gate to join these two lines. Yet, since this was the only logical OR I needed on the board, I didn’t feel it was worth adding a full quad-OR <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT32.pdf">74HC32</a> IC. Instead, I used two diodes to create an OR gate, saving most of the space another IC would’ve taken up.</p><h3>De-bouncing</h3><p>When hooking up the push buttons to the inverter inputs we need to anticipate contact noise when pushing down or releasing the button. When a mechanical switch makes two metal contacts touch, there is a very brief moment during which the contacts “bounce”, making and breaking the electrical connection.</p><p>This can be seen on a logic analyzer or oscilloscope at a high enough sampling rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*uNmAmbY09t-6q_i1BUClKQ.png" /><figcaption>Mechanical switches do not cleanly make or break contact (Jack G. Ganssle)</figcaption></figure><p>If we’d connect this signal straight to the counter input, a single button press would actually advance the counter by as much as there are bounces.</p><p>There are many ways to mitigate this phenomenon, either in hardware or, if a microcontroller is used, <a href="https://www.arduino.cc/en/tutorial/debounce">in software</a>. We’ll do it in hardware using resistors and capacitors to build a low-pass filter to smooth out the signal transition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*f98Y1dmI-V0oy70IiCHVxQ.png" /></figure><p>When the push button is not pressed, the hour_button signal is pulled low through R5. When the it is now pressed, capacitor C3 starts charging through resistor R1, causing the voltage on hour_button to rise slowly.</p><p>With VCC at 3V, R1 at 100KOhm and C3 at 100nF, it takes about 11 milliseconds for the voltage to rise to 2V (CMOS logic high). If during this time the connection briefly bounces, the voltage no longer abruptly swings between 0V and 3V, but just slightly prolongs the capacitor charging time. This is important because wild rail-to-rail swings are what trigger digital oscillations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*gPjpNQq8gAnPCSVZcI4Mdg.png" /><figcaption>CMOS logic levels (Sparkfun)</figcaption></figure><p>When released, C3 is slowly discharged through diode D1 and resistor R5, preventing bounce.</p><p>We’re not yet there though.</p><p>3.3V CMOS defines a logic low as any voltage below 0.8V and anything over 2V as a logic high. However, behavior between 0.8V and 2V is undefined and our capacitor charges for 11ms, spending a long time in this undefined zone.</p><p>To prevent unwanted behavior during this transition, we run the signal through a <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT14.pdf">Schmitt trigger inverter</a>. A <a href="https://en.wikipedia.org/wiki/Schmitt_trigger">Schmitt trigger</a> applies hysteresis to the input signal while in the undefined zone, defining its output state to be its previous state. This means that when rising past 0.8V, the output remains a logic low until 2V is reached and vice versa on the way down.</p><h3>Quartz crystal</h3><p>At this point we have pretty much everything, except for an accurate clock signal. In true vintage style I wanted to use a quartz crystal for this. Quartz is a material which exhibits <a href="https://en.wikipedia.org/wiki/Piezoelectricity">piezoelectricity</a>: it generates an electrical charge in response to mechanical stress and slightly deforms when exposed to an electrical charge.</p><p>This property can be used to create a <a href="https://en.wikipedia.org/wiki/Crystal_oscillator">crystal oscillator circuit</a>. First apply a voltage to the crystal and wait for it to deform to resist the charge. Then when fully deformed, remove the charge and wait for the crystal to counter the change while regaining its shape at which point we reapply the charge.</p><p>The duration for a quartz crystal to deform is directly related to its thickness which in turn very precisely defines its resonance frequency. This way quartz crystals can be cut with frequencies from a few kilohertz to hundreds of megahertz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coYdWT9A1qGx49gav8Isrg.png" /><figcaption>Pierce-Gate crystal oscillator circuit</figcaption></figure><p>The mechanism to flip the applied voltage at the end of each phase is often a digital inverter which also provides the gain necessary to keep the oscillation going.</p><p>I chose the <a href="https://ecsxtal.com/store/pdf/ECS-3x8X%202x6X%201X5X.pdf">ECS-2X6X</a> “watch crystal”, with a 32,768Hz resonance frequency. Since 32,768 equals 2¹⁵, we can run the signal through a 15-stage frequency divider to get a precise 1Hz clock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqGWDdpZ6Y6CC0Fn67CiUA.jpeg" /><figcaption>32,768Hz watch crystal hooked up to a 74HC4060 combined oscillator and 14-stage ripple counter</figcaption></figure><p>The <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT4060.pdf">74HC4060</a> is a combined oscillator inverter and 14 stage ripple counter which should produce an accurate 2Hz signal. We add an additional single flip-flop (<a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT74.pdf">74HC74</a>) to provide the final 15th division down to 1Hz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*2wFoHzXIsfPOwkAQ7mSu2A.jpeg" /><figcaption>The logic analyzer shows a very accurate clock signal after 14 divisions</figcaption></figure><h3>Breadboard prototype</h3><p>With all these components in place we could finally wire everything up on a breadboard for a test drive.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRXZeaL9HYxQ%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRXZeaL9HYxQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRXZeaL9HYxQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/00efc38c65f82d911c072c435a7578b3/href">https://medium.com/media/00efc38c65f82d911c072c435a7578b3/href</a></iframe><h3>Automatic brightness control</h3><p>I remember having a clock radio as a child whose LED display automatically adjusted its brightness to ambient light conditions. With daylight it was very bright while at night it dimmed so it didn’t light up the whole room.</p><p>If I were going to put this on a PCB and actually use it, it needed to have this feature.</p><p>In contrast to incandescent light bulbs, the brightness of LEDs is not easily controlled by varying the voltage or current in an analog fashion. A typical red LED won’t emit any light until about 2V is applied and burns out at about at about 3V. When modulating the current through a variable series resistor we get a relatively low contrast ratio and differences in chromaticity or color temperature.</p><p>Instead, the brightness of an LED is more easily controlled by making it strobe very quickly, varying the time between on versus off with a process called <a href="https://en.wikipedia.org/wiki/Pulse-width_modulation">Pulse Width Modulation</a>, or PWM.</p><p>Using a generic <a href="http://www.ti.com/lit/ds/symlink/ne555.pdf">555 timer chip</a>, a <a href="https://en.wikipedia.org/wiki/Photoresistor">photoresistor</a> and some capacitors and resistors, we can create a low tech pulse width modulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ZTXa9Vb-qAAgAclzWeF8A.png" /><figcaption>A typical 555 oscillator circuit (www.electronics-tutorials.ws)</figcaption></figure><p><a href="https://www.electronics-tutorials.ws/waveforms/555_oscillator.html">A typical 555 oscillator circuit</a> (astable multivibrator) is shown above. Capacitor C1 charges through R1 + R2 (<em>t1</em> — output on pin 3 high) and discharges through R2 (<em>t2</em> — pin 3 low). When R1 and R2 have equal resistance, interval <em>t1</em> (high) is twice as long as <em>t2</em> (low). The duty cycle is said to be 67%.</p><p>To create PWM, we can sink the common cathodes of all 7 segment displays through an NPN transistor to ground and connecting the 555 timer’s output to the transistor’s base.</p><p>We’d now like to use a photoresistor for R2 so we can shorten or prolong the discharging time (during which the LEDs are off), while keeping the charging the time fixed.</p><p>Because the duty cycle of the standard circuit cannot go below 50%, we add some diodes to bypass R2 during charging, fixing the charge time to ~0.3ms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cIIfyUaFBEVhJqTpbKqFFg.png" /><figcaption>Adaptive brightness through photoresistor-driven pulse width modulation</figcaption></figure><p>Since photoresistors go to many megaohm in total darkness, I put a 470K resistor in parallel to cap the discharge time at maximum 15ms at a flicker-free 64Hz (duty cycle ~2%). In full daylight discharge time falls to as little as 0.1ms for a 80% duty cycle at ~2kHz, providing a wide variation of intensity.</p><p>Despite all this, the breadboard prototype would not reach full brightness even in broad daylight. This turned out to be due to a 100K resistor R12 I initially used between the 555 and the transistor. At 3V and 100K the current through the base is 30uA. The <a href="https://www.onsemi.com/pub/Collateral/PN2222-D.PDF">PN2222</a>’s maximum gain ratio is about 300, capping the LEDs drain current at 9mA, insufficient for all displays to operate at full brightness.</p><h3>Voltage regulator</h3><p>I wanted to power the circuit using USB for its ubiquity. However, USB is 5V and while the CMOS chips work fine on that, the quartz crystal’s datasheet suggests driving it with 3V and provides values for the series resistor and load capacitors based on this. Running at 5V might require careful recalculation of these components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxvDb9DsMpqtYbSaf5b5HQ.jpeg" /><figcaption>The crystal’s datasheet’s suggested circuit is based on 3V</figcaption></figure><p>Instead I decided to add a voltage regulator and run the entire circuit at 3V. Since I couldn’t find any readily available 3V fixed regulators (3.3V is a more popular output voltage), I picked the 800mA <a href="https://www.digikey.com/product-detail/en/stmicroelectronics/LD1117V50-DG/497-12821-5-ND/3028552">LD1117V</a> adjustable linear regulator and added a potentiometer so I would be able to tune the exact voltage later on the board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7dCJ8uoSvoraz3jbJH3Pw.jpeg" /><figcaption>Voltage regulator circuit</figcaption></figure><p>With a total of 42 LEDs, the six 7 segment displays are the primary energy consumers. Driven at 3V with a 150 Ohm series resistor and 2V drop, they draw 7mA each, for a total of almost 300mA.</p><p>Since most smaller TO-92 regulators are limited to ~100mA, the larger 800mA LD11187V was more appropriate.</p><h3>PCB</h3><p>At this point I was keen to see if I could design a PCB to move the project beyond the breadboard and turn it into an actual usable thing.</p><p>With no EDA experience I installed <a href="https://kicad-pcb.org/">KiCad</a>, followed <a href="https://www.youtube.com/watch?v=vaCVh2SAZY4">DigiKey’s tutorial series on YouTube</a>, and stumbled my way through an initial 2-layer board layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMG74ev_qDckmnp9jdVZ9Q.jpeg" /><figcaption>PCB layout in KiCad</figcaption></figure><p>After weeks of painful adjustments and changes I decided to take the plunge and send the design off to a board house for a prototype run. <a href="https://oshpark.com/shared_projects/OE6N7Z1x">I uploaded the project to OshPark</a> and ordered the minimum 3 board batch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-bS5mcMzKY1llslkIP46dA.png" /><figcaption>OshPark’s auto-generated preview at time of order</figcaption></figure><p>In the meantime I ordered enough components from <a href="https://www.digikey.com/">DigiKey</a> to assemble the 3 boards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kM9v2Lb8axkwdH6MfJqGMA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tPYLmWf1sBVWIg5AQMZYQg.jpeg" /><figcaption>After a 10 day wait, the boards arrived!</figcaption></figure><p>Receiving those first ever boards was quite exciting but also nerve wracking. It would not be easy to make changes or correct mistakes and once everything would be soldered on, even debugging might be a challenge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ddov917DIlbJ2bosrtIkw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3NQ84h0pFPQBgafqwV3LiA.jpeg" /><figcaption>Calibrating the voltage regulator prior to crystal installation</figcaption></figure><h3>Crystal oscillator problems</h3><p>It was at this point that I hit the first real issue. While the crystal oscillator circuit had performed OK on the breadboard, it did not on the fully assembled PCB. It ran too fast. Exactly 5 times faster than it should.</p><p>The cause for the discrepancy between the behavior on the breadboard versus the PCB might be a difference in capacitance. At 22pF, the load capacitors are fairly small, to the point that <a href="https://wiki.analog.com/university/courses/electronics/electronics-lab-breadboard-coupling">parasitic capacitance</a> from the traces and wires and added resistance from poor breadboard contacts need to be anticipated and factored in.</p><p>During the breadboard phase I was able to experiment with different value load capacitors and series resistor. Now that everything was soldered this was a lot more difficult.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdQ_1Jihaq4Q0lrTJrvTTA.jpeg" /><figcaption>Debugging the hard way</figcaption></figure><p>The high cost the PCB put on this stab-in-the-dark, trial and error approach made it unlikely to succeed and the only change I was able to achieve was a configuration at which the crystal oscillated precisely 7 times faster than it should. I was not able to get its frequency down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mq5C4vEH2ZM5yP3Cl9JkaA.jpeg" /><figcaption>Measuring the oscillation frequency with a logic analyzer</figcaption></figure><p>I made an attempt to understand the fundamental properties and math behind <a href="https://en.wikipedia.org/wiki/RLC_circuit">RLC</a> and crystal oscillator circuits such that I could understand the effects different values for load capacitance, series resistance and voltage would have on the drive level and frequency. That way I should be able to accurate derive the correct component values for my board.</p><p><a href="https://electronics.stackexchange.com/questions/448700/calculating-rs-value-for-32khz-pierce-gate-crystal-oscillator-circuit">Calculating Rs Value for 32kHz Pierce-Gate Crystal Oscillator Circuit</a></p><p>Unfortunately I’m more of an engineer than an academic and I had to concede that an alternative approach was needed if I wanted to finish this project successfully.</p><h3>Microelectromechanical system oscillator (MEMS)</h3><p>A friend then pointed me at oscillator ICs which contain a highly accurate resonator along with all the circuitry necessary to provide a stable, precise output frequency. No tuning or external components are needed making them a convenient substitute for quartz crystal based circuits.</p><p>If I could replace the crystal oscillator circuit on the PCB with a <a href="https://en.wikipedia.org/wiki/Microelectromechanical_system_oscillator">MEMS oscillator IC</a> of the same frequency and wire it up to the 74HC4060 clock divider, I might be able to get it running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RLrgYsgfFAmw0_68hMQ7KQ.jpeg" /></figure><p>It would have to be pretty small to fit in the existing space though and I would have to create a little adapter to provide it with power and connect it to the right traces.</p><p>I picked the <a href="https://www.digikey.com/short/zcbnmn">SiT1630</a>, which is a 32,768Hz MEMS oscillator in a very small SOT23–5 package (they don’t seem to come in through-hole).</p><p><a href="https://oshpark.com/shared_projects/KbQrsVwL">I then created a very small PCB</a> with through-hole locations exactly matching those of the crystal circuit. I would then be able to use short solid wires to not only run signal connections between the two boards, but also use them to provide the structural mounting mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0Ty-3j501rKF_5wxS7gJw.jpeg" /></figure><p>On this little board, H2 connects to one of the load capacitor’s GND leads, H1 uses the other capacitor’s now unconnected through-hole to run a power wire through. This wire sticks through the back of the board where it runs along and connects to the VCC terminal of a nearby IC.</p><p>H3 connects to the crystal footprint’s terminal that is connected to the 74HC4060’s clock input, while H4 is not connected to anything and merely provides structural support.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SqjSJKVcW-RbPXIq3O_00A.jpeg" /><figcaption>The MEMS extension board slots into the old crystal circuit’s through-holes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoK9KYHvjLNwqEkXP1zzcw.jpeg" /><figcaption>A hardware patch</figcaption></figure><p>The earlier decision to add a voltage regulator to run the board at 3V instead the 5V USB input proved invaluable at this stage as all readily available MEMS oscillators on DigiKey are rated 1.5–3.63V.</p><p>With all this in place I finally had a working clock!</p><h3>Mounting plate</h3><p>When I did the PCB I put in 5 mounting holes and now it was time to make them useful. To be able to put it up on the wall I created a very simple 3D printed frame on <a href="https://www.tinkercad.com/things/d8liB4Bth6m">Tinkercad</a> that would leave the entire PCB visible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZY9ZHD3X8yrKs_wbR2F4w.jpeg" /><figcaption>Prototyping at the local library</figcaption></figure><p>I used the public printers at the local library to try different colors and verify the dimensions and then used <a href="https://www.3dhubs.com/">3D Hubs</a> to order 3 copies (after all, Oshpark sent me 3 PCBs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFnY0M4QlJ-cPFhnyD5wmw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lJyLlsidIiKJolIT1mFRQ.jpeg" /><figcaption>The final product, 1 of 3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZASAiQBcnlfAEwgZb5l6g.jpeg" /><figcaption>Wall mounted and officially in service</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sKkPbXTxoJGoUtjdFisJYA.jpeg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FVpXJpEoqJYc%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DVpXJpEoqJYc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FVpXJpEoqJYc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fb235ba4f0ed82318c3f5d6ec0287ce/href">https://medium.com/media/3fb235ba4f0ed82318c3f5d6ec0287ce/href</a></iframe><h3>Future improvements</h3><p>Software projects are rarely true “done”. With software you can just create a new commit and release at any time, continuously improving quality, fixing bugs and adding features. You can test a half-baked version, try it on for size, and adjust accordingly. It’s such a normal part of software development that it’s easy to take it for granted.</p><p>I changed and tweaked the PCB layout for weeks, yet pretty much the minute I uploaded it to Oshpark I started finding things I should have changed.</p><p>The first thing I regretted was not putting in the ubiquitous 1Hz double blinking dots between the displays. It would have been trivial and they could have stopped blinking when you hit the “set time” button as a visual indicator that you paused the clock.</p><p>Another one was that the very first display, like all others, will show a zero. However, most digital clocks show midnight as “0:00” instead of “00:00” and that would have been a nice touch.</p><p>And lastly, probably most serious, I forgot to reset the clock divider when “set time” is pressed. Instead, I just bring the seconds counter’s reset line high. As a consequence it’s impossible to precisely synchronize time down to the second. You would let go of “set time” when it’s precisely a full minute, but because the clock divider wasn’t reset, the moment you let you, it won’t take a full second until the first tick. It might tick to 1 almost immediately and so you’d never truly get it synchronized.</p><p>Fixing this by modifying the board was impractical, as I tied the clock divider’s reset line to the ground pour on both the top and bottom layer and so I’d have to cut a circle around the pin on both sides, requiring desoldering of the IC socket first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lx4H3vq5Rmr5uP9ggCPCHQ.jpeg" /></figure><h3>Resources</h3><p>The project’s schematic and PCB layout files in KiCad, as well as the STL file for the base plate can be found at: <a href="https://github.com/erikvanzijst/clock">https://github.com/erikvanzijst/clock</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a80ec5e427" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scramble Pt. 2: Levels & Spawn Points]]></title>
            <link>https://medium.com/@erikvanzijst/scramble-pt-2-levels-spawn-points-41194f5dc80d?source=rss-2f01e04f8696------2</link>
            <guid isPermaLink="false">https://medium.com/p/41194f5dc80d</guid>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[circuit]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[breadboard]]></category>
            <dc:creator><![CDATA[Erik van Zijst]]></dc:creator>
            <pubDate>Fri, 25 Oct 2019 06:22:11 GMT</pubDate>
            <atom:updated>2019-10-25T06:22:11.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*n22GzttO8L8C_bG1EJIXEw.png" /></figure><p>As an exercise into understanding digital electronics and controlling matrix displays in particular, I ended up with quite an elaborate breadboard project and very crude and simple video game I dubbed Scramble:</p><p><a href="https://medium.com/@erikvanzijst/scramble-a-simple-scrolling-game-37f6fbb8b4f8">Scramble: A Simple Scrolling Game</a></p><p>The state of the game as described in that earlier post I decided was good enough to wrap things up on and move on the next phase of designing and immortalizing the working project on a custom PCB layout, freeing up the breadboards for something new.</p><p>At the same time however, my 8 year old son and his friend started playing the game and were appalled that every time they died, they had to start all over from the beginning. With only a single life, the 32Kb single, continuous “world” you navigate through really is quite long.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxDvoqCoyyXbKwlgWZ_AVA.jpeg" /></figure><p>At this point the circuit simply just iterated over every memory address, writing it to the the display as a new column. When you ran into something the game just stopped and you pressed the reset button to start over.</p><p>If I wanted it to capture and hold the attention of the 8 year old brain, some type of level or checkpoint was needed.</p><h3>No Microcontroller</h3><p>I had gotten this far without using an Arduino or other type of microcontroller, using nothing but bare electronic components and generic, <a href="https://en.wikipedia.org/wiki/7400-series_integrated_circuits">7400-series</a> discrete CMOS logic chips.</p><p>I wanted to stick to that for this project, but I didn’t want to increase the chip count too much. PCB manufacturers tend to charge per square inch and so I had to come up with something very simple.</p><h3>Spawn Points</h3><p>What I decided to do was split the 15 bit address counter into two logical sections: the lower 9 bits and the higher 6 bits. They would still just form a single address bus, but the way the bits would be initialized and reset would be different.</p><p>The address counter uses 4 daisy-chained <a href="http://www.ti.com/lit/ds/symlink/sn54hc191.pdf">74HC191</a> programmable 4-bit binary ripple counters that had their programmable data input lines tied to ground and their active-low LOAD line tied to one of the Power-On-Reset lines. This forced the loading of all zeros into the counters both at power-on and when pushing the reset button.</p><p>If we somehow inhibited the reset for the 6 high order bits, then a reset would only affect the 9 low order bits. These 9 bits address 512 bytes of data and this way when you died and hit reset, you would only rewind up to 512 pixels.</p><p>This creates a very simple sequence of 32K/512 = 64 fixed-position “levels” or spawn points. Every 512 pixels you pass a checkpoint. Unless you switched off the power, the 6 high order address bits would never reset.</p><p>To this end, we feed the output of the high order counter bits back to their input lines. This way when reset is pushed, instead of latching zeros, they just latch their existing values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nh2aqsHWhte60n2fqyLaiw.png" /></figure><p>We do still need to force an initial zero-load of the high order bits upon power-on though, just not during reset.</p><p>To achieve this we use a separate, independent power-on delay circuit that provides a low signal for about 9 milliseconds after power-on. This signal runs through a Schmitt-trigger inverter which drives 6 parallel <a href="https://assets.nexperia.com/documents/data-sheet/74HC05.pdf">74HC05</a> open-drain inverters which in turn connect to the 6 high order counter input lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ocuomqspUQ1CJ5hjVrzATg.png" /><figcaption>Open-drain / open-collector output (Wikipedia).</figcaption></figure><p>An <a href="https://en.wikipedia.org/wiki/Open_collector">open-drain</a> inverter’s output is high-impedance when its input is low, but sinks its output pin to ground when the input is high.</p><p>Since the open drains are connected to the counter input lines, these are forced low during power-on when the POR_5 pulse arrives, ensuring a one-off reset. The 100K resistors prevent the output lines from shorting to ground during this phase.</p><h3>Level Design</h3><p>With this in place, attention went to the design of the levels.</p><p>To create level data, I decided to use standard photo/pixel editing software where I could just draw the level, save it as a monochrome PNG or BMP 8 pixels high and then compile it to binary using a small script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2be138e9ce2fbc1ef85cffc0aafc826e/href">https://medium.com/media/2be138e9ce2fbc1ef85cffc0aafc826e/href</a></iframe><pre>$ ./image2bin.py --help<br>usage: ./image2bin.py [-h] [-o OUTPUT] file</pre><pre>Convert image to binary.</pre><pre>positional arguments:<br>  file</pre><pre>optional arguments:<br>  -h, --help            show this help message and exit<br>  -o OUTPUT, --output OUTPUT<br>                        write to file (stdout when omitted)</pre><pre>$ ./image2bin.py levels/level3.bmp &gt; level.bin</pre><p>The binary file can then be written to the EEPROM using the custom programmer I built earlier.</p><p><a href="https://medium.com/@erikvanzijst/diy-eeprom-programmer-4fd11a486ea">DIY EEPROM Programmer</a></p><pre>$ eeprom.py load &lt; level.bin<br>Loading 4096 bytes into EEPROM...<br>100%<br>Complete.<br>$</pre><p>With the total address space logically divided into 64 levels of 512 bytes each, it became convenient to design each level as an individual PNG and concatenate them all in the final compilation step.</p><p>This passed the 8-year-old test so I suddenly had additional level-building resources at my disposal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvowlVFN5Su_rukQKjbvBg.jpeg" /></figure><h3>Reintroducing Text Banners</h3><p>It would be nice to have a visible indication when the end of a level is reached. Similarly, I wanted to be able to display scrolling text with the title of the game at the start of the first level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urIaq9NtOCGVfkXuR9vEYw.png" /></figure><p>Then at the end of a level I wanted to have a bit of a lull and a message announcing the start of the next level.</p><p>I could already do this using the text banner scripts I wrote as part of the <a href="https://medium.com/@erikvanzijst/matrix-displays-ffbf660fe90e">initial matrix display project</a>, but there was the practical problem of the player running into the text and dying.</p><p>This was worst on initial startup when the game opens, boldly scrolling “SCRAMBLE” across the screen, immediately colliding with the player.</p><p>What was needed was a mechanism to programmatically disable the player dot during text scenes.</p><h3>Hiding the Player</h3><p>Since I wanted to leave the level designer some flexibility, I did not want to hardwire fixed address ranges where the player pixel would disappear. Instead, I wanted something that could be embedded in the level data to trigger this dynamically. Ideally with few additional ICs.</p><p>I considered two similar approaches to this.</p><p>I could just designate two specific 8-bit values as a opcodes to enable and disable the player and make it the level designer’s responsibility to avoid those two patterns unless they wanted to toggle the player. It’s quite ugly in that it mixes instructions and data, something computers would always separate, but we’re on a budget.</p><p>An alternative would be to distinguish between odd and even addresses, using one to only hold display data and the other for opcodes. This would have the benefit of opcodes not appearing as visual artifacts on the screen, but would halve the effective capacity of the EEPROM.</p><h3>Opcodes</h3><p>I decided to go with the first approach in large part because it kept level design simple and being able to draw in something like Gimp or MSPaint worked well.</p><p>I then selected two byte values as my opcodes by analyzing every letter and symbol in the 8x8 character set I had compiled from both the Linux and MS-DOS console fonts, looking for vertical byte patterns that did not appear in any of them. That way no text banner could inadvertently toggle the player pixel.</p><p>I picked 0x8a(10001010) to disable and 0x8b (10001011) to enable the player.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PaD_kZXD36DWEg177RM9ng.png" /></figure><p>By putting several of these in sequence we can then make the player blink on and off. This works very well at the start of a level to draw attention to the pixel as the level starts and obstacles scroll into view.</p><h3>Schematic</h3><p>To implement this I used a <a href="https://assets.nexperia.com/documents/data-sheet/74HC688.pdf">74HC688</a> 8-bit comparator to compare the data output from the EEPROM against the hardwired opcode bit patterns.</p><p>While we are looking for 2 distinct opcodes, a single comparator suffices. Since 0x8a and 0x8b differ only on bit zero, we can match on just the 7 high order bits and use the value of bit 0 (LSB) to determine the new state of the player.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QoOBZyzeFpEm0cGa6rZ8w.png" /></figure><p>The player’s state is stored in a <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT74.pdf">D-type flip-flop</a> which is latched when the comparator finds an opcode match, followed by a clock pulse. This latches the state until another opcode is encountered.</p><p>The flip-flop’s active-low ENABLE_PLAYER output line is connected to the circuit that handles the player’s input controller. This contains a custom analog to digital converter (ADC) that gets disabled by a high on PLAYER_ENABLE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcPYM5xQlw1QOTzT-JWOrA.png" /><figcaption>Display, input controller and opcode subsystems.</figcaption></figure><p>At this point the opcodes work and we can dynamically control the player pixel from the level data. However, the opcode also appears as a visible column on the display, which is ugly.</p><p>To suppress the rendering of opcode data, the opcode circuit has an OPCODE output line that goes high when an opcode is being processed.</p><p>This signal is connected to the active-low INPUT_ENABLE of a <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT244.pdf">74HC244</a> line driver inside the matrix display circuit which disconnects the data bus from the shift registers’ inputs, making them latch all zeros during an opcode cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miZnqgPMctXaxRe2B_s75w.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dxw7oXf7n9Rw&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fxw7oXf7n9Rw%3Ffeature%3Doembed&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4f4d773c64da17c9e1a223fb02e2661/href">https://medium.com/media/f4f4d773c64da17c9e1a223fb02e2661/href</a></iframe><h3>Resources</h3><p>The full KiCad schematic can be found at <a href="https://github.com/erikvanzijst/scramble">https://github.com/erikvanzijst/scramble</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41194f5dc80d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DIY EEPROM Programmer]]></title>
            <link>https://medium.com/@erikvanzijst/diy-eeprom-programmer-4fd11a486ea?source=rss-2f01e04f8696------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fd11a486ea</guid>
            <category><![CDATA[eeprom]]></category>
            <category><![CDATA[pcb]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[eeprom-programmer]]></category>
            <category><![CDATA[circuit]]></category>
            <dc:creator><![CDATA[Erik van Zijst]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 15:35:40 GMT</pubDate>
            <atom:updated>2019-10-25T19:16:46.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IyM1A_fdNrr3KZdr.jpeg" /></figure><p>I had a number of projects in mind that I wanted to do without the use of a microcontroller. Yet, I needed some sort of persistent data storage that was easy to access on a breadboard with just basic logic components.</p><p>I decided to try and use old EEPROMs for this. In contrast to most newer EEPROMs they have parallel input and output pins for address and data, making it trivial to read from.</p><p>However, since parallel I/O requires lots of pins, these chips tend to be much larger and expensive than their modern serial counterparts that have largely replaced them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*TLDpNfdZdeCSHrPR.png" /></figure><h3>Atmel AT28C256</h3><p>I chose to target the <a href="https://www.microchip.com/wwwproducts/en/AT28C256">Atmel AT28C256</a> as it’s still actively produced. It has 15 address pins for 2¹⁵ = 32768 addresses. Each address points to one byte, the content of which appears on the 8 I/O pins for a total capacity of 32768 bytes, or 256 <a href="https://en.wikipedia.org/wiki/Kibibit">Kibibit</a>.</p><h3>Programming</h3><p>To load data you need an EEPROM programmer and like the chips, these devices have become somewhat rare and expensive. Hence the project to build one ourselves.</p><p>The easiest approach is probably to use a microcontroller to bridge between the chip and a computer, run a bidirectional serial protocol between the microcontoller and the computer to send image data back and forth.</p><p>Since the AT28C256 requires 5v for writing, we can’t use a Raspberry Pi or Arduino Nano/Mini as their GPIO ports are all 3.3v. The regular old <a href="https://store.arduino.cc/usa/arduino-uno-rev3">Arduino UNO</a> is 5v though and so should work nicely.</p><h3>Schematic</h3><p>Since the Arduino UNO does not have enough GPIO pins, we cannot hook up all address and I/O pins directly. Instead, we’ll use two daisy-chained 8 bit <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT595.pdf">595 shift registers</a> to stage the 15 bit address so that we have to use only 1 pin on the Arduino instead of 15. That leaves enough pins for the I/O lines, shift register control lines and an activity LED.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kWr4zwAGaAW_zuFa.png" /></figure><h3>Reading</h3><p>Reading data is just a matter of putting a 15 bit address on the address pins and then reading the byte that appears on the I/O pins. To do this, we write the address out to pin A4 one bit at a time. Pin A4 is connected to the first shift register&#39;s data line (SER in the schematic).</p><p>After each bit, a pulse is sent out on pin D11 which is connected to the shift registers&#39; clock inputs (SRCLK in the schematic). At each pulse, the bit on the data line is stored in the first of 8 latches, while the existing data is shifted one position down. The value of the last latch is shifted to pin QH&#39; which serves as the data input for the second shift register.</p><p>When all 15 bits have been shifted in, a pulse on line D12 triggers the registers&#39; storage clock (RCLK) and makes the contents of the latches appear on the output pins QA-QH which are connected to the EEPROM&#39;s address pins.</p><p>Within 150ns the contents of the address then appears on the EEPROM’s output pins where we can read it on the D2-D9 pins of the Arduino.</p><h3>Writing</h3><p>Writing data is a bit more work.</p><p>First, we shift out the address we want to write as before. Then we bring the EEPROM’s Output Enable (~OE) high and Chip Enable (~CE) low to put the I/O pins in high impedance mode.</p><p>Then we output the data we want to write onto the D2-D9 I/O lines, followed by a high-low-high pulse on the EEPROM&#39;s~WE pin (connected to A0 on the Arduino). This initiates a write operation which needs up to 10 milliseconds to complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O2aLmvS20354kQJX.png" /></figure><p>At 150ns vs 10ms for reading and writing respectively, the difference in performance is tremendous. To address this, the chip has a Page Write mechanism that allows for bursts of up to 64 bytes to be written in one cycle, using a 64 byte internal page memory staging area and a slightly more involved write sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JfL_FTtv0DG68Zfe.jpeg" /></figure><h3>Arduino Code and Python Interface</h3><p>To communicate with the Arduino interactively, we defined a <a href="https://raw.githubusercontent.com/erikvanzijst/eeprom/master/protocol.txt">simple bidirectional, command-based protocol</a> for use over the serial-to-USB interface.</p><p>On the computer we run a Python script that sends commands to the Arduino which responds by either reading or writing data.</p><p>The protocol has 5 distinct commands:</p><ul><li><strong>read</strong>: tells the Arduino to read a single address and return its value</li><li><strong>write</strong>: tells the Arduino to write a given byte to a specific address</li><li><strong>dump</strong>: dumps the entire contents of the EEPROM as a binary stream</li><li><strong>load</strong>: writes a stream of binary data to the EEPROM</li><li><strong>reset</strong>: resets the internal state of the Arduino to recover from errors</li></ul><p>The Python client program implements this protocol and have data piped directly to it on the shell.</p><pre>$ ./eeprom.py --help<br>usage: ./eeprom.py [-h] [-p PORT] {dump,load,test} ...<br><br>AT28C256 EEPROM Programmer<br><br>positional arguments:<br>  {dump,load,test}      sub-command help<br>    dump                dumps the entire contents of the EEPOM to stdout<br>    load                loads up to 32kb of stdin onto the EEPROM<br>    test                writes random data and reads it back for verification<br><br>optional arguments:<br>  -h, --help            show this help message and exit<br>  -p PORT, --port PORT  the serial port the Arduino is connected to (on OSX<br>                        typically /dev/tty.usbmodemXXXX)<br>$</pre><p>It also has an interactive REPL-like interface that can be handy to peek and poke at specific addresses.</p><pre>$ ./eeprom.py <br>AT28C256 EEPROM Programmer</pre><pre>Read or write individual addresses, dump out the full contents to a file, or<br>load an image file onto the EEPROM.</pre><pre>To read a single byte:<br>&gt; [r|read] [addr]</pre><pre>To write a byte to a specific address:<br>&gt; [w|write] [addr] [value]</pre><pre>To dump the entire EEPROM to a file:<br>&gt; [d|dump] [filename]</pre><pre>To load a local file into the EEPROM:<br>&gt; [l|load] [filename]</pre><pre>Send a reset command:<br>&gt; reset</pre><pre>Address supports hex (0xFF) and octal (0o7) notation.</pre><pre>&gt;</pre><h3>Amazon</h3><p>As parallel EEPROMs are somewhat expensive, I thought it would be a good idea to order from a <a href="https://www.amazon.com/sp?_encoding=UTF8&amp;seller=A16AIX8W4ITW1M">Chinese seller</a> claiming to have genuine, brand new Atmel AT28C256 chips for a fifth of US retail price. Even if one were defective, I’d still have 4 left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*jY30IzQiyB-Wlo_Q.png" /></figure><p>Don’t.</p><p>All 5 chips already contained data (new chips come empty as per the datasheet). Two of them had the software write protection enabled (new chips never have that as your first action will be to write to them). Two others exhibited corruption issues where specific addresses would fail to hold their data.</p><p>Still, the seller maintained the product was brand new and not at all pulled from old computer equipment.</p><pre>$ file eeprom2.bin<br>eeprom2.bin: PDP-11 demand-paged pure executable</pre><h3>PCB</h3><p>With the breadboard circuit, Arduino code and Python CLI interface working I decided to try and create a custom PCB in <a href="http://www.kicad-pcb.org/">KiCad</a> that would slot onto the Arduino as a <a href="https://learn.sparkfun.com/tutorials/arduino-shields/all">Shield</a> extension board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zWo6AtRk26TU74uS.png" /></figure><p>To gain some experience hand-soldering surface mount devices, I picked SMT packages for the shift registers and decoupling capacitors.</p><p>The ZIF socket is a 40 pin device I had lying around. Since the AT28C256 is a 28-DIP, I just left the 12 left-most pins unconnected. It’s a low budget project.</p><p>When I went to upload the Gerber files to <a href="https://oshpark.com/">OshPark</a> for fabrication I noticed their “ <a href="https://docs.oshpark.com/services/afterdark/">After Dark</a> “ option that uses a black FR4 substrate, with transparent soldermask that makes the copper traces pop against a black background.</p><p>Unfortunately I made this choice after I already designed and uploaded the board and failed to realize I should have removed the ground plate from the front of the board for the visual effect to work.</p><h3></h3><p>Beginner&#39;s mistake on my part.If you&#39;re gonna go for maximum &quot;After Dark&quot; effect (and you should, cause it&#39;s awesome), don&#39;t do a ground pour.@oshpark #AfterDark pic.twitter.com/L0HSFzPOCa</p><p>The board still works fine either way and provided good SMT practice although next time I could change the footprints to have longer exposed pads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wazb0vC8xDIovaYa.jpg" /></figure><h3>Final Board and Resources</h3><p>The KiCad project as well as the <a href="https://raw.githubusercontent.com/erikvanzijst/eeprom/master/protocol.txt">serial protocol</a> description and code for the Arduino and Python CLI can be found on <a href="https://github.com/erikvanzijst/eeprom">on GitHub</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-e47g5MrUd1tx7Jj.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GFpb295xIqvxsfaP.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A7fxwrbZVo9l2o1f.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lt9NNihkOKbFoazI.jpg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLrvN16UWzd9EryeSAD-SocTLd7Eodnu2W%26start%3D0&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHwUqPn2EaRc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHwUqPn2EaRc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9720f357fc30372ebd3a1e49a03d5f3/href">https://medium.com/media/e9720f357fc30372ebd3a1e49a03d5f3/href</a></iframe><p><em>Originally published at </em><a href="https://erikvanzijst.github.io/electronics/eeprom/"><em>https://erikvanzijst.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fd11a486ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scramble: A Simple Scrolling Game]]></title>
            <link>https://medium.com/@erikvanzijst/scramble-a-simple-scrolling-game-37f6fbb8b4f8?source=rss-2f01e04f8696------2</link>
            <guid isPermaLink="false">https://medium.com/p/37f6fbb8b4f8</guid>
            <category><![CDATA[circuit]]></category>
            <category><![CDATA[eeprom]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[breadboard]]></category>
            <category><![CDATA[videogames]]></category>
            <dc:creator><![CDATA[Erik van Zijst]]></dc:creator>
            <pubDate>Sun, 20 Oct 2019 23:02:43 GMT</pubDate>
            <atom:updated>2019-10-20T23:02:43.664Z</atom:updated>
            <content:encoded><![CDATA[<p>With the <a href="https://medium.com/@erikvanzijst/matrix-displays-ffbf660fe90e">marquee display working</a>, I figured it would be interesting to see if it could be expanded upon with some interactive elements to turn it into a (very simple!) game.</p><p>Could we fly and navigate a pixel through a scrolling field of obstacles in the style of early video games?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*jc27zBPUDY15ktzN.jpg" /></figure><p>I loved playing <a href="https://www.youtube.com/watch?v=pmPjsBDN9Xw">River Raid</a> in the mid 80s which according to <a href="http://www.vintagecomputing.com/index.php/archives/800">creator Carol Shaw was inspired</a> by the 1981 Konami video game <a href="https://en.wikipedia.org/wiki/Scramble_%28video_game%29">Scramble</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*wxtqQKLAT2Eov-hT.gif" /></figure><p>With a heavy dose of imagination, an 8x8 two-color display with a single interactive pixel for a spaceship might be a bit like the horizontally scrolling game Scramble?</p><h3>No Microcontroller</h3><p>When tinkering with the <a href="https://medium.com/@erikvanzijst/matrix-displays-ffbf660fe90e">marquee circuit</a>, I decided to avoid using a microcontroller, Arduino or Raspberry Pi and code, but instead hardwire everything using basic logic ICs. Even though it severely limits the complexity we can reasonably achieve on a breadboard, it’d be a fun challenge to continue this artificial restriction.</p><h3>Overlay Drawing</h3><p>Since the marquee circuit merely displays what’s in the shift registers and can only append to the data, not modify any pixel data already in the latches, I decided to draw the movable pixel on top of the marquee data, on the left-most column of the display and let you move it up an down using some input control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/0*6EhME5PNkzGVD0mL.png" /></figure><p>Your pixel will be at any value between 0–7 on the left-most column and to paint it on the display, we need to wait until the row that we are on is being drawn and then light up the last (left) pixel of the row, regardless of the contents of the shift register at that location. When a row is painted that we are not on, then the last pixel should just reflect the contents of the register.</p><p>Expanding on the schematic from the <a href="https://erikvanzijst.github.io/electronics/matrix/matrix.html">marquee circuit</a>, we can use an OR gate to compare the value of the last bit of the shift register and whether our pixel is located on the row currently being painted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z5y9AOdiKjPKzr_v.png" /></figure><p>This also provides a convenient place for collision detection and the player to die. If both lines are high, we have a collision, so at this point we’re adding a <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT08.pdf">74HC08</a> (quad AND gate) and <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT32.pdf">74HC32</a> (quad OR gate).</p><h3>Input Control</h3><p>To move the spaceship pixel up an down I decided to use a potentiometer for the player to turn up and down, instead of push buttons, even though the analog nature of a pot and lack of microcontroller means more circuitry.</p><p>I decided to reuse the <a href="https://medium.com/@erikvanzijst/3-bit-digital-to-analog-converter-61427ca971b4">custom Analog to Digital Converter</a> circuit I had built earlier. It uses the pot as a voltage divider and a series of op amps to compare the voltage to 7 discrete levels. This is then encoded into a 3-bit binary number indicating the horizontal row the player is on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aOvSbb7snHlseOEr.png" /></figure><p>As the display scanning and refreshing logic repeatedly cycles up and down the display, painting each line, the player’s 3-bit location is compared to the display counter. When the player’s row is painted, the two 3-bit values will match and we bring the second line to the OR gate high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E-VNDELQmEchK4dc.png" /></figure><p>For this comparison we’re using a <a href="https://assets.nexperia.com/documents/data-sheet/74HC688.pdf">74HC688</a> 8-bit magnitude comparator (though we only use 3 of its bits).</p><p>With this in place, we now have a vertically movable pixel on top of whatever content scrolls over the display. The circuit even detects when you run into the environment (although it doesn’t respond yet).</p><h3>Power On Reset</h3><p>When an electronic circuit that maintains state, like a <a href="https://en.wikipedia.org/wiki/Flip-flop_%28electronics%29">flip-flop</a>, is powered on, it’s initial state (on or off) is generally unpredictable. This is also the case for the storage flip-flops in our shift registers. This means that on startup the display will be filled with random data which then gradually scrolls off-screen as new data is latched.</p><p>This was annoying with the earlier marquee circuit, but is very problematic for our game as random data might spawn on the player’s location, instantly causing a collision.</p><p>To avoid this we need to make sure all shift registers boot up empty and since the only way to clear a 595 shift register is to bring its SRCLR line low and then clocking its latch input SRCLK, we need to build a little multi-step circuit that runs only on startup.</p><p>Not sure how this type of thing is typically done, I decided to add a resistor-capacitor that starts charging on startup, rising its voltage until it triggers a <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT14.pdf">schmitt-trigger inverter</a> to flip, providing a digital signal delayed by about 2.5 milliseconds after startup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A0gx5Bh_q6GjQlxB.png" /></figure><p>By daisy chaining several of these we get 5 output lines that exhibit the following delayed characteristics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1sFru0rLH9VtduT1.png" /></figure><p>Note that the voltage on the first line rises gradually instead of sharply, which is not a digital signal, confusing the logic analyzer.</p><p>We connect the shift registers’ SRCLR line to line POR_5 so we have about 7ms after startup to deliver a pulse to SRCLK and clear out the register&#39;s initial random data.</p><p>We also connect POR_5 to the display driver&#39;s line decoders&#39; G1 pins to disable their outputs during these initial 7ms. This way none of the shift registers or display cathode drains activate, keeping the display dark.</p><p>We AND POR_3 and POR_4 to create a single low-high-low pulse from ~2.5 to ~7ms after startup to flush the contents. This one-time pulse can be OR&#39;d with the regular clock signal driving the shift registers&#39; SRCLK inputs during the marquee cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YVBc1AMqrqv4VzIl.png" /></figure><p>Lastly we also need to reset the address counters to 0 on startup. The <a href="http://www.ti.com/lit/ds/symlink/sn54hc191.pdf">74HC191</a> has a LOAD line ( Pl in the schematic) to instantly set the internal state to the values on the 4 input lines P0-P3 on which we use pull-down resistors. The Pl pin is connected to POR_5.</p><h3>Collisions</h3><p>The game now starts up cleanly with an empty screen as the parcourse starts scrolling in from the right and we need a mechanism to freeze the game when you collide with the environment.</p><p>To be able to control the scrolling we add a <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT74.pdf">74HC74</a> flip-flop we can toggle between scrolling and stopped. This state can be used as input on the marquee’s address counters’ Count Enable CE pin.</p><p>We want to make sure the flip-flop comes up in counting mode at startup to start off the game scrolling and so we connect its data input line to VCC and its clock line to POR_5 so in the event the flip-flop comes up in LOW state, it will toggle automatically to HIGH at the 7ms mark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mccIKQCacTS0U0hU.png" /></figure><p>Next we connect the inverted collision signal from earlier to the flip-flop’s reset R line. When a collision occurs, R will go from HIGH to LOW, toggling the state to off, bringing the counters&#39; Count Enable Ce line HIGH, stopping all scrolling motion.</p><h3>Race Conditions</h3><p>When testing this collision logic, I kept dying whenever there was a wall directly below me. This shouldn’t happen as I never actually moved into the row below.</p><p>With the logic analyzer connected to the AND gate that compares the draw signal from the ADC input circuit against the pixel value from shift register of the active row, an odd signal appeared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*eWDBY6gdkcwMUbW_.jpg" /></figure><p>First the player’s row gets drawn during which line A goes high. This row does not have scenery on the last pixel, represented by a low signal on the output line of the shift register B. Then, the display switches to paint the next row. At this point the (next) shift register output line goes high, while the player&#39;s row goes low (we&#39;re not visible on this line) simultaneously.</p><p>There should not be pulse on the AND gate’s output, but for ~40ns (the highest resolution of my <a href="https://www.sparkfun.com/products/15033">24MHz logic analyzer</a>) the output is high, triggering the game state flip-flop.</p><p>What’s actually happening here is that during the row transition the signal from the shift register arrives slightly ahead of the signal from the ADC (which traverses a longer path through more ICs) and so for a few nanoseconds, both AND inputs are high. A literal race condition.</p><p>The crude solution I came up with was to put a simple RC low pass filter on the AND gate’s output to suppress pulses shorter than 2 microseconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fdghdW3WzlJk3jmB.png" /></figure><p>This got rid of the race condition and stabilized the game play. The ghost pulse still appeared on the AND gate, but didn’t propagate through the filter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*8tgcJSLSeT4KCz8a.jpg" /></figure><h3>Restarting</h3><p>To restart the game after it stops, we extend the Power On Reset circuit by adding a button to discharge the capacitors, re-initiating the conditions at startup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CoU67A1HAdbbAfKQ.png" /></figure><p>That brought the project to a point where I thought it was complete enough as a first version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9D4tupu8GpQMhKXd.jpg" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLrvN16UWzd9EryeSAD-SocTLd7Eodnu2W%26start%3D0&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJxsSOqSgFzE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJxsSOqSgFzE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/53939d3d77759cb571149b88c2980370/href">https://medium.com/media/53939d3d77759cb571149b88c2980370/href</a></iframe><h3>Resources</h3><p>The full KiCad schematic can be found at <a href="https://github.com/erikvanzijst/scramble">https://github.com/erikvanzijst/scramble</a></p><p><em>Originally published at </em><a href="https://erikvanzijst.github.io/electronics/scramble/"><em>https://erikvanzijst.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37f6fbb8b4f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matrix Displays]]></title>
            <link>https://medium.com/@erikvanzijst/matrix-displays-ffbf660fe90e?source=rss-2f01e04f8696------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffbf660fe90e</guid>
            <category><![CDATA[eeprom]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[breadboard]]></category>
            <category><![CDATA[led-display-board]]></category>
            <category><![CDATA[circuit]]></category>
            <dc:creator><![CDATA[Erik van Zijst]]></dc:creator>
            <pubDate>Sun, 20 Oct 2019 22:46:19 GMT</pubDate>
            <atom:updated>2019-10-29T00:20:32.797Z</atom:updated>
            <content:encoded><![CDATA[<p>I was interested in using an LED matrix display and I picked up some cheap 8x8 ones on Amazon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9_4ZGU6j5bZ-smPo.png" /></figure><p>Matrix displays typically don’t have individual pins for each LED. Instead, internally the LEDs are connected in a grid pattern, exposing only the row and column terminals. Either the row pins are all anode and the column pins cathode, or vice versa.</p><p>Put power on row 3 and connect column 2 to ground and the LED on the intersection between those lines lights up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*YzfQH8lCHkxxIPBx.png" /></figure><p>You can uniquely address only one entire row or column at a time and so to display a steady image covering the entire display, you need to quickly scan over the rows/columns, refreshing them faster than the eye can see.</p><p>My Amazon order came in a ziplock bag without datasheet or product numbers and since the position of the pins does not at all line up with the rows and columns, it took a while figuring things out.</p><h3>Driving Matrix Displays</h3><p>A common way to drive bare matrix displays of this kind is to hook them up to a microcontroller and implement the continuous refresh cycle in software, painting one column at a time at high speed, typically using a <a href="https://en.wikipedia.org/wiki/Shift_register">shift register</a> as a staging area holding the pixels for the active column.</p><p>In case of a <a href="https://www.arduino.cc/en/tutorial/ShiftOut">74xx595</a>, the shift register’s 8 outputs are connected the 8 row pins, providing the anode for the LEDs. The column pins can be connected to the MCU directly as output pins. Put 8 bits in the shift register and pull one of the column pins low so as to be a current sink and one row will light up. Now load the data for the next row and toggle the next column. Rinse and repeat many times per second.</p><p>To offload the MCU, there are <a href="https://playground.arduino.cc/Main/LEDMatrix/">specialized ICs</a> implementing the refresh logic in hardware.</p><p>I did not want to use a microcontroller or code, but instead try to drive the displays directly with basic logic hardware.</p><h3>Marquee</h3><p>A relatively simple application is the scrolling marquee. For this I used 8 74HC595 shift registers, each dedicated to holding the data for one column. All registers are connected to a single bus. Only one register has its output pins enabled at any one time, with the others set to tri-state.</p><p>The 8 cathodes of the displays are connected to 8 <a href="https://assets.nexperia.com/documents/data-sheet/74HC05.pdf">74HC05</a> open-drain inverters acting as sinks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GVrbdaZrwDJVx9_p.png" /></figure><p>The control logic responsible for cycling through the shift registers and drains is implemented using a <a href="http://www.ti.com/lit/gpn/ne555">555 timer chip</a> oscillating at ~400Hz, driving a <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT393.pdf">4 bit binary counter</a> of which we only use the lower 3 bits to repeatedly count from 0–7.</p><p>The binary counter then feeds to 3–8 line decoders that activate one shift register and column sink at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nbtWsboi4gb4KI2n.png" /></figure><p>A line decoder activates the output pin that corresponds to the binary number on its inputs. A 3 line decoder therefore has 8 output pins. The binary number 3 (011) triggers line Y3 of the decoder to go high, which opens the inverter for the 4th column (zero, binary 000, activates line Y0 and 7, binary 111, activates Y7).</p><p>Since the 595 Output Enable inputs are “active low”, we need a line decoder with inverted outputs (all pins high, except the active one). This is why we use both a <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT138.pdf">74HC138</a> and its nearly identical cousin <a href="https://assets.nexperia.com/documents/data-sheet/74HC_HCT238.pdf">74HC238</a> for the row and columns respectively.</p><h3>Clocking input</h3><p>With this in place all we have left to do is feed the shift registers with data. If we do this continuously, we’ll get a scrolling marquee.</p><p>As we’re not using a microcontroller, I chose to use a parallel <a href="https://en.wikipedia.org/wiki/EEPROM">EEPROM</a> for data storage. EEPROMs act like non-volatile <a href="https://en.wikipedia.org/wiki/Static_random-access_memory">SRAM</a> and the older, parallel ones have a parallel address and data bus that makes them trivial to interface with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/0*gyOKCl3HB4rmGddy.jpg" /></figure><p>The parallel address bus limits the capacity. You need a large physical chip with 15 address pins and 8 data pins for just 32KiB of data. As this doesn’t scale well, more modern EEPROMs have <a href="https://www.rfwireless-world.com/Terminology/UART-vs-SPI-vs-I2C.html">serial interface protocols</a>.</p><p>I chose the 256 kibi-bit (32KiB) <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/doc0006.pdf">AT28C256</a> as it’s still readily available.</p><p>We hook up the address pins to a 15 stage ripple counter that slowly cycles through the entire address space and we hook up the 8 data pins to the data input lines of the shift registers. After loading an address and putting the 8-bit data onto the shift registers’ inputs, we clock the shift and latch pins of all registers simultaneously, appending a new row of data to the display.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OCT7EUFDVSdiWgwF.png" /></figure><p>Because there are no 15 stage ripple counters, we’re daisy chaining 4 4-stage <a href="https://assets.nexperia.com/documents/data-sheet/74HC191.pdf">74HC191</a> counters. We’re using the 15 high bits for the EEPROM address and the first bit (LSB) as a clock signal write the input to the shift registers between the loading of the addresses.</p><p>The clock signal is produced by another 555 timer running at 48Hz.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLrvN16UWzd9EryeSAD-SocTLd7Eodnu2W&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D7vDrLuH4eWA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F7vDrLuH4eWA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2fa02568a503685d4804ed4504e6428/href">https://medium.com/media/d2fa02568a503685d4804ed4504e6428/href</a></iframe><h3>Data Format</h3><p>Each byte in the EEPROM corresponds directly to a full row of pixels and since we want the marquee to scroll from right to left, we rotate the display such that each shift register’s contents align with a horizontal row of pixels, with the register’s first output pin connected to the right-most pixel.</p><p>This way each byte in the EEPROM appears as a vertical line of 8 pixels on the right side of the display, shifting the existing data one position to the left.</p><p>To encode an 8x8 picture, we slice it vertically, each byte going from top to bottom.</p><pre>--------<br>--------<br>-####---<br>##--##--<br>######--<br>##------<br>-####---<br>--------</pre><p>For instance, the letter “e” gets encoded as</p><pre>00011100    // first column<br>00111110    // second column<br>00101010    // ...<br>00101010<br>00111010<br>00011000<br>00000000<br>00000000</pre><p>The font used in the video is the standard 8x9 (truncated to 8x8) <a href="https://www.zap.org.au/software/fonts/console-fonts-zap/">Linux console font</a> for VGA text displays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*sXlXUqGvfmhjfId7.png" /></figure><p>I wrote <a href="https://gist.github.com/erikvanzijst/50b74403c8a2465201c41968dd26081b">2 small scripts</a> to load the text output from <a href="https://www.seasip.info/Unix/PSF/">psftools</a> and compile any string to the binary format expected by the circuit.</p><p>With each character taking up 8 bytes, the total capacity of the 32KiB EEPROM is 4096 characters.</p><p><em>Originally published at </em><a href="https://erikvanzijst.github.io/electronics/matrix/matrix.html"><em>https://erikvanzijst.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffbf660fe90e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Bit Digital to Analog Converter]]></title>
            <link>https://medium.com/@erikvanzijst/3-bit-digital-to-analog-converter-61427ca971b4?source=rss-2f01e04f8696------2</link>
            <guid isPermaLink="false">https://medium.com/p/61427ca971b4</guid>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[breadboard]]></category>
            <category><![CDATA[operational-amplifier]]></category>
            <category><![CDATA[analog-to-digital]]></category>
            <category><![CDATA[cad]]></category>
            <dc:creator><![CDATA[Erik van Zijst]]></dc:creator>
            <pubDate>Sun, 20 Oct 2019 00:26:12 GMT</pubDate>
            <atom:updated>2020-08-16T23:54:47.958Z</atom:updated>
            <content:encoded><![CDATA[<h3>3 Bit Analog to Digital Converter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1H66EbH2Sfj6MLwN1FQiw.jpeg" /></figure><p>An exercise in turning the analog input from a potentiometer into digital form.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLrvN16UWzd9EryeSAD-SocTLd7Eodnu2W&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dz3wcODP0M10&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fz3wcODP0M10%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a45fc8c3f80cce98ec9d12833a0998e/href">https://medium.com/media/8a45fc8c3f80cce98ec9d12833a0998e/href</a></iframe><p>Instead of using a specialized, off the shelf ADC, this circuit uses operational amplifiers in open-loop to compare the voltage over the pot’s wiper to 7 pre-configured voltage levels produced by a resistor ladder.</p><p>If the pot’s voltage exceeds an op amp’s reference voltage, its output goes low. The output of these 7 op amps is then fed to an 8-to-3 priority line decoder that looks for the highest line with an active signal and turns that into a 3-bit binary number on its outputs.</p><p>The decoder used is the SN74HC148 which has inverted inputs and outputs, meaning that a low voltage is considered active and a high voltage inactive. Therefore, if input line 7 (MSB) is low, it represents the highest number and the binary value 7 is output (which is also inverted and so represented as “000”).</p><p>When the pot is turned all the way down and its voltage falls below that of the reference voltage of the 7th opamp (1.375v), all the opamps are active (a high voltage on their outputs), which is interpreted as inactive by the inverting line decoder.</p><p>Note that the lowest input line of the decoder is tied to ground so that we never have all input lines high. The line decoder translates 01111111 as zero (111 binary output), 10111111 as 1 (110 binary output), and 00000001 as 7 (000 binary output).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*znWKtIA2ZOjlSWJo.png" /></figure><p>Note that the resistor ladders are configured such that the variable domain is limited to the 1–4v range (so the pot starts at 1v and swings up to 4v), instead of the full 0–5v. This is because the LM324AN op amp does not offer rail-to-rail performance. So instead of feeding the op amps with a higher voltage power source, we instead shape the input values.</p><p>Components used:</p><ul><li>2x LM324AN Quad Operational Amplifier — <a href="http://www.ti.com/lit/ds/symlink/lm224.pdf">http://www.ti.com/lit/ds/symlink/lm224.pdf</a></li><li>1x SN74HC148 8-to-3 Line Priority Encoder — <a href="http://www.ti.com/lit/ds/symlink/sn74hc148.pdf">http://www.ti.com/lit/ds/symlink/sn74hc148.pdf</a></li><li>Loads of resistors</li></ul><p><em>Originally published at </em><a href="https://erikvanzijst.github.io/electronics/opamp.html"><em>https://erikvanzijst.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61427ca971b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Knight Rider LEDs Part 3 (Raspberry Pi)]]></title>
            <link>https://medium.com/@erikvanzijst/knight-rider-leds-part-3-raspberry-pi-c8b581ce21eb?source=rss-2f01e04f8696------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8b581ce21eb</guid>
            <category><![CDATA[knight-rider]]></category>
            <category><![CDATA[breadboard]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[cmo]]></category>
            <category><![CDATA[electronics]]></category>
            <dc:creator><![CDATA[Erik van Zijst]]></dc:creator>
            <pubDate>Sat, 19 Oct 2019 00:37:37 GMT</pubDate>
            <atom:updated>2019-10-19T00:43:30.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Et-MAbO8PqLXc1LA1aM6A.jpeg" /></figure><p>The same algorithm driving the LEDs as was hardwired with the 74HCxx ICs in the previous project <a href="https://medium.com/@erikvanzijst/knight-rider-leds-part-2-protoboard-8e199f14ee78">Knight Rider Part 2</a>, but implemented in 5 lines of Python on a Raspberry Pi running <a href="https://gpiozero.readthedocs.io/">pgiozero</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLrvN16UWzd9EryeSAD-SocTLd7Eodnu2W&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPsVcLdAyAcU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPsVcLdAyAcU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/da38f8ee32d2f59bc520c3d5fec9cf95/href">https://medium.com/media/da38f8ee32d2f59bc520c3d5fec9cf95/href</a></iframe><p>The code that drives the LEDs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1e4b345ee5f9d15f219924ada0f2d82/href">https://medium.com/media/e1e4b345ee5f9d15f219924ada0f2d82/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8b581ce21eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>