<?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 Manuel Bl. on Medium]]></title>
        <description><![CDATA[Stories by Manuel Bl. on Medium]]></description>
        <link>https://medium.com/@manuel.bl?source=rss-a254c232c895------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*H18Ei1XHCzV1SIg3.jpg</url>
            <title>Stories by Manuel Bl. on Medium</title>
            <link>https://medium.com/@manuel.bl?source=rss-a254c232c895------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:24:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manuel.bl/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[Calling Windows COM interfaces from Java — the easy and modern way]]></title>
            <link>https://medium.com/@manuel.bl/calling-windows-com-interfaces-from-java-the-easy-and-modern-way-3d2ca725bbed?source=rss-a254c232c895------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d2ca725bbed</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Manuel Bl.]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 15:27:38 GMT</pubDate>
            <atom:updated>2025-08-04T20:16:07.488Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java using Windows COM interfaces — the easy and modern way</h3><p>The Win32 API does not just consist of functions (like <a href="https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw"><em>CreateWindowEx</em></a>) but also of many COM interfaces. Using them from Java was a challenge until recently.</p><p>The <a href="https://en.wikipedia.org/wiki/Component_Object_Model">Component Object Model (COM)</a> is an object-oriented API exposing objects with member functions. An application can call the member functions to query the object and have it execute actions. But it cannot directly access any data in the object directly.</p><p>COM objects have a binary layout compatible with C++ objects. They can easily be called from C++.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bKxu9qKtJeUWX3f8D6W4fA.png" /><figcaption>COM object layout</figcaption></figure><p>From Java, it is a bigger challenge, even with the advent of Java’s <a href="https://docs.oracle.com/en/java/javase/24/core/foreign-function-and-memory-api.html">Foreign Function And Memory API</a> (FFM) in Java 22. It is a new Java API for calling native code. It will likely replace older technologies such as JNI and JNA.</p><p>To call a native (non-COM) method using FFM, several steps are required:</p><ul><li>look up the the function in the dynamic-link library (DDL)</li><li>create a method handle describing the arguments</li><li>call the method handle</li></ul><p>This binding code is often generated with <a href="https://docs.oracle.com/en/java/javase/24/core/call-native-functions-jextract.html"><em>jextract</em></a>. Unfortunately, <em>jextract</em> is of limited use for Windows APIs as it lacks support for several Windows-specific concepts, most notably COM interfaces.</p><p>Luckily, the <a href="https://github.com/manuelbl/WindowsApiGenerator">Windows API Generator</a> for Java will help here. It creates the Java code for dealing with COM objects and calling its member functions. (I’m the main author this open-source software.)</p><h4>Example Application</h4><p>Let us see it in action by creating a Java application that modifies the taskbar to show the progress of a long-running task. Windows offers the COM <a href="https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nn-shobjidl_core-itaskbarlist3"><em>ITaskbarList3</em></a> interface to do so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*l7zALJxYoGXoOh74otJCKw.png" /><figcaption>Taskbar button with progress indicator (rightmost application)</figcaption></figure><p>The main steps are:</p><ul><li>Create an <em>ITaskbarList</em> instance using <a href="https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cocreateinstance"><em>CoCreateInstance</em></a></li><li>Call the <a href="https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressstate"><em>SetProgressState</em></a> member function to start displaying progress in the taskbar button</li><li>Call the <a href="https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressvalue"><em>SetProgressValue</em></a> member function multiple times to update the progress while the long-running task is underway</li><li>Call the <a href="https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-itaskbarlist3-setprogressstate"><em>SetProgressState</em></a> member function to reset the taskbar button after the long-running task has finished.</li></ul><p>The full example application implements it as part of a Java Swing application. The long-running task is started when a button in the main window is clicked. While it is running, a progress bar below the application’s taskbar button displays the progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*gCA1RAIp3xueLMdwYhANUw.png" /><figcaption>Example application to start the long-running task</figcaption></figure><p>The full source code is available at <a href="https://github.com/manuelbl/WindowsApiGenerator/tree/main/examples/taskbar">https://github.com/manuelbl/WindowsApiGenerator/tree/main/examples/taskbar</a>.</p><h4>Generating the FFM code</h4><p>Windows API Generator is available as a Maven or Gradle plug-in. To use it, it is added to Maven’s <em>pom.xml</em> or Gradle’s <em>build.gradle</em> file. For Maven, it looks like this:</p><pre>  &lt;build&gt;<br>    &lt;plugins&gt;<br>      &lt;plugin&gt;<br>        &lt;groupId&gt;net.codecrete.windows-api&lt;/groupId&gt;<br>        &lt;artifactId&gt;windowsapi-maven-plugin&lt;/artifactId&gt;<br>        &lt;version&gt;0.8.0&lt;/version&gt;<br>        &lt;executions&gt;<br>          &lt;execution&gt;<br>            &lt;goals&gt;<br>              &lt;goal&gt;windows-api&lt;/goal&gt;<br>            &lt;/goals&gt;<br>            &lt;configuration&gt;<br>              ...<br>            &lt;/configuration&gt;<br>          &lt;/execution&gt;<br>        &lt;/executions&gt;<br>      &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>  &lt;/build&gt;</pre><p>In the same file, the COM interfaces, functions etc. to generate are declared. For Maven, it looks like this:</p><pre>            &lt;configuration&gt;<br>              &lt;comInterfaces&gt;<br>                &lt;comInterface&gt;ITaskbarList3&lt;/comInterface&gt;<br>              &lt;/comInterfaces&gt;<br>              &lt;functions&gt;<br>                &lt;function&gt;CoCreateInstance&lt;/function&gt;<br>                &lt;function&gt;CoInitializeEx&lt;/function&gt;<br>                &lt;function&gt;FindWindowW&lt;/function&gt;<br>                &lt;function&gt;FormatMessageW&lt;/function&gt;<br>                &lt;function&gt;GetModuleHandleW&lt;/function&gt;<br>                &lt;function&gt;LocalFree&lt;/function&gt;<br>              &lt;/functions&gt;<br>              &lt;constants&gt;<br>                &lt;constant&gt;TaskbarList&lt;/constant&gt;<br>              &lt;/constants&gt;<br>            &lt;/configuration&gt;</pre><p>To execute the plug-in, run mvn generate-sources or press the <em>Generate Sources</em> button in IntelliJ. In a Maven project, the generated code will be put in the target/generated-sources/windows-api folder (with Gradle, it’s build/generated-src/windows-api).</p><h4>Creating the COM Object</h4><p>Using the generated code, the Taskbar object can be created with <em>CoCreateInstance</em>. It takes the object’s GUID as the first parameter (TaskbarList()), and the interface’s IID as the fourth parameter (ITaskbarList3.iid()). These concepts are similar to Java where a class (specified by a GUID in COM world) can implement multiple interfaces (specified by an IID). Unlike Java, it is not possible to have a pointer to an object, just pointers to interfaces.</p><p>The returned native pointer (in the memory allocated by taskbarListOut) is then wrapped by a Java object called taskbarList.</p><pre>// create instance of ITaskbarList, requesting interface ITaskbarList3<br>var taskbarListOut = arena.allocate(ADDRESS);<br>hr = CoCreateInstance(TaskbarList(), NULL, CLSCTX.ALL, ITaskbarList3.iid(), taskbarListOut);<br>checkSuccessful(hr);<br><br>// Wrap instance in easy-to-use Java object<br>taskbarList = ITaskbarList3.wrap(taskbarListOut.get(ADDRESS, 0));</pre><p>taskbarList is of type ITaskbarList3, a generated Java interface:</p><pre>public interface ITaskbarList3 extends ITaskbarList2 {<br><br>    int SetProgressValue(MemorySegment hwnd, long ullCompleted, long ullTotal);<br><br>    int SetProgressState(MemorySegment hwnd, int tbpFlags);<br><br>    ...<br>}</pre><p>The actual interface implementation contains the Java FFM code to lookup the function pointer in the virtual function table and call it.</p><h4>Calling the COM Object</h4><p>Given this wrapped COM object, it is now straightforward to use it:</p><pre>// Initializes the taskbar list object. This method must be called before any other ITaskbarList methods can be called.<br>hr = taskbarList.HrInit();<br>checkSuccessful(hr);<br><br>// Enable display of progress<br>hr = taskbarList.SetProgressState(hwnd, TBPFLAG.TBPF_NORMAL);<br>checkSuccessful(hr);<br><br>for (int i = 0; i &lt; 100; i += 10) {<br>    // Set progress value<br>    hr = taskbarList.SetProgressValue(hwnd, i, 100);<br>    checkSuccessful(hr);<br><br>    // Sleep<br>    sleep(200);<br>}<br><br>// Disable display of progress<br>hr = taskbarList.SetProgressState(hwnd, TBPFLAG.TBPF_NOPROGRESS);<br>checkSuccessful(hr);</pre><p>This code does not look much different than the equivalent C++ code would.</p><p>Note that Windows API Generator automatically generated the TBPFLAG enumeration even though it was not explicitly configured. It does so for many data types used a function parameters.</p><h4>Reference Counting</h4><p>To manage the life-time of COM objects, reference counting is used. All COM objects implement <a href="https://learn.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-addref"><em>AddRef</em></a> to increment the count and <a href="https://learn.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-release"><em>Release</em></a> to decrement it. When the reference count reaches 0, the object will be destroyed.</p><p>Functions such as <a href="https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cocreateinstance"><em>CoCreateInstance </em></a>return an object with a reference count of 1. Thus, there is no need to call <a href="https://learn.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-addref"><em>AddRef</em></a>. But <a href="https://learn.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-release"><em>Release</em></a> needs to be called when the object is no longer needed. It is done in the finally block.</p><pre>} finally {<br>    if (taskbarList != null)<br>        taskbarList.Release();<br>}</pre><h4>Further Information</h4><p>More detailed information about Windows API Generator can be found on its <a href="https://github.com/manuelbl/WindowsApiGenerator">homepage</a>. This include details about the <a href="http://Windows API Maven Plugin">Windows API Maven Plugin</a> and the <a href="https://github.com/manuelbl/WindowsApiGenerator/blob/main/docs/gradle_plugin.md">Windows API Gradle Plugin</a>. And did you know that it does not just support calling COM objects but also implementing them in Java?</p><p><a href="https://medium.com/@manuel.bl/calling-windows-apis-wit-java-ffm-is-tricky-9e296dc40a37">Calling Windows APIs wit Java FFM is tricky</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d2ca725bbed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling Windows APIs wit Java FFM is tricky]]></title>
            <link>https://medium.com/@manuel.bl/calling-windows-apis-wit-java-ffm-is-tricky-9e296dc40a37?source=rss-a254c232c895------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e296dc40a37</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Manuel Bl.]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 15:26:21 GMT</pubDate>
            <atom:updated>2025-07-08T15:28:29.005Z</atom:updated>
            <content:encoded><![CDATA[<h3>Calling Windows APIs with Java FFM is tricky</h3><p>The <a href="https://docs.oracle.com/en/java/javase/24/core/foreign-function-and-memory-api.html">Foreign Function and Memory API</a> (FFM) is the new Java technology to call native code. It is surprisingly difficult to use for the Windows API as Windows uses concepts that challenge Java FFM and even more so <a href="https://docs.oracle.com/en/java/javase/24/core/call-native-functions-jextract.html"><em>jextract</em></a>.</p><p>Calling a native function requires several lines of code to set up and invoke the required method handle. As this code is tedious and error-prone, <em>jextract </em>was released along with Java FFM in Java 22. It generates code to call given native functions and access the associated native data structures. However, it is not helpful for the Windows API as it does not support crucial Windows API concepts. This is where <a href="https://github.com/manuelbl/WindowsApiGenerator">Windows API Generator</a> for Java comes to the rescue. It generates the special code needed for Windows. (I’m the main author of this open-source tool.)</p><h4>Challenge 1: Error Handling</h4><p>Windows API functions often return a value indicating if an error has occurred. If it did, the actual error code can be retrieved with <a href="https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror"><em>GetLastError</em></a>. Unfortunately, this does not work with Java FFM because the Java VM calls Windows function itself, which overwrite the error code. So Java FFM provides the <a href="https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/lang/foreign/Linker.Option.html#captureCallState(java.lang.String...)"><em>captureCallState </em></a>linker option to capture the error code.</p><p><em>jextract </em>cannot generate such function calls. However, Windows API Generator can. If a Windows API functions uses <em>GetLastError</em>, it will automatically add the call state argument as the first parameter. As an example, the function <a href="https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getvolumepathnamew"><em>GetVolumePathNameW </em></a>has the following signature (in C):</p><pre>BOOL GetVolumePathNameW(<br>  [in]  LPCWSTR lpszFileName,<br>  [out] LPWSTR  lpszVolumePathName,<br>  [in]  DWORD   cchBufferLength<br>);</pre><p>And the documentation states:</p><blockquote>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call <a href="https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror">GetLastError</a>.</blockquote><p>Windows API Generator generates a Java function with the following signature (note the first parameter):</p><pre>static int GetVolumePathNameW(<br>    MemorySegment lastErrorState,<br>    MemorySegment lpszFileName,<br>    MemorySegment lpszVolumePathName,<br>    int cchBufferLength<br>);</pre><p>The function can be used like so:</p><pre>try (var arena = Arena.ofConfined()) {<br>    MemorySegment errorState = arena.allocate(<br>            Linker.Option.captureStateLayout());<br><br>    String currentDirectory = new File(&quot;&quot;).getAbsolutePath();<br>    MemorySegment filename = arena.allocateFrom(currentDirectory, UTF_16LE);<br>    MemorySegment buffer = arena.allocate(JAVA_CHAR, 500);<br>    if (GetVolumePathNameW(errorState, filename, buffer, 500) == 0) {<br>        // call has failed<br>        int errorCode = getLastError(errorState);<br>        throw new IllegalStateException(getErrorMessage(errorCode));<br>    }<br><br>    String volumePath = buffer.getString(0, UTF_16LE);<br>    System.out.println(&quot;Volume path: &quot; + volumePath);<br>}</pre><p>getLastError() and getErrorMessage() are helper methods to extract the error code and to retrieve the full error message, respectively. The full source code can be found at <a href="https://github.com/manuelbl/WindowsApiGenerator/tree/main/examples/medium_story">https://github.com/manuelbl/WindowsApiGenerator/tree/main/examples/medium_story</a>.</p><p>The signature of both generated Java function and the native C function are displayed as a tooltip in the IDE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3H0ttpuDqUiGTADWusgaA.png" /><figcaption>IDE displaying function’s Java and C signature</figcaption></figure><p>The above example also shows a typical example of string handling. Before the call, a native string is allocated for the Java string (filename). Additionally, a buffer to receive the resulting native string is allocated. If the call is successful, the buffer content is converted to a Java string (volumePath).</p><h4>Challenge 2: String and GUID Constants</h4><p>The Windows API makes use of many non-integer constants using types like ANSI string, Unicode strings, GUIDs, PROPKEY. These constants are not accessible in the associated dynamic-link library (DDL). So neither Java FFM nor <em>jextract </em>can support them. If C or C++ is used, these constants are inserted into the application itself, using a combination of C macros and Microsoft specific compiler options.</p><p>Windows API Generator supports these constants. It generates the necessary Java FFM code to allocate and initialize them. In the below example, <a href="https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath"><em>SHGetKnownFolderPath </em></a>is called using the GUID constant <a href="https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid"><em>FOLDERID_CommonPrograms</em></a><em>:</em></p><pre>try (var arena = Arena.ofConfined()) {<br>    MemorySegment out = arena.allocate(ADDRESS);<br>    SHGetKnownFolderPath(FOLDERID_CommonPrograms(), 0, NULL, out);<br>    MemorySegment str = out.get(ADDRESS, 0)<br>            .reinterpret(1000, arena, Apis::CoTaskMemFree);<br>    String folder = str.getString(0, UTF_16LE);<br>    System.out.println(&quot;Common programs folder: &quot; + folder);<br>}</pre><p>The above code also shows a typical example of handling <em>out </em>parameters. A memory segment large enough to hold a pointer is allocated in native memory and passed to the Windows API function. After the function call, the pointer is retrieved from the memory segment.</p><p>The reinterpretcall is necessary to tell Java FFM that the pointer refers to a large memory area (1000 bytes is used). It is also used to register a cleanup function to deallocate the native memory when the arena is closed.</p><h4>Challenge 3: COM Interfaces</h4><p>The Windows API does not just consist of functions and associated data structured. Many APIs come in the form of COM interfaces. Windows API Generator fully supports them. But that is the content of another story:</p><p><a href="https://medium.com/@manuel.bl/calling-windows-com-interfaces-from-java-the-easy-and-modern-way-3d2ca725bbed">Calling Windows COM interfaces from Java — the easy and modern way</a></p><h4>Configuring Windows API Generator</h4><p>To generate the code, Windows API Generator must be configured and run. It is available as both a Maven and a Gradle plugin. Here, the use of the Gradle plugin is shown. In build.gradle (or build.kts), the plugin is added:</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &quot;net.codecrete.windows-api&quot; version &quot;0.8.0&quot;<br>}</pre><p>Then the plugin is configured (in the same file):</p><pre>generateWindowsApi {<br>    functions = [<br>            &quot;CoTaskMemFree&quot;,<br>            &quot;FormatMessageW&quot;,<br>            &quot;GetModuleHandleW&quot;,<br>            &quot;GetVolumePathNameW&quot;,<br>            &quot;LocalFree&quot;,<br>            &quot;SHGetKnownFolderPath&quot;,<br>    ]<br>    constants = [<br>            &quot;FOLDERID_CommonPrograms&quot;,<br>            &quot;FOLDERID_Desktop&quot;,<br>            &quot;FOLDERID_Programs&quot;,<br>            &quot;FOLDERID_PublicDesktop&quot;,<br>    ]<br>}</pre><p>The configuration lists the functions and constants the plugin should generate. It will additionally generate the data structures and enumerations used as function parameters.</p><p>To run the code generation, gradle generateWindowsApi is executed. Most actions to build the project will also execute this Gradle task automatically.</p><h4>Further Information</h4><p>On its <a href="https://github.com/manuelbl/WindowsApiGenerator">homepage</a>, you can find additional information about how to use Windows API Generator, including details about the <a href="https://github.com/manuelbl/WindowsApiGenerator/blob/main/docs/maven_plugin.md">Windows API Maven Plugin</a>, the <a href="https://github.com/manuelbl/WindowsApiGenerator/blob/main/docs/gradle_plugin.md">Windows API Gradle Plugin</a> and many <a href="https://github.com/manuelbl/WindowsApiGenerator?tab=readme-ov-file#example-projects">example projects</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e296dc40a37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[USB for Microcontrollers — Part 1: Basic USB Concepts]]></title>
            <link>https://medium.com/@manuel.bl/usb-for-microcontrollers-part-1-basic-usb-concepts-519a33372cc9?source=rss-a254c232c895------2</link>
            <guid isPermaLink="false">https://medium.com/p/519a33372cc9</guid>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[usb]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <dc:creator><![CDATA[Manuel Bl.]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 21:19:10 GMT</pubDate>
            <atom:updated>2020-10-01T21:19:10.885Z</atom:updated>
            <content:encoded><![CDATA[<h3>USB for Microcontrollers — Part 1: Basic USB Concepts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0h9aLiJ675tiV6k1" /><figcaption>Photo by <a href="https://unsplash.com/@vishnumaiea?utm_source=medium&amp;utm_medium=referral">Vishnu Mohanan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>USB is the most convenient choice to connect an MCU-based device with an application running on a laptop or desktop computer. This tutorial introduces the relevant USB concepts and implements two sample projects.</p><p>The sample projects consist of microcontroller firmware and code for a computer. A device driver is not required if done correctly. Follow along to learn how to do it.</p><ul><li>Part 1: Basic USB Concepts (this page)</li><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-2-firmware-167c4e6e5632">Part 2: Firmware</a></li><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-3-host-software-and-device-drivers-1aeb45191185">Part 3: Host Software and Device Drivers</a></li><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-4-handling-large-amounts-of-data-f577565c4c7d">Part 4: Handling Large Amounts of Data</a></li></ul><h3>Introduction to USB</h3><p>Before diving into a specific project, the basic concepts of USB need to be understood. USB is a versatile communication standard and has been enhanced with new features regularly. Today it covers a wide range of devices from low-speed devices like keyboards to high-speed devices like SSDs and cameras, can provide or source power at up to 100W, transfer high-resolution video signals, and all of this at the same time. With the new features, complexity has increased too. This tutorial focuses on a <em>full-speed USB 2.0 device</em>, the most relevant category for microcontrollers. For the most part, USB 2.0 concepts still hold for newer USB standards and thus are relevant beyond these examples.</p><h4>Host and Device</h4><p>USB defines two basic roles:</p><ul><li><strong>Host</strong>: The host is usually a desktop PC, server or laptop. It controls the USB communication and provides power to devices. It is usually possible to connect several devices to a host.</li><li><strong>Device</strong>: A device can be anything like a keyboard, printer, external disk, a microcontroller project etc. It is connected to a single host and responds to communication from the host.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKZm-penBkBkurZjOq9Ehw.png" /><figcaption>Host and devices</figcaption></figure><p>A device may not start communication; it may only transmit if asked by the host. The host will ask the device at least every millisecond if it has data to transmit.</p><h4>Endpoints</h4><p>Endpoints are the basis for communication between host and device. Each USB device offers one or more endpoints. Endpoints are <em>communication channels</em>. Each message sent over USB is addressed to or originates from a specific endpoint.</p><p>Each device offers at least endpoint 0, a <em>control endpoint</em>. A control endpoints exchanges control messages and is bidirectional. The host uses endpoint 0 to query descriptive information about the device and to configure it.</p><p>Another type of endpoints are <em>bulk data endpoints</em>. They are used to transfer large amounts of data and they are unidirectional. Bulk data endpoints implement data streams called <em>pipes</em>, i.e. it is a stream protocol and not a message protocol. Thus, there is no concept of message boundaries even though data streams are built upon a message protocol at a lower level.</p><p>In USB terminology, the endpoint direction is named from the host’s perspective. Thus, <em>IN</em> always refers to transfers from a device to the host and <em>OUT</em> always refers to transfers from the host to a device. This is confusing when implementing the firmware for a device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UosKyHfNti63_hMyOTADQQ.png" /><figcaption>IN and OUT direction</figcaption></figure><p>Overall, there are four endpoint types:</p><ul><li><strong>Control transfer</strong>: a low throughput endpoint for control information. It is used for querying device information and configuring the device.</li><li><strong>Bulk transfer</strong>: endpoint for transferring large amounts of data. It has low priority but can achieve high throughput by using all the bandwidth not needed for other types. It is used for serial data connection, data transfer for mass storage devices etc.</li><li><strong>Interrupt transfer</strong>: a low throughput endpoint with high priority for status updates. It is used for notifying about keystrokes on a keyboard, mouse movements etc.</li><li><strong>Isochronous transfer</strong>: a high priority, fixed bandwidth endpoint. It is used for transferring real-time data such as real-time audio.</li></ul><p>The tutorial projects will use control and bulk transfer endpoints, the two most common endpoint types.</p><h4>Interfaces and Configurations</h4><p>Interfaces group endpoints. Each endpoint belongs to a single interface. For example, if a device performs two functions, it could have two interfaces to describe which endpoint belongs to which function. Each device must have at least one interface.</p><p>Configurations describe settings or modes of a device, e.g. high-power and low-power configuration, regular mode and firmware update mode. The host selects a configuration and activates it. Only one configuration can be activated at a time. Each configuration will provide different interfaces and endpoints.</p><h4>Descriptors</h4><p>Descriptors describe a USB device. They provide information such as vendor, power requirements, supported protocols, configuration details, interface details and endpoint details. When a USB device is plugged in, the host will read the descriptors using the control transfer endpoint 0. Based on the descriptor information, it will decide how to make the device available on the host, e.g. which device drivers to activate.</p><p>The descriptor is a data structure organized hierarchically to represent the device, configuration, interface and endpoint details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-U0Wu4xVpK_1cjmOMU22w.png" /><figcaption>Hierarchical descriptor organization</figcaption></figure><p>Note all interfaces will have endpoint 0 as well even though it is not specified in the descriptor. Furthermore, configuration numbering starts at 1.</p><h4>Vendor and Product ID</h4><p>Among other things, the device descriptor contains the <em>vendor ID (VID) </em>and <em>product ID (PID)</em>, two 16-bit IDs. They will be essential later for connecting to the correct device from the host.</p><p>The <a href="https://www.usb.org/">USB Implementors Forum</a> assigns a unique vendor ID to an organization, which can then create products using the its vendor ID in combination with any product ID. Getting a vendor ID isn’t cheap: Either you pay an annual membership fee of USD 5,000 or reduced membership plus a one-time fee of USD 6,000.</p><p>For a private project or a project still under development, you can get away with using a yet unused vendor ID. Open-source projects can get a unique VID/PID combination from <a href="http://pid.codes/">http://pid.codes/</a> or from <a href="http://wiki.openmoko.org/wiki/USB_Product_IDs">Openmoko</a> for free.</p><p>Vendor and product IDs can be looked up in several places, e.g. <a href="https://www.the-sz.com/products/usbid/">https://www.the-sz.com/products/usbid/</a>. While vendor IDs are centrally managed by the USB Implementors Forum, product IDs can be freely assigned by each vendor. These databases collect them from different source but naturally have an incomplete picture of product IDs.</p><h4>USB Classes</h4><p>The device and the interface descriptor contain class information (divided into class, sub class and protocol). This information declares what functionality the device has and what protocol it uses to communicate (on top of bare USB). The host will then load the appropriate device driver.</p><p>Several classes are standardized. They include classes for keyboards, mice, printers, serial adapters, camera, external storage devices, microphones and loudspeakers. Most operating systems will provide device drivers for these classes out of the box. So, if such a device is plugged in, it will immediately work, independent of the vendor it is from.</p><p>If you have a device that would be useful if it was treated like a keyboard, an external disk etc., implement such a standardized protocol. However, this tutorial will show how to implement a custom protocol (called <em>vendor-specific</em> in the USB standard). Custom protocols make sense if the device is always used together with a specific application on the host that is able to speak this protocol.</p><p>There is much more to USB than can be covered in this tutorial. For a more detailed introduction, I highly recommend <a href="https://www.beyondlogic.org/usbnutshell/usb1.shtml">USB in a NutShell</a> and <a href="http://www.usbmadesimple.co.uk/">UBS Made Simple</a>.</p><p>Enough about the theory. Let’s get cracking…</p><p>→ <a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-2-firmware-167c4e6e5632">Part 2: Firmware</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=519a33372cc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[USB for Microcontrollers — Part 2: Firmware]]></title>
            <link>https://medium.com/@manuel.bl/usb-for-microcontrollers-part-2-firmware-167c4e6e5632?source=rss-a254c232c895------2</link>
            <guid isPermaLink="false">https://medium.com/p/167c4e6e5632</guid>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[usb]]></category>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[electronics]]></category>
            <dc:creator><![CDATA[Manuel Bl.]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 21:18:38 GMT</pubDate>
            <atom:updated>2020-10-02T15:55:32.354Z</atom:updated>
            <content:encoded><![CDATA[<h3>USB for Microcontrollers — Part 2: Firmware</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Nc-zDaj73iFRTlu" /><figcaption>Photo by <a href="https://unsplash.com/@lazycreekimages?utm_source=medium&amp;utm_medium=referral">Michael Dziedzic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this part, the firmware to turn an LED on a microcontroller board on and off is implemented. In contrast to the typical blink example, the program will run on a computer and send commands via USB to the MCU to control the LED.</p><p>This is part 2 of a 4 part series:</p><ul><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-1-basic-usb-concepts-519a33372cc9">Part 1: Basic USB Concepts</a></li><li>Part 2: Firmware (this part)</li><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-3-host-software-and-device-drivers-1aeb45191185">Part 3: Host Software and Device Drivers</a></li><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-4-handling-large-amounts-of-data-f577565c4c7d">Part 4: Handling Large Amounts of Data</a></li></ul><h4>Hardware</h4><p>For the device implementation, a microcontroller (MCU) with an integrated USB peripheral is needed. Such microcontrollers are offered by all major MCU manufacturer. For this tutorial, a STM32 Blue Pill is used. It is an inexpensive board with a STM32F103C8T6 MCU. Even if you are using another MCU, the major concepts shown in this tutorial still apply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Z8CGw19zm2Q6E50MfzVQw.jpeg" /><figcaption>STM32 Blue Pill</figcaption></figure><p>The board can be programmed via a serial connection or via the SWD debug port (the four pins on the short side of the board). It is strongly suggested to use SWD port as it is far more convenient, and it also enables on-device debugging. A debug adapter such as ST-Link or J-Link is required. Clones of ST-Link 2 adapter are available at very low cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkAIBGG5AkbmvOp80ur2Zw.jpeg" /><figcaption>ST-Link Debug Adapter (Clone)</figcaption></figure><h4>Firmware Tooling</h4><p>To implement the software, <a href="https://libopencm3.org/">LibOpenCM3</a> is used. The framework has an excellent USB implementation and is easy to use. Other options would have been the <em>STM32Cube</em> framework — unfortunately, its USB implementation is unnecessarily complex. The popular Arduino framework supports certain USB classes on some MCU boards but lacks good support for custom protocols.</p><p>For both example projects, both the LibOpenCM3 and the STM32Cube is given. But only the LibOpenCM3 code is discussed.</p><p>The project itself is set up with <a href="https://platformio.org/">PlatformIO</a>. It is recommended to use it as an extension in <a href="https://code.visualstudio.com/">Visual Studio Code</a>. All the code can be found in the <a href="https://github.com/manuelbl/usb-tutorial">usb-tutorial</a> GitHub repository.</p><h4>Blink Project</h4><p>The goal of the <em>Blink Project</em> is to have a blink program running on a laptop or desktop computer and controlling a LED on the Blue Pill board. In order to do so, the blink program sends commands over USB to the MUC board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jzdw2zYERyfUxyXZEMtVeQ.png" /><figcaption>Blink Project</figcaption></figure><p>In the project, the Blue Pill implements a USB device with endpoint 0 only. In addition to the required commands for device discovery and configuration, two custom commands are added:</p><ul><li>Turn LED on</li><li>Turn LED off</li></ul><p>Endpoint 0 is the control endpoint. It implements control requests. The format of the requests is given by the USB standard. It includes so called <em>vendor requests</em>, i.e. it includes a range of codes that can be used without interfering with the USB standard, not even with future enhancements. So the LED commands are implemented as vendor requests.</p><h4>USB Descriptor</h4><p>For such a simple project, the main implementation is to provide the descriptor. With LibOpenCM3, it consists of four elements (see <a href="https://github.com/manuelbl/usb-tutorial/blob/master/blinky-libopencm3/src/usb_descriptor.cpp"><em>usb_descriptor.c</em></a>):</p><ul><li>Device descriptor</li><li>Array of configuration descriptors</li><li>Array of interfaces</li><li>Array of interface descriptors</li></ul><p>All arrays have just a single element for this project. As endpoint 0 does not need to be declared, there is no array of endpoint descriptors. It will be needed in the next project.</p><p>Note that the interfaces are described in two separate arrays. This is specific to LibOpenCM3. It will combine it into a single level at run-time.</p><p>When studying the code, you will also note that strings are in a separate array. Within the descriptor, the index into the array is given. This is how the USB protocol works: strings are requested separately.</p><h4>USB Device Initialization</h4><p>The descriptor is required for the device initialization. Somewhat simplified, the code looks like so (also see <a href="https://github.com/manuelbl/usb-tutorial/blob/master/blinky-libopencm3/src/main.cpp"><em>main.cpp</em></a>):</p><pre>rcc_clock_setup_in_hse_8mhz_out_72mhz(); ❶</pre><pre>rcc_periph_clock_enable(RCC_USB); ❷<br>rcc_periph_reset_pulse(RST_USB); ❷</pre><pre>usb_device = usbd_init( ❸<br>    &amp;st_usbfs_v1_usb_driver,<br>    &amp;usb_device_desc,<br>    usb_config_descs,<br>    usb_desc_strings,<br>    sizeof(usb_desc_strings) / sizeof(usb_desc_strings[0]),<br>    usbd_control_buffer,<br>    sizeof(usbd_control_buffer)<br>);</pre><pre>usbd_register_set_config_callback(usb_device, usb_set_config); ❹</pre><pre>nvic_set_priority(NVIC_USB_LP_CAN_RX0_IRQ, 2 &lt;&lt; 6); ❺<br>nvic_enable_irq(NVIC_USB_LP_CAN_RX0_IRQ); ❺</pre><p>The MCU is configured for a main clock of 72 MHz including the required 48 MHz USB clock ❶ and the USB peripheral is enabled ❷. The main step is to initialize the USB device by a call to <em>usbd_init</em>, which takes the device descriptor, configuration descriptors and string array discussed above plus a buffer required for processing control requests ❸. Finally, the USB low priority interrupt is enabled ❺. (❹ will be covered later.)</p><h4>Registering and Handling Control Requests</h4><p>Handling all mandatory control requests is a major task. Fortunately, LibOpenCM3 takes care of it. For our project, two commands for turning the LED on and off need to be added.</p><p>Control requests have a fixed structure. Vendor specific request types (request type 2) may be used for custom purposes such as controlling an LED.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IEM1chtcnPdEWcrPCLNeYA.png" /><figcaption>Control requests for controlling LED</figcaption></figure><p>To handle a vendor specific request type, a <em>control callback</em> is registered. In the registration, the request type <em>vendor</em> and the recipient <em>interface</em> are specified. So the callback will only be call for these kind of requests (also see <a href="https://github.com/manuelbl/usb-tutorial/blob/master/blinky-libopencm3/src/main.cpp"><em>main.cpp</em></a>):</p><pre>usbd_register_control_callback(<br>    usbd_dev,<br>    USB_REQ_TYPE_VENDOR | USB_REQ_TYPE_INTERFACE,<br>    USB_REQ_TYPE_TYPE   | USB_REQ_TYPE_RECIPIENT,<br>    led_control<br>);</pre><p>The control callback cannot be registered when the USB device is initialized as all callbacks are removed when the device is configured. So it has to be registered when the device configuration is set. It is possible to register a callback for when the device configuration is set. So the setup looks like so:</p><ol><li><strong>Device initialization</strong>: register callback for setting configuration (see ❹ above)</li><li><strong>Set configuration callback</strong>: register callback for control request</li><li><strong>Control request callback</strong>: handle LED command</li></ol><p>Handling the control requests is straightforward: check the vendor specific request code and interface number and — if they match — turn the LED on or off. It they do not match, indicate that the next request handler can take care of it (also see <a href="https://github.com/manuelbl/usb-tutorial/blob/master/blinky-libopencm3/src/main.cpp"><em>main.cpp</em></a>):</p><pre>usbd_request_return_codes <strong>led_control</strong>(<br>    usbd_device *usbd_dev,<br>    usb_setup_data *req,<br>    uint8_t **buf, uint16_t *len,<br>    usbd_control_complete_callback *complete<br>) {<br>    if (req-&gt;bRequest == 0x33 &amp;&amp; req-&gt;wIndex == 0) {<br>        if (req-&gt;wValue == 0) {<br>            gpio_clear(GPIOC, GPIO13);<br>        } else {<br>            gpio_set(GPIOC, GPIO13);<br>        }<br>        *buf = nullptr;<br>        *len = 0;<br>        return USBD_REQ_HANDLED;<br>    }<br>    return USBD_REQ_NEXT_CALLBACK;<br>}</pre><p>The last piece for the USB code to work is to call <em>usbd_poll</em>, either from the USB low priority interrupt handler (as shown below) or frequently from the main loop.</p><pre>extern &quot;C&quot; void <strong>usb_lp_can_rx0_isr</strong>()<br>{<br>    usbd_poll(usb_device);<br>}</pre><h4>Test Device</h4><p>If the code is compiled, uploaded to the Blue Pill and the Blue Pill is connected to a computer via USB, it should be discoverable.</p><p>On a Mac, click <em>About This Mac</em> in the Apple menu, click <em>System Report…</em> and then select <em>USB</em> in the left column. It should display information about the device:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*DjARuATkuFHgC1MyUb1_EQ.png" /><figcaption>macOS System Report</figcaption></figure><p>On Windows, open <em>Device Manager</em> and expand <em>Universal Serial Bus devices</em>. It should show a device called <em>Blinky</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxlRKM8bSGVnkS-VmZXoHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*53x1js449QkwUdX2gxc3Dg.png" /><figcaption>Windows Device Manager and Driver Details</figcaption></figure><p>By double clicking, the <em>Properties</em> windows open. Click on <em>Driver</em> and <em>Driver Details</em> to open yet another window. It will show <em>winusb.sys</em> as the first driver. If you have ever used <em>Zadig</em> (a tool for installing and changing USB drivers) on the computer, it will have left it traces and the screens will look slightly different.</p><p>Now that the device is working, let’s move on to the host software…</p><p>→ <a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-3-host-software-and-device-drivers-1aeb45191185">Part 3: Host Software and Device Drivers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=167c4e6e5632" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[USB for Microcontrollers — Part 3: Host Software and Device Drivers]]></title>
            <link>https://medium.com/@manuel.bl/usb-for-microcontrollers-part-3-host-software-and-device-drivers-1aeb45191185?source=rss-a254c232c895------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aeb45191185</guid>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[usb]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[firmware]]></category>
            <dc:creator><![CDATA[Manuel Bl.]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 21:17:47 GMT</pubDate>
            <atom:updated>2020-10-02T15:55:26.865Z</atom:updated>
            <content:encoded><![CDATA[<h3>USB for Microcontrollers — Part 3: Host Software and Device Drivers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VnGkwm_Rx1R_HoVF" /><figcaption>Photo by <a href="https://unsplash.com/@tylerdaviaux?utm_source=medium&amp;utm_medium=referral">Tyler Daviaux</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>With device and firmware ready, this part implements the application running on a computer and communicating with the MCU — without writing device drivers.</p><p>This is part 3 of a 4 part series:</p><ul><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-1-basic-usb-concepts-519a33372cc9">Part 1: Basic USB Concepts</a></li><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-2-firmware-167c4e6e5632">Part 2: Firmware</a></li><li>Part 3: Host Software and Device Drivers (this part)</li><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-4-handling-large-amounts-of-data-f577565c4c7d">Part 4: Handling Large Amounts of Data</a></li></ul><h4>Python Preparation</h4><p>To have a cross-platform application running on Windows, macOS and Linux, Python is used. The easiest way to use it for this tutorial is to run it from PlatformIO. For USB communication, the <a href="https://github.com/pyusb/pyusb">PyUSB</a> module is needed. To install it, open a Python terminal from PlatformIO (<em>Command Palette…</em> / <em>Python: Create Terminal</em>) and run:</p><pre>pip install pyusb</pre><p>PyUSB builds upon the C library <a href="https://libusb.info/">libusb</a>. It needs to be installed too.</p><p>On macOS, make sure <a href="https://brew.sh/">Homebrew</a> is installed and run:</p><pre>brew install libusb</pre><p>On Windows, download the latest stable package (<em>libusb-1.0.nn.7z</em>), unpack it and copy <em>libusb-1.0.dll</em> (from <em>MS64\dll</em>) to a directory that is listed in the environment variable PATH.</p><p>On Linux, use your system’s package manager and install libusb-1.0–0, e.g.:</p><pre>sudo apt-get install libusb-1.0-0</pre><h4>Blink Program</h4><p>The Blink Program (see <a href="https://github.com/manuelbl/usb-tutorial/blob/master/blinky-host/blinky.py">blinky.py</a>) is straight-forward:</p><pre>import usb.core<br>import time</pre><pre>dev = usb.core.find(idVendor=0xcafe, idProduct=0xcafe) ❶</pre><pre>dev.set_configuration() ❷</pre><pre>led_on = False<br>while True:<br>    led_on = not led_on<br>    dev.ctrl_transfer(bmRequestType=0x41, bRequest=0x33, \<br>        wValue=int(led_on), wIndex=0) ❸<br>    time.sleep(0.6) ❹</pre><p>First, the device is located ❶. To find the correct device among all connected USB devices, the vendor and product ID are specified. Then the first configuration is activated ❷. The first configuration in the USB device descriptor is the default, so no argument is needed in the call to <em>set_configuration</em>.</p><p>Now the <em>blink</em> loop starts: It mainly consists of sending the control request to turn the LED on or off ❸ and a delay ❹. The control request uses the parameters described in the previous part.</p><p>That’s it. If you run <a href="https://github.com/manuelbl/usb-tutorial/blob/master/blinky-host/blinky.py">blinky.py</a> from PlatformIO (using the green arrow in the top right corner), the green LED on the Blue Pill should blink. To stop it, press Ctrl+C in the terminal.</p><h4>What about Device Drivers?</h4><p>On macOS and Linux, device drivers for USB devices are not an issue. A full set of drivers for all standardized USB classes such keyboard, mouse, camera, external disk etc. exists, and there is a generic driver for all other USB devices. <em>libUSB</em> — and <em>pyusb</em> for that matter — use the generic driver to talk to the USB device.</p><p>Software accessing USB devices runs in user-mode. No privileged (kernel-mode) software is needed except for the device drivers provided by the operation system. And there is no need to write device drivers. It is straight-forward and without surprises.</p><p>Windows is different. It has device drivers for all standardized USB classes as well and uses them automatically. It even has a generic driver, but it does not use it automatically: it needs to be installed. But why did it work on Windows too — without manually installing any drivers?</p><p>The generic driver is called <a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/winusb">WinUSB</a>. Similar to macOS and Linux, it allows to user-mode software to talk to USB devices directly. However, it must be installed explicitly.</p><p>To do so, there are three options:</p><ol><li>Provide <em>.inf</em> files so the user can run the installation manually.</li><li>Use a software like <a href="https://zadig.akeo.ie/">Zadig</a> to install it manually.</li><li>Implement the Windows Compatible ID (WCID) extension on the device so Windows installs the WinUSB driver automatically when the device is first plugged in.</li></ol><p>In this project, the WCID extension has been implemented as it is the only one providing a real <em>plug-and-play experience</em>. At the minimum, it consists of two parts:</p><ol><li>An additional string in the USB device descriptor.</li><li>A vendor specific USB control request.</li></ol><p>It is described in detail on the excellent <a href="https://github.com/pbatard/libwdi/wiki/WCID-Devices">WCID Devices</a> web page. The implementation can be found in the <a href="https://github.com/manuelbl/usb-tutorial/blob/master/blinky-libopencm3/src/wcid.cpp">wcid.cpp</a> file. It can be reused without any changes in other projects. To activate it, <em>register_wcid_desc()</em> must be called from the <em>set_config</em> callback.</p><p>Blinking an LED is a simple example. Let’s move on to a more challenging example — sending an image to a TFT display connected to the MCU…</p><p>→ <a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-4-handling-large-amounts-of-data-f577565c4c7d">Part 4: Handling Large Amounts of Data</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aeb45191185" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[USB for Microcontrollers — Part 4: Handling Large Amounts of Data]]></title>
            <link>https://medium.com/@manuel.bl/usb-for-microcontrollers-part-4-handling-large-amounts-of-data-f577565c4c7d?source=rss-a254c232c895------2</link>
            <guid isPermaLink="false">https://medium.com/p/f577565c4c7d</guid>
            <category><![CDATA[usb]]></category>
            <category><![CDATA[firmware]]></category>
            <category><![CDATA[stm32]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[microcontrollers]]></category>
            <dc:creator><![CDATA[Manuel Bl.]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 21:16:42 GMT</pubDate>
            <atom:updated>2020-10-02T15:55:17.698Z</atom:updated>
            <content:encoded><![CDATA[<h3>USB for Microcontrollers — Part 4: Handling Large Amounts of Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FaMqq3cHqQRpnzPB5ynj7A.jpeg" /></figure><p>To demonstrate handling large amounts of data, an image is sent from the computer via USB to the device and displayed on a display.</p><p>This is part 4 of a 4 part series:</p><ul><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-1-basic-usb-concepts-519a33372cc9">Part 1: Basic USB Concepts</a></li><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-2-firmware-167c4e6e5632">Part 2: Firmware</a></li><li><a href="https://medium.com/@manuel.bl/usb-for-microcontrollers-part-3-host-software-and-device-drivers-1aeb45191185">Part 3: Host Software and Device Drivers</a></li><li>Part 4: Handling Large Amounts of Data (this part)</li></ul><p>The display and the MCU are connected via SPI (and additional control lines):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lEEdiKFxaPau2j3fPBNkxA.png" /><figcaption>Display Project</figcaption></figure><p>The challenges are:</p><ol><li>The display’s SPI interface is slower than the USB connection.</li><li>The image does not fit into the device’s main memory.</li></ol><p>To address challenge 2, the image data is sent to the display as soon as an entire pixel row is ready.</p><p>For challenge 1, <em>flow control</em> is needed, i.e. the USB device needs to be able to tell the computer to stop sending data until the device is capable of accepting more data. A buffer for 4-pixel rows is used. It is the maximum amount of data the MCU will buffer temporarily.</p><h4>USB Flow Control</h4><p>To transfer large amounts of data via a USB connection, <em>bulk endpoints</em> are used. They get the bandwidth not used by other types of endpoints, i.e. they have low priority but usually get a lot of bandwidth. Best of all: they have built-in error handling (retransmission of corrupted data) and they have flow control.</p><p>If the computer (in its role as USB host) has a large amount of data to send, it will split it into packets of 64 bytes (for USB full speed) and send each packet separately. The USB device will immediately respond with a short message to each packet:</p><ul><li><strong>ACK</strong>: An <em>acknowledged</em> message confirms the successful receipt of a packet. The device will process the received data, and the computer will send the next packet.</li><li><strong>NAK</strong>: A <em>not acknowledged</em> message indicates that the packet was correctly received but not accepted because the endpoint buffer is not empty as the device is still processing the previous packet. The computer will resend the packet later and continue trying until the packet is accepted or the operation times out.</li></ul><p>There are further responses for error cases that are described in more detailed USB introductions. For flow control, <em>ACK</em> and <em>NAK</em> are relevant. They are the way to inform the USB host whether data can be accepted or not and thereby control the speed of transmission.</p><h4>USB Peripheral Design</h4><p>In order to understand how ACK and NAK responses can be controlled, a basic understanding of the MCU architecture and in particular the USB peripheral is required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzQYj6LQru3u5Mjfw2VZ7w.png" /><figcaption>USB Peripheral</figcaption></figure><p>An MCU consists of a CPU, flash and RAM memory and several peripherals like UART, SPI and USB. The USB peripheral takes care of many parts of the USB implementation: the electrical encoding and decoding of signals, the lowest level of the USB packet format, USB transactions etc. It is aware of the currently active endpoints and the difference between the endpoint types.</p><p>The CPU configures the USB peripheral by writing to USB registers, and it can read the current status from the USB registers. As many other peripherals, the USB peripheral can trigger interrupts.</p><p>USB transmission is so fast that the CPU cannot deliver byte by byte as it is possible for I2C, SPI or UART. Instead, the CPU needs to write an entire packet to a special memory area from where it is transmitted by the USB peripheral without further interaction with the CPU. Similarly, when a packet is received, the USB peripheral writes the packet data to this memory area. Within the USB memory area, there are separate sections for each configured endpoint.</p><p>In the above illustration, the memory area is labelled as <em>USB memory</em>. In an STM32 the memory area is called <em>PMA</em> (for <em>Packet Memory Area</em>). Other MCU might have a different name but they work in a very similar fashion.</p><h4>Receiving Data on a Bulk Endpoint</h4><p>In addition to transmitting or receiving an entire packet without CPU interaction, the USB peripheral will also immediately respond to a received packet. For error cases, the possible responses are given by the USB standard. Regarding flow control, the CPU will need to tell the USB peripheral ahead of time how to answer to the next received packet. It can be configured separately for each endpoint.</p><p>The typical flow for receiving data on bulk endpoints is:</p><ol><li>The CPU configures a bulk endpoint and sets it into the state <em>ready</em>. The USB peripheral can now receive a packet and will immediately respond with ACK.</li><li>Once a packet has been received, the USB peripheral switches the endpoint into the state <em>not ready</em>. If a further packet is received, the USB peripheral would discard it and respond with NAK.</li><li>The USB peripheral triggers an interrupt thereby informing the CPU that a new packet has been received.</li><li>The CPU processes the received data (or at least copies it from the USB memory to another memory area).</li><li>If the CPU is able to handle more data, it sets the endpoint into the state <em>ready</em> so the next packet can be received (leading to step 2). Otherwise it leaves it in the state <em>not ready </em>until it has processed the data and sets it into the state <em>ready</em> later.</li></ol><h4>Transmitting Data on a Bulk Endpoint</h4><p>Transmission is slightly simpler as flow control mainly affects the host side and is taken care of there:</p><ol><li>The CPU copies data for a single packet into the USB memory area and sets the endpoint into the state <em>ready</em>.</li><li>Once the host asks if the device has data to transmit on this particular endpoint, the USB peripheral will transmit the packet.</li><li>If the transmission succeeds, the endpoint is set into the state <em>not ready</em>. If the host ask again for data, the USB peripheral would respond with NAK indicating there is not data currently.</li><li>The USB peripheral triggers an interrupt to inform the CPU that the packet has been successfully transmitted.</li></ol><h4>Display Setup</h4><p>The project uses a color TFT display with a resolution of 128 by 160 pixels. It includes ST7735 controller and is operated with an SPI interface and with 16-bit colors. It is connected as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVt4z11WxpQpDr9xpEf3wg.png" /><figcaption>Display Connections</figcaption></figure><h4>Firmware</h4><p>The main idea of the firmware is to handle received data (pixels of the image) in the USB interrupt (resulting in the call of a registered callback function) and to add the data to a circular buffer. The main loop checks the circular buffer and whenever a full row of pixels is ready, it is sent to the display. The communication with the display can be found in <a href="https://github.com/manuelbl/usb-tutorial/blob/master/display-libopencm3/include/display.h"><em>display.h</em></a> and <a href="https://github.com/manuelbl/usb-tutorial/blob/master/display-libopencm3/src/display.cpp"><em>display.cpp</em></a>.</p><p>The USB descriptor now additionally contains an endpoint declaration (see <a href="https://github.com/manuelbl/usb-tutorial/blob/master/display-libopencm3/src/usb_descriptor.cpp#L37"><em>usb_descriptor.cpp</em></a>). The endpoint address is 1, the maximum packet size is 64 bytes — the maximum length for USB full speed bulk endpoints.</p><pre>static const struct usb_endpoint_descriptor comm_endpoint_descs[] = { {<br>    .bLength = USB_DT_ENDPOINT_SIZE,<br>    .bDescriptorType = USB_DT_ENDPOINT,<br>    .bEndpointAddress = 1,  // EP_DATA_OUT<br>    .bmAttributes = USB_ENDPOINT_ATTR_BULK,<br>    .wMaxPacketSize = 64,<br>    .bInterval = 0<br>} };</pre><p>In <a href="https://github.com/manuelbl/usb-tutorial/blob/master/display-libopencm3/src/main.cpp#L84"><em>usb_set_config</em></a> (called when the device configuration is selected), the endpoint is set up (instead of registering a callback for vendor calls):</p><pre>void <strong>usb_set_config</strong>(usbd_device *usbd_dev, uint16_t wValue)<br>{<br>    register_wcid_desc(usbd_dev);<br>    usbd_ep_setup(usbd_dev, EP_DATA_OUT, USB_ENDPOINT_ATTR_BULK,<br>        BULK_MAX_PACKET_SIZE, usb_data_received);</pre><pre>}</pre><p>As part of the setup, a callback is registered. The callback function is called when a packet has been received. Somewhat simplified the callback looks like so (see <a href="https://github.com/manuelbl/usb-tutorial/blob/master/display-libopencm3/src/main.cpp#L94"><em>usb_data_received</em></a>):</p><pre>void <strong>usb_data_received</strong>(usbd_device *usbd_dev, uint8_t ep)<br>{<br>    // retrieve USB data<br>    uint8_t packet[BULK_MAX_PACKET_SIZE];<br>    int len = usbd_ep_read_packet(usb_device, EP_DATA_OUT,<br>        packet, sizeof(packet));</pre><pre>    // copy data into circular pixel buffer<br>    buffer.add_data(packet, len);</pre><pre>    // check buffer: if less than 2 packets fit -&gt; NAK<br>    if (buffer.avail_size() &lt; MIN_FREE_SPACE)<br>    {<br>         usbd_ep_nak_set(usbd_dev, ep, 1);<br>    }<br>}</pre><p>This is the main part of flow control. <em>usbd_ep_read_packet</em> copies the data from USB memory to the specified buffer. It also set the endpoint into the state <em>ready</em>. After having copied the data to the circular buffer for pixel data, the code checks if there is space for another two USB packets. If not, the endpoint is set into the state <em>not ready</em>. (In STM32 MCUs, <em>ready</em> is called <em>VALID</em> and <em>not ready</em> is called <em>NAK</em>.)</p><p>The reason the code checks for 2 packets and not 1 is the unfortunate fact that LibOpenCM3 sets the endpoint to <em>VALID</em> in <em>usbd_ep_read_packet</em>. So there is small window between setting it to <em>VALID</em> and setting it to NAK when a next packet could arrive while the previous one is still being processed. To cater for it, it needs to be set to <em>NAK</em> earlier.</p><h4>Host software</h4><p>For the software, Python is used again. And additional module for handling images is required and needs to be installed:</p><pre>pip install pillow</pre><p>The Python code first reads the image from disk and converts it into a byte array of 16-bit pixels in RGB565 format. Locating the device and selecting the default configuration is the same as in the first example. Sending the data is even simpler: a single call to <em>write</em> with the entire byte array is sufficient (2000 is the timeout in ms):</p><pre>DATA_EP = 1</pre><pre># load image<br>im = Image.open(&quot;parrot.png&quot;)<br>pixels = convert_rgb565(im)</pre><pre># find device<br>dev = usb.core.find(idVendor=0xcafe, idProduct=0xceaf)<br>if dev is None:<br>    raise ValueError(&#39;Device not found&#39;)</pre><pre># set configuration<br>dev.set_configuration()</pre><pre># send pixel data<br>dev.write(DATA_EP, pixels, 2000)</pre><p>The array is 128 × 160 × 2 bytes = 40,960 bytes long. The single call to <em>write</em> exemplifies the strength of bulk endpoints and the underlying implementation in today’s operating systems. They take care of splitting the data into packets (64 bytes in our cases) and sending it to the USB device at the speed the device is capable of handling.</p><p>It also shows that a bulk endpoint implements a data stream and is not message oriented like a control endpoint. Even if the Python code would call <em>write </em>for every single byte, it would still look more or less the same on the device side: it would mostly receive 64-byte packets. This is because the computer can and will merge data in its buffers.</p><p>I hope the tutorial was helpful and will help you to implement a great device with USB communication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f577565c4c7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arduino In-circuit Debugging with PlatformIO]]></title>
            <link>https://medium.com/@manuel.bl/arduino-in-circuit-debugging-with-platformio-9f699da57ddc?source=rss-a254c232c895------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f699da57ddc</guid>
            <category><![CDATA[platformio]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Manuel Bl.]]></dc:creator>
            <pubDate>Sun, 18 Aug 2019 15:58:39 GMT</pubDate>
            <atom:updated>2020-09-06T07:59:47.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTu-Jd6HVVxZuWozOzz0BA.png" /></figure><p>Some Arduino boards have debugging signals exposed on the bottom side. With an inexpensive adapter you can start using the <a href="https://platformio.org/">PlatformIO</a> debugger — a tool far more powerful than <em>print</em> statements to track down bugs in your software.</p><h4>The Board</h4><p>The <a href="https://store.arduino.cc/nano-33-iot">Arduino Nano 33 IoT</a> is a recently released Arduino board. It comes in the typical <em>Nano</em> form factor and offers unique features: powerful Atmel SAMD21 micro controller, Bluetooth, WiFi, crypto chip and a 6 axis IMU (acceleration and gyroscope).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*pTqz3eEEjLxZqLTX5NO4zg.png" /><figcaption>Arduino Nano 33 IoT</figcaption></figure><p>What really caught my attention were the exposed pads on the bottom side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*5Z9wO3GAePNpgorcKB9hEw.png" /><figcaption>Bottom side of Arduino Nano 33 IoT</figcaption></figure><p>These aren’t just test points. They are debug signals. And for the first time, they are described on the <a href="https://store.arduino.cc/nano-33-iot">Arduino web site</a> (see last section of technical specification).</p><p>The description is confusing though. So here is a visual pinout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vs7_ZcXzO_NqdjOzG4MjVw.png" /><figcaption>Debug port pads</figcaption></figure><p><em>SWD</em> and <em>SWCLK</em> are the relevant signals: they are a debug port called <a href="https://developer.arm.com/architectures/cpu-architecture/debug-visibility-and-trace/coresight-architecture/serial-wire-debug">Serial Wire Debug</a> (abbreviated as SWD), available on all ARM-based micro controllers. And the Atmel SAMD21 is ARM-based of course. The remaining signals are less important as they are also available as regular pins.</p><h4>The Debug Adapter</h4><p>There are plenty of debug adapters available for <em>Serial Wire Debug</em> or<em> SWD</em>. I have used a J-Link adapter from uncle Ali for about USD 12.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p27DcxvoMU0TG_g9ZHJgUQ.png" /><figcaption>J-Link Debug Adapter</figcaption></figure><p>The adapter is a clone of <a href="https://www.segger.com/products/debug-probes/j-link/">Segger J-Link Debug Probes</a>. Many clones even carry the Segger logo although they are not a genuine product. Several variants are available and difficult to distinguish. This is the least expensive one, and it worked.</p><h4>Connecting the Adapter</h4><p>In order to connect the Arduino board to the debug adapter, wires need to be soldered to the debug pads. I’ve soldered wires to all five of them but in the end did not use the <em>3.3V</em> wire. The <em>GND</em> and <em>RST</em> pins can also be soldered to regular pins, or if you have a board with headers pins, just connect them to the header pins. The minimum are the <em>SWD</em> and <em>SWCLK</em> wires.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExeAezh0n6Mu_QFIptPLZw.png" /><figcaption>Wires soldered to the debug port</figcaption></figure><p>I then crimped Dupont connectors onto the other end of the wires. You can also start with ready-made Dupont wires, cut off the connectors on one side and solder them to the board.</p><p>The wires need to be connected to the J-Link adapter to the following pins:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTSijOoeamIcw8xixIKn0Q.png" /><figcaption>J-Link Pinout for Serial Wire Debug (SWD)</figcaption></figure><p>The <em>SWD</em> pin is called <em>SWDIO</em> here as this is the official J-Link label. It is sufficient to connect as single <em>GND</em> pin. The <em>3.3V</em> wire is not connected as the board will be powered via USB.</p><p>Dupont connectors can be directly plugged onto the J-Link pins. I have used an intermediate adapter board as it simplifies plugging and unplugging the adapter. The pinout is the same.</p><h4>Debug Your Program</h4><p>If everything is plugged in (J-Link to computer, Arduino board to computer, Arduino board to J-Link), debugging with <a href="https://platformio.org/">PlatformIO</a> can start. J-Link is not the default debugger for the Arduino Nano 33 IoT. Therefore, the <strong>debug_tool</strong> needs to be specified in <strong>platformio.ini</strong>:</p><pre>[env:nano_33_iot]<br>platform = atmelsam<br>board = nano_33_iot<br>framework = arduino</pre><pre>debug_tool = jlink</pre><pre>lib_deps =<br>    Arduino_LSM6DS3</pre><p>The example program (<strong>main.cpp</strong>) reads gyroscope values from the IMU and prints them to the serial port:</p><pre>#include &lt;Arduino.h&gt;<br>#include &lt;Arduino_LSM6DS3.h&gt;</pre><pre>void setup() {<br>    Serial.begin(9600);</pre><pre>    // Wait for serial connection to be ready<br>    while (!Serial);</pre><pre>    if (!IMU.begin()) {<br>        Serial.println(&quot;Failed to initialize IMU&quot;);<br>        while (1);<br>    }<br>    <br>    Serial.print(&quot;Gyroscope sample rate = &quot;);<br>    Serial.print(IMU.gyroscopeSampleRate());<br>    Serial.println(&quot; Hz&quot;);<br>    Serial.println();<br>    Serial.println(&quot;Gyroscope in degrees/second&quot;);<br>    Serial.println(&quot;X, Y, Z&quot;);<br>}</pre><pre>void loop() {<br>    float x, y, z;<br> <br>    if (IMU.gyroscopeAvailable()) {<br>        IMU.readGyroscope(x, y, z);<br>        <br>        Serial.print(x);<br>        Serial.print(&quot;, &quot;);<br>        Serial.print(y);<br>        Serial.print(&quot;, &quot;);<br>        Serial.println(z);<br>    }<br>}</pre><p>To start debugging, go to the debug view (1), select the <em>PIO Debug</em> configuration of your project (2) and click the arrow icon next to it (3). It will take a moment to compile your code again and start the debugger in the background. Then your program is started and immediately stopped in the <em>main</em> function in another <em>main.cpp</em> file (4):</p><figure><img alt="PlatformIO debugging session: debug view, configuration selection, start, first breakpoint" src="https://cdn-images-1.medium.com/max/1024/1*5E3F-E9eHtJ6APNIjEJDBg.png" /></figure><p>You can then open your own main.cpp file and set a breakpoint by clicking next to the line number (1). A small red dot will appear. The blue array icon (2) continues the execution. The program will then likely be stuck at the check for the serial connection (3). To unlock it a serial terminal program needs to connect to the Arduino board, e.g. by running PlatformIO’s <em>Serial Monitor</em>. The program will run to your breakpoint and stop again. By clicking the arrow button again, the program completes an iteration of the <em>loop</em> function and again stops at the breakpoint in the next iteration.</p><figure><img alt="PlatformIO debug session: breakpoint, continue execution, serial connection check, variable inspection" src="https://cdn-images-1.medium.com/max/1024/1*rEM_ey5xKHPmX8CAvuhdiA.png" /></figure><p>Variables can easily be inspected in the debugger’s <em>Variables</em> view (4). There is no need anymore for adding <em>print</em> statements and recompiling your program to analyze your program.</p><h4>Other Arduino Boards</h4><p>Two further Arduino boards expose their debug signals in exactly the same way as the Arduino Nano 33 IoT: <a href="https://store.arduino.cc/nano-33-ble">Arduino Nano 33 BLE</a> and <a href="https://store.arduino.cc/nano-33-ble-sense">Arduino Nano 33 BLE Sense</a>. They use a Nordic Semiconductor nRF52840 microcontroller and a new <a href="https://blog.arduino.cc/2019/07/31/why-we-chose-to-build-the-arduino-nano-33-ble-core-on-mbed-os/">Mbed OS based Arduino core</a>. This combination is now supported by PlatformIO (with a few hick-ups though).</p><p>Further Arduino boards can be connected to a debugger in the same way:</p><ul><li><a href="https://store.arduino.cc/mkr-wifi-1010">Arduino MKR WIFI 1010</a></li><li><a href="https://store.arduino.cc/mkr-gsm-1400">Arduino MKR GSM 1400</a></li><li><a href="https://store.arduino.cc/arduino-mkr-nb-1500">Arduino MKR NB 1500</a></li><li><a href="https://store.arduino.cc/mkr-wan-1300">Arduino MKR WAN 1300</a></li><li><a href="https://store.arduino.cc/mkr-wifi-1010">Arduino MKR WIFI 1010</a></li><li><a href="https://store.arduino.cc/arduino-mkrzero">Arduino MKR ZERO</a></li></ul><p>The debug pads are also on the bottom side but look slightly different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abhQQJlFb_KyO4Elb-FiWg.png" /><figcaption>Debug Port Pads on Arduino MKR Boards</figcaption></figure><p>Additional boards with exposed debug pads are available from Adafruit and SparkFun. They all have in common that they use an Atmel SAMD21 microcontroller.</p><p><strong>Happy debugging…</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f699da57ddc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low-cost ESP32 In-circuit Debugging]]></title>
            <link>https://medium.com/@manuel.bl/low-cost-esp32-in-circuit-debugging-dbbee39e508b?source=rss-a254c232c895------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbbee39e508b</guid>
            <category><![CDATA[platformio]]></category>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[Manuel Bl.]]></dc:creator>
            <pubDate>Sun, 07 Jul 2019 19:36:42 GMT</pubDate>
            <atom:updated>2019-08-23T22:02:10.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKYkpjDW9pSRiYoe9VcAVw.jpeg" /></figure><p>If you have experience in software development, then you’ve probably never liked the Arduino IDE. Arduino is a great ecosystem with an incredible number of libraries and a variety of supported boards. Yet the IDE lacks essential features such a code completion and immediate error checking.</p><p>Chances are you have already switched to <a href="https://platformio.org/">PlatformIO</a>, a modern IDE that adds the missing features while still retaining the simple Arduino model and the benefits of the huge ecosystem. If you haven’t done so yet, switch now because PlatformIO also allows you to debug your program directly on the device— a valuable feature that will take you to a new level of micro controller programming. The PlatformIO features relevant for makers are free — including debugging.</p><p>Not all boards are capable of being run under the control of a debugger. The <em>ATmega</em> is such an example. However, more powerful chips are — in particular the chips with an ARM core and the ESP32.</p><p>This is an instruction how to setup on-device debugging in PlatformIO for the ESP32. Three different adapters for debugging are shown, the least expensive one for <strong>USD 8</strong> including shipping.</p><p>The instructions assume that you have already installed PlatformIO (the version with Visual Studio Code) and have a working project that uploads and runs code on your ESP32 board.</p><h4>Debugging the ESP32</h4><p>In order to debug code on the ESP32, PlatformIO runs <a href="http://openocd.org/">OpenOCD</a> in the background. It’s an open-source on-chip debugger — hence the name. You don’t need to install it, PlatformIO will take care of it.</p><p>OpenOCD communicates with the ESP32 via the <a href="https://en.wikipedia.org/wiki/JTAG">JTAG</a> protocol and port. JTAG is an industry standard for communicating with the internals of a chip. JTAG uses the five signals (plus ground):</p><ol><li><strong>TDI</strong> (Test Data In)</li><li><strong>TDO</strong> (Test Data Out)</li><li><strong>TCK</strong> (Test Clock)</li><li><strong>TMS</strong> (Test Mode Select)</li><li><strong>TRST</strong> (Test Reset) optional.</li></ol><p>On the ESP32, the JTAG pins are GPIO pins at the same time. So during debugging, you cannot use them. They are:</p><ul><li>GPIO12 — TDI</li><li>GPIO15 — TDO</li><li>GPIO13 — TCK</li><li>GPIO14 — TMS</li></ul><p>The reset pin (TRST) is not fully supported by OpenOCD. Fortunately, it’s optional.</p><p>To connect OpenOCD to the ESP32, a <em>JTAG adapter</em> is needed. The JTAG adapter has a USB and a JTAG port, similar to a USB-to-Serial adapter. It is connected between your computer and the ESP32 board. The direct USB connection to the ESP32 board is still needed. So the overall setup looks like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJuEX1PLvvjcmD74AYB6Ag.png" /></figure><p>PlatformIO will upload the program using the <em>esptool.py</em> via the regular USB connection to the ESP32 board. The debugger uses the other connection that goes via USB to the JTAG adapter and then via the JTAG protocol to the ESP32 board.</p><h3>Adapter 1: ESP-Prog</h3><p>The <a href="https://github.com/espressif/esp-iot-solution/blob/master/documents/evaluation_boards/ESP-Prog_guide_en.md">ESP-Prog Board</a> is the official debugging board of Espressif, the designers of the ESP32 chip. The design is open source — schematic and PCB layout are <a href="http://espressif.com/en/support/download/documents?keys=Reference+Design">available publicly</a>. The boards can be bought from Ebay, Aliexpress and many local distributors and start at about <strong>USD 18</strong> including shipping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*4X6CUrGZx6GWY__Fkbucog.jpeg" /><figcaption>ESP-Prog board</figcaption></figure><h4>Connecting the board</h4><p>To debug your program, connect the JTAG and ground pins to the ESP32 boards, e.g. using Dupont wires. The JTAG pins can be found on the biggest connector on the board:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xspg-BAn-M5fLgsILqXNAw.png" /><figcaption>JTAG pins on the ESP-Prog board</figcaption></figure><p>Then connect both the ESP32 board and the ESP-Prog board via USB to your computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZxltUr2uVzxiB6VKYAjxg.jpeg" /><figcaption>ESP-Prog adapter connected to an ESP32 development board</figcaption></figure><h4>Driver management</h4><p>When you connect the ESP-Prog board, your computer will most likely detect it automatically, load a driver and create two virtual serial ports. The main chip on the board is a FTDI FT2232HL, a two channel USB-to-UART (and additional protocols) IC. So that’s the expected behaviour. Unfortunately, that’s not what’s needed for debugging. The serial driver prevents OpenOCD from using the JTAG pins. So it must be unloaded.</p><h4>Unload driver on macOS</h4><p>MacOS comes with a FTDI driver out of the box and it will create two serial ports named <em>/dev/cu.usbserial-00006014A</em> and <em>/dev/cu.usbserial-00006014B</em>. To unload the driver and get rid of the serial ports, run the following command in the terminal:</p><pre>sudo kextunload /Library/Extensions/FTDIUSBSerialDriver.kext</pre><h4>Unload driver on Windows</h4><p>On Windows, a tool called <a href="https://zadig.akeo.ie/">Zadig</a> is used to unload the driver. Download and run it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Llni7p8FrJhqhZ2R4HIsig.png" /><figcaption>Zadig for unloading the FTDI driver</figcaption></figure><ul><li>In the <em>Options</em> menu, check <em>List All Devices</em></li><li>Select <em>Dual RS232-HS (Interface 0)</em> from the main drop down</li><li>Click <em>Replace Driver</em></li></ul><p>The FTDI driver will be unloaded, and the WinUSB driver from Microsoft will be loaded instead. It’s a generic USB driver that gives applications full control over the USB communication with the device.</p><h4>Configuring your PlatformIO project</h4><p>Next go to your PlatformIO project and two lines to the project’s <em>platform.ini </em>file:</p><pre>debug_tool = esp-prog<br>debug_init_break = tbreak setup</pre><p>That’s it: setup completed. You’re ready for debugging.</p><h4>Start debugging your code</h4><p>In Platform IO / Visual Studio Code:</p><ul><li>Click the <em>Debug</em> icon on the left side to open the debugger view</li><li>Click the green <em>Start Debugging</em> button at the top to start your app with the debugger.</li><li>The debugger will automatically break (stop) the code at the beginning of the <em>setup()</em> function.</li><li>You can then set additional breakpoints by clicking left of the line number. A red dot will appear.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhb1YI47qF6l55qnYGF9yw.png" /><figcaption>Debugging in PlatformIO</figcaption></figure><p>For more instructions how to use the debugger, watch Andreas Spiess’ YouTube video <a href="https://www.youtube.com/watch?v=psMqilqlrRQ">Free Inline Debugging for ESP32 and Arduino Sketches</a>.</p><h4>Additional features of the ESP-Prog board</h4><p>The ESP-Prog board isn’t just a JTAG adapter. It also provides:</p><ul><li>RX/TX pins for serial communication (they can be used concurrently as the FT2232HL is a dual-channel chip),</li><li>a voltage regular that can provide 3.3V,</li><li>the typical circuitry to enable and reset the ESP32 chip via the DTR and RTS signals of the serial connection.</li></ul><p>None of these features are used in the above setup as they are already present on the ESP32 development board. They might be quite useful with a naked ESP32 module. But since there are not needed, a simpler board also works for debugging…</p><h3>Adapter 2: Generic FT2232HL Board</h3><p>As mentioned, the ESP-Prog board has a FT2232HL chip at its core. Most of the circuitry around it is for features that are not needed in this setup. So a generic FT2232HL board also works as a JTAG adapter. In fact, they are a drop-in replacement. They can be bought from Ebay and Aliexpress, starting at about <strong>USD 10</strong> including shipping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dm4hlaOVEW_UTY-_dNqQaQ.jpeg" /><figcaption>CJMCU FT2232HL board</figcaption></figure><p>The JTAG port is on the pins AD0 to AD3. So connect them to the ESP32 board like so:</p><ul><li>GPIO12 — AD1 (TDI)</li><li>GPIO15 — AD2 (TDO)</li><li>GPIO13 — AD0 (TCK)</li><li>GPIO14 — AD3 (TMS)</li><li>GND — GND</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qf6kO3QzYHyQGXFX88ZYMA.jpeg" /><figcaption>FT2232HL board (in dead bug style) connected to an ESP32 development board</figcaption></figure><p>That’s it. Everything else (unloading the FTDI driver, configuring the PlatformIO project etc.) is exactly the same as above.</p><h3>Adapter 3: Generic FT232H board</h3><p>There is yet another, even less expensive option: generic FT232H or FT232HL boards (L stands for lead-free). The FT232HL has the same features as the FT2232HL chip — except it hast just a single channel. The boards are available from Ebay and Aliexpress starting at <strong>USD 8</strong> including shipping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BKXAVIqrVKQMF47FwS0yNg.jpeg" /><figcaption>CJMCU FT232H board</figcaption></figure><p>The connections are the same as for the other generic FTDI boards:</p><ul><li>GPIO12 — AD1 (TDI)</li><li>GPIO15 — AD2 (TDO)</li><li>GPIO13 — AD0 (TCK)</li><li>GPIO14 — AD3 (TMS)</li><li>GND — GND</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFp4GlTwUSu1gz28omzspg.jpeg" /><figcaption>FT232H board (in dead bug style) connected to an ESP32 development board</figcaption></figure><p>Unloading the driver and extending <em>platform.ini</em> is the same as above. However, if you start the debugger, you will find that it reports an error because the device cannot be found:</p><pre>Error: unable to open ftdi device with vid 0403, pid 6010, description &#39;*&#39;, serial &#39;*&#39; at bus location &#39;*&#39;</pre><p>The hexadecimal numbers 0403 and 6010 are the USB vendor and product ID of the FT2232HL chip and OpenOCD looks for them. Unfortunately, the FT232H chip has the vendor/product ID 0403/6014 (also see <a href="https://www.the-sz.com/products/usbid/">USB ID Database</a>). That’s also visible in <em>Zadig on Windows </em>and in macOS’ <em>System Report</em> (accessible from <em>About This Mac</em>).</p><p>So an additional change is needed: The vendor/product ID have to be added to an OpenOCD configuration file. Open the file <em>esp32_devkitj_v1.cfg</em> in an editor. It can be found in the directory <em>packages/tool-openocd-esp32/share/openocd/scripts/interface/ftdi</em> within your PlatformIO installation. The typical installation directories are <em>/Users/username/.platformio</em> on macOS and <em>C:\Users\username\.platformio</em> on Windows.</p><p>Then add the vendor/product ID pair <em>0x0403 0x6014</em> as shown below in bold:</p><pre>#<br># Driver for the FT2232H JTAG chip on the Espressif DevkitJ board<br>#</pre><pre><br>interface ftdi<br>ftdi_vid_pid 0x0403 0x6010 0x0403 0x6014</pre><pre># interface 1 is the uart<br>ftdi_channel 0<br># just TCK TDI TDO TMS, no reset<br>ftdi_layout_init 0x0008 0x000b<br>reset_config none</pre><p>That’s it. Add the following lines to your project’s platform.ini (the same as for the other adapters) and start debugging:</p><pre>debug_tool = esp-prog<br>debug_init_break = tbreak setup</pre><h4>Platform Updates</h4><p>Every update of the <em>Espressif 32</em> platform within PlatformIO will reset the configuration file to its original state. So you will have to reapply the simple configuration change after every update.</p><p><strong>Happy coding and debugging…</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbbee39e508b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>