Coming Out of a $0.10 Shell – Semihosting on WCH RISCV MCUs

Continuing our exploration of embedded CI jobs, let’s delve into achieving a comprehensive test-runner for a tiny embedded MCU. Instrumenting a WCH MCU that costs just $0.10, breaking free from the confines of a 16KB flash and 2KB RAM.

I’ve previously discussed this remarkable chip in a prior blog post. It’s a highly economical 32-bit MCU with a RISC-V2A core and a treasure trove of handy peripherals. WCH took an inventive approach to the debug interface, eschewing the resource-heavy JTAG in favour of a space-efficient single-wire debug interface. A mere trio of jumper cables (VCC, GND, SWDIO) are all you need to run and program this chip.

Single Wire Debug Interface + Power
Single Wire Debug Interface + Power

However, there are challenges. The non-standard interface needs its own set of drivers and code. While WCH has shown openness to open-source ideals, they’ve forked their own version of OpenOCD to cater to their interface nuances. You’ll find this bundled with MounRiver Studio or as a standalone toolchain. A polite inquiry to their support usually garners the source code swiftly.

As of my current writing, the MounRiver Studio 1.8 port regrettably lacks semihosting support. In response, I’ve revived it for their interface. My sources reside here: I forked
Karl Palssons’ well-maintained WCH OpenOCD sources and seamlessly merged in the pivotal commits from WCH’s divergence from the mainline RISCV OpenOCD. I’ve also submitted a patch WCHs’ way, hoping it’ll find its place in the forthcoming release. A pull request to Karls’s repo is a work in progress too.

What is Semihosting?

Semihosting, an ingenious mechanism, bridges the gap between a microcontroller or processor and its host environment through debug calls. These calls unlock a realm of possibilities:

  • Debugging and Testing: Console input and status retrieval from the target.
  • I/O Mastery: Orchestrating file exchanges within the host system.
  • Code Crafting and Testing: When hardware drivers are still germinating in the early development phases, semihosting is an easy way to evaluate a target.
  • Logging: Robust logging and tracing capabilities.

Tom Verbeure has a comprehensive writeup and practical examples for another RISCV core that I encourage anyone to read too. The genesis traces back to ARM’s pioneering steps, with a fortunate twist: RISCV embraced ARM’s interface blueprint. Consequently, OpenOCD developers found themselves tasked with seamlessly extending the same support to RISCV as they did for ARM.

The main drawback of semihosting lies in its speed. It operates at considerably reduced speeds compared to specialized hardware interfaces like UART. This deceleration originates from the debugger’s polling loop. A break state is triggered in the RISCV to signal a host call. Typically, the debugger polls the target execution state in intervals of roughly 100ms or less. On ARM this is even worse since some architectures need to interrupt to call the debugger. This limits you to around tens of host calls per second. Each host call carries an ID and buffer pointer, necessitating data extraction by the debugger after acknowledging the target request. Consequently, for tasks as simple as outputting a character, the process becomes sluggish. Optimal utilization entails conducting substantial bulk transfers with each call.

Another drawback is that semihosting code should steer clear of production deployment. Depending on the core configuration, the code could encounter hard faults (absence of trap handler or trap support) or linger indefinitely due to an “ebreak” state in the absence of a debugger connection. This makes semihosting a prime choice for prototyping, debugging, and testing endeavors.

If your focus narrows to just console I/O, alternative projects are emerging that employ RISCV DMI data transfer registers for console output, as shown by Charles Lohr’s work showcased here. Unfortunately, the tooling seems confined to CH32V003 and lacks extensive testing or applicability across WCH’s broader product lines. Moreover, adopting this avenue sacrifices the array of automation and test capabilities intrinsic to OpenOCD. Though ongoing development holds the promise of resolving these challenges, this remains brimming with potential.

Implementing Console Output

The WCH’s RISC-V toolchain supports the standard C library. This implies seamless integration of familiar C functions akin to your desktop experience. Yet, unlocking their utility necessitates the establishment of underlying bindings, showcased in the source found here.

Regrettably, the standard library confines printf to character-based IO. However, optimizing performance leads us to printf_, a variant empowering block transfers, thereby accelerating the pace, as shown in the main function.

Where to go from here

In my professional realm, this technique is a staple for continuous integration testing. I employ a pyexpect script to monitor OpenOCD’s console output, complemented by a loopback telnet session for target management. This is particularly useful for automated software testing. Enter Unity, a sleek C-powered test runner tailor-made to accommodate a spectrum of resource-limited systems. The process of porting this to your application is simple: tweak the read and write functions for semihosting, and assess pass-fail criteria through scripting within OpenOCD. Moreover, you can easily tweak my CH32V003 sample’s versatility to file-based I/O with the host system.

Posted in Embedded, RISCV | Leave a comment

Embedded Continous Integration Made Easier

I often get asked how we test our production firmware. This is a conceptual overview of how this can be done for almost any complex embedded system without embarking on a very expensive hardware-in-the-loop setup. Some of this work is grounded in lessons learned in previous research that I did during my tenure at the University of Waterloo as PostDoc years ago.

Sample Continous Integration Setup with HIL
Sample Continous Integration Setup with HIL

Embracing Continuous Integration for Complex Embedded Systems is essential in today’s Agile world. It’s universally agreed upon that CI is crucial for bug-free products. However, automating code with hardware components can pose challenges. The decision between software-based testing (mock systems) and hardware-in-the-loop approaches becomes critical. Despite these complexities, the standard benefits persist: improved code quality, faster deployment, regression testing, and an efficient feedback loop during development.

For complex embedded systems, opting for hardware-in-the-loop testing is preferable. It offers a more realistic approach compared to software-based testing. While setting up the hardware may have initial overhead, it avoids the need for constant revisions of mock interfaces, which can introduce their own bugs and prove less reliable than the actual production or pre-production hardware. I have done this for many products currently on the market. This post provides a blueprint of how this can be done for a complex embedded system, such as our Bottlenose camera.

If you are a large corporation flush with cash and no considerations for extra overheads, call your National Instruments representative right now, if you’re more like my company, read on. Setting up a hardware-in-the-loop system shouldn’t be prohibitively expensive if your control and data interfaces to the real world are limited.

The camera has a GigE Vision interface and various client utilities (see GitHub) that run in Windows and Linux to support the camera. Our CI, shown in the above picture comprises

  1. Security Token to sign production software targeted for Microsoft operating systems
  2. The machine that tests the Microsoft platform targeted code
  3. A router managing concurrent access to the Entity-under-Test (EuT)
  4. The EuT: An open-frame Bottlenose Stereo assembly with a heatsink
  5. A debugger to directly flash production and test firmware
  6. A power control module.
  7. The machine that tests Linux-targeted code and does control all aspects of the CI

The significant enabler for having a local CI is GitHub. They permit local runners that can run as services or full console sessions on almost any platform that supports an operating system. GitHub has a comprehensive set of documentation to guide you to set one up. The idea is to script deployment, test, and execution in a manner that could work from a Linux console or Windows desktop session. Machines (2) and (7) have each a runner. You can set up the GitHub CI job dependencies in a way that the jobs are sequenced to allow for interaction between the EuT, Windows tests, and Linux tests.

The debugger (5) would be optional for hard-pressed companies that just want to execute pass-fail tests. However, since some elements only show on the CI, the system is set up in a manner that one could debug CI failures directly on the CI. Furthermore, most SoCs and microcontrollers have a device-firmware-update mode (DFU) that allows software deployment without a debugger. Further, if you use an ARM-based microcontroller or another architecture that supports Semi-Hosting, this could be your instrumentation interface for test orchestration as well. If you use a legacy platform or something that has no mature Semi-hosting interface yet (for example the RISCV series by WCH), use a debugger such as WCH-Link or Flyswatter2 that has an extra UART/RS232 interface. That interface can be used for unit-test instrumentation, you can directly integrate instrumentation points for the UART into your debugger footprint. This is shown in my reaction trainer prototype.

The module (6) provides power-stepping to the EuT. This is needed to frame the start and stop between different test phases and to recover a bad CI job. This module can be expanded with power-measuring capabilities for your application.

All CI machines and the EuT are on the same isolated physical network that is controlled by (3). Further to integrate the test machines with GitHub the machines use Wi-Fi to fetch the CI jobs from GitHub via the corporate Wi-Fi network.

We target all our executables to conform to Microsofts Extended Validation (EV). Most solutions that enable this require a physical access token in the form of a USB stick. Further complicating code-signing is the agent software and token reader that is specific to your brand of tokens. To avoid unauthorized access, some vendors prevent you from using the Microsoft Sign tool if you are not on a desktop session. That forced us to set up the Windows CI machine (7) in Kiosk mode. Further, if the CI machine ever needs to be debugged via a remote session it is paramount to reboot it after, such that the desktop session is restored. GitHub actions permit you to store secret keys as Action Secrets on an organizational or repository level, such that these never end up in code.

In terms of software, the entire orchestration is done in Python. For bare-metal firmware-based tests, we use Unity, for C++ on an operating system we use meson test with GoogleTest, and for Python unittest. All bare-metal and bootstrap code is instrumented via OpenOCD scripts. For ARM microcontrollers for example a Cortex-R4 bootstrap processor we have in our SoC, OpenOCD provides an excellent interface to use Semi-Hosting as for test instrumentation.

The Buts: “This is all nice and cute, but I have more serious issues, like…”

  • “But I have to simulate physical thing X”: The first question to ask yourself. Are you testing something like printf? Is there an actual value to simulate property X as opposed to mocking it from the debug interface (as discussed above)? If not read on …
  • “But I have analog interfaces on my EuT”: Look into emulating these from a low-cost platform. For example, the power-control module in my setup could be replaced by an Arduino with a DAC that drives your analog interfaces.
  • “But my analog interfaces measure physical properties directly”: Can you cheaply simulate the physical properties? Could you desolder your analog sensor and drive the analog sensor output from an Arduino? For an inertial measurement unit,
    can you build a fixture out of industrial automation equipment to test (see here for ideas)?
    For Image sensors, can you build fixtures at the focal range to detect (see here for example)?
  • “But I have RF interfaces that need testing”: Simulate another endpoint from the computer attached to your EuT.
    Can you simulate your RF protocol from a low-cost SDR?
    Can you implement non-PC-supported interfaces from a purpose-built embedded module? If your EuT is the only endpoint in your building for that protocol shielding may not be a concern. If it is a concern, you could look into building your own mini test-chamber,
    a good application note for this can be found here.
    Commercial solutions for these are also widely available or could be rented for the duration of the project.
  • “But running my test poses a safety hazard for human life:” Again, back to the first point. If that is still not an option, can you safety your test environment in a cage with light curtains and other human lockout measures? I actually was in that boat.
    We did work on drone autopilots for a big Canadian company.
    The EuT was a 100lbs heavy-lift drone. We actually build a cage with lockouts and secured the drone on a ball joint. However, these tests followed a manual script and didn’t make it into an automated continuous integration. The other big issue about such kinds of tests is EuT wear. While you might neglect or write off lower-cost EuTs due to issues like flash-endurance on a EuT replacement schedule, something like drones or welding robots might not be suited for all-in automated integration tests, which brings us back to the first point.
  • “But my device requires a human test subject in the loop:” Again going back to the first point. If that is not an option, you are likely doing something wrong. For medical devices, you are likely on a waterfall or V-shaped development process with set acceptance test gates. Human trials will be mandated at later stages and should not be considered at this stage. Joking, if that is not an option, haze your new hires. We did some work for a company that builds conductive energy weapons (your guess is likely right) years ago. In casual talks with some staff, they said it was part of their interview question. (Paraphrasing, so that corporate hints are left out): “Would you like to have the EuT tested on you?”. Most folks allegedly answered yes. The best answer I got was from a marketing chap. “Yes, after you pay me.” I kid you not, the story is that the CEO was waiting to sign their first paycheck. “I’m coming…”. Our work involved cameras, I later heard that the camera division was consolidated into a different unit from the “EuT” folks, my guess is, it was probably for talent acquisition reasons.
    But seriously, back to point one, there are probably documented procedures on the physical properties of a human test subject without an actual test subject in the loop.
  • “But my ‘but’ is not covered”: Leave a comment below …

This is a brief conceptual run-down of how a hardware-in-the-loop system can be set up without embarking on a significant instrumentation investment. Further by using local runners, you can allow for long-running complex CI pipelines without ever overrunning your GitHub minutes budget. If you have multiple product lines you can scale this setup as shown in a paper I published a few years ago. The source code from our CI is omitted to protect trade secrets. If you need help with your test setup, drop me a line. I’m open to consulting inquiries.

Posted in Coding, DevOps, Embedded, Linux, Windows | Leave a comment

IoT Contest Conclusion

I am delighted to present my final submission for the IoT contest. Throughout this journey, I have worked diligently to develop a reaction trainer prototype rivalling existing commercial solutions such as Blaze Pods. By leveraging the capabilities of the CH32V208W microcontroller, I have designed a custom PCB that incorporates a calibrated RF-fronted specifically engineered to support Bluetooth Low Energy (BLE) functionality. This achievement marks a significant milestone in developing a high-performance reaction trainer.

One of the notable outcomes of this project is the successful integration of WCH’s TMOS-based BLE stack into the RT-Thread operating system. This integration is crucial to enabling seamless communication and interaction between the sensor and various devices. While a final pull request for this integration is still pending, initial testing and implementation have showcased promising results, affirming the potential of this combined technology stack.

You can see the solution in action in the following Video.

Reaction Trainer in Action

Sources

The hardware design was discussed in my previous post here.

The following tools were used during the development process.

The Journey

The development was supported by listening to various contemporary Chinese Pop, KPop, JPop, City Pop, and classic rock songs. 🙂

I digress, please see the description of technical tooling used during the development below.

Firmware Development Process

Using Clion for RT-Thread Development
Using Clion for RT-Thread Development

Throughout the development process, I utilized JetBrains CLion as the primary tool for firmware development. Its comprehensive features and user-friendly interface provided an efficient and streamlined workflow. With CLion, I was able to write, compile, and debug the firmware code seamlessly, ensuring smooth progress throughout the project.

While the RT-Thread IDE showed promise, it lacked Linux support. Furthermore, it poses a challenge in integrating the BSP directly within the IDE. As a result, I had difficulty getting the BSP working within the RT-Thread IDE. However, I quickly adapted to the situation and decided to utilize command-line tools for development instead. This allowed me to overcome the limitations and continue working effectively on the project.

The entire application, including the firmware and RT-Thread configuration, was built using scons, a powerful build system. By leveraging scons –menuconfig, I was able to configure the RT-Thread operating system to suit the specific requirements of the project. This ensured optimal performance and seamless integration of the components.

To index the toolchain and build sources within JetBrains CLion, I made use of the compile_db feature. By incorporating the compile_db, I could effectively navigate and analyze the project’s source code, enhancing the development experience and facilitating efficient debugging. It was obtained using bear in Ubuntu.

Because of the challenges of getting the CH32V208 BSP setup in the RT-Thread IDE, I throughout the duration of the contest, took an active role in providing ample support and assistance to fellow contestants in setting up the BSP for the CH32V platform. By sharing my knowledge and expertise, I aimed to create a collaborative and supportive environment, fostering growth and success for all participants in the contest.

Hardware

Reaction Trainer Design in Kicad
Reaction Trainer Design in Kicad

The hardware design phase of the project was conducted using Kicad, an open-source electronic design automation (EDA) software. Despite the lack of vendor support for Kicad, I was able to overcome this challenge by referring to the provided reference sources in Altium Designer. To create the necessary footprints for the CH32V208 microcontroller, I utilized a sad electronics template as a foundation, customizing it to meet the specific requirements of my design. The Altium-based reference design was manually ported to Kicad, ensuring compatibility and tailored adjustments for my project’s needs. For more in-depth explanations of the various components and design details, please refer to my previous post.

Smart Phone Application (Android)

Android Application Development in JetBrains IntelliJ
Android Application Development in JetBrains IntelliJ

Developing the Android app for this project presented several challenges and learning opportunities. It had been almost a decade since I last worked on mobile development, and this marked my first experience with Bluetooth Low Energy (BLE) integration into a mobile application. The learning curve was steep as I had to familiarize myself with the GATT (Generic Attribute Profile) profile and device management within the Android platform.

To tackle the development process, I utilized JetBrains IntelliJ as my primary development environment. The IntelliJ IDE provided a robust and feature-rich toolkit for Android app development, facilitating a smooth workflow.

Considering the project timeline, the functionality of the Android app was kept relatively simplistic by modern standards. Given more time, I would have dedicated efforts towards refining and enhancing the user experience, incorporating additional features and optimizations.

Overall, the Android app development journey was a valuable learning experience, allowing me to reacquaint myself with mobile development practices while overcoming the challenges associated with BLE integration and GATT profile management.

The only platform the application was tested on was my phone, a Samsung Galaxy S20+.

Conclusion

One of the standout aspects of this project has been the impressive ease of use offered by the RT-Thread operating system. Its user-friendly interface and intuitive design have greatly contributed to the development process. It is truly remarkable to witness a POSIX-like operating system with such a small footprint perform exceptionally well, surpassing expectations in terms of efficiency and functionality.

The power and capabilities of the WCH CH32V-series have left a lasting impression. Despite their affordability, these microcontrollers pack a remarkable punch, offering impressive performance and versatility.

Looking ahead, I am excited to expand the application of this technology by producing more units for testing in martial arts practice at the club. The potential to incorporate these devices into real-world training scenarios holds great promise, and I am eager to witness the impact they can make in enhancing performance and skill development.

While there were a few aspects that didn’t go as planned, such as the initial intention to include an audio frontend that had to be omitted due to space constraints in the low-cost PCB manufacturing process, and the inability to bypass VBUS detection on the CH32V208, limiting the ability to redirect the RT-Thread console to USB-VCP, I was able to adapt and find alternative solutions. The CH32V208 BSP for RT-Thread also presented some challenges, particularly in integrating it with the RT-Thread Studio.

Based on the positive experience and successful outcomes of this project, I am seriously considering utilizing RT-Thread, which is permissible under the Apache 2.0 license, for other commercial applications. The reliability, flexibility, and potential for further innovation offered by RT-Thread make it an enticing choice for future ventures. Its robust performance and expansive capabilities make it a compelling option for a wide range of commercial projects.

Posted in Coding, Contest, Embedded, Linux, Martial Arts, RISCV, RT-Thread, WCH | Leave a comment

IoT Contest: Reaction Trainer Design

As always you find the design files on my GitHub.

Designing a sensor that meets the specific requirements of a particular application involves overcoming several hardware challenges. From creating a Printed Circuit Board (PCB) using Computer-Aided Engineering (CAE) software to carefully selecting the right components, every step in the design process is crucial. Additionally, designing for manufacturing adds another layer of complexity. In this blog post, we will delve into the intricacies of tackling these hardware challenges, exploring the essential considerations and techniques involved in crafting a successful sensor design.

Production PCB
Production PCB

The design of the sensor encompasses several key components, each playing a crucial role in its functionality and performance. These components include the microcontroller, power management system, visual feedback module, proximity sensing unit, and RF frontend. Ensuring the seamless integration of these components within a suitable enclosure presents a significant challenge. Considering that mechanical lead times often pose a bottleneck in the design process, a signal light was chosen as the ideal enclosure. In the subsequent paragraphs, we will delve into each of these sections individually, exploring their intricate details and considerations.

System Overview
System Overview

The Microcontroller


As a participant in the contest, I have made a deliberate choice to utilize the CH32V208W platform for my project. This platform features a 32-bit RISCV controller renowned for its affordability and versatility, offering a rich selection of peripheral interfaces to cater to a wide range of requirements. Specifically tailored for this contest, the essential peripherals I will be utilizing include an on-chip RF peripheral with a proprietary library, enabling seamless integration of the Bluetooth Low-Energy interface. Additionally, an I2C interface will be employed to connect an accelerometer, an ADC will facilitate power sensing, a USB connection will allow for factory flash and firmware upgrades, and additional pins will be allocated for driving high-power LEDs, providing comprehensive visual feedback. By leveraging the capabilities of the CH32V208W platform and carefully selecting the necessary peripherals, I aim to create an efficient and effective solution for this contest.

Reaction Trainer MCU Design
Reaction Trainer MCU Design

The presented diagram illustrates the essential circuitry encompassing the microcontroller. In the case of this particular chip, the requirements are relatively straightforward, consisting of a few stabilizing capacitors and external oscillators to ensure precise timing for both the USB and RF front end. While the chip does feature internal oscillators that could potentially enable autonomous operation, it remains imperative to incorporate at least one high-speed external oscillator to guarantee accurate timing for USB and RF functionalities. Although the inclusion of a 32768Hz oscillator is optional, I opted to adhere to the development kit specifications in order to mitigate any potential design risks. Once the debug interface is enabled via the WCH ISP tool, the debug connector no longer necessitates a reset line. The bootloader is activated by bridging BOOT0 to VCC or closing J2. It is worth noting that the chip is conveniently available in a QFN-68 package from LCSC. However, due to the challenging nature of hand soldering, I have decided to enlist the services of JLC-PCB to handle the entire assembly process, ensuring optimal results and reliability.

One issue that was not documented was the inclusion of the VINT capacitor for the internal regulator. The development kit at a 1uF capacitor. Since I am cheap and want to save on feeder setup fees, I added a 10uF capacitor instead to share volume across other parts of the design. Fingers crossed, this will work.

The RF Frontend for Bluetooth Low Energy

The above schematic shows antenna design and guestimated antenna matching. Nanjing Qinheng Microelectronics (WCH) provides guidance in Chinese on how to lay out an inverted F-antenna. I found a well-maintained library for several WCH footprints, including the antennas from Sad Electronics. I forked it to add schematic symbols for the CH32V208 and adapt the antenna footprints for existing Kicad schematic antenna symbols. Expect a merge request, once the design works. Infineon has a good application note on the design theory behind it. Putting the footprint in place is less than half the battle for RF design. The bigger challenge is calibrating the layout to the environment, as minuscule changes in the PCB dielectric or ground plane will throw the reference design out of calibration. Texas Instruments has a good application note for this. Because the ground plane next to the IFA section is critical I used this plugin to generate strips of vias in the plane.

The USB Interface

USB Interface
USB Interface

The USB interface is fairly straightforward. Since I do not require high-speed USB, I did not route the USB interface explicitly as differential pair and eyeballed it instead. Make sure you have ample ground-planes and around the trace pairs. This should be ok. To protect against accidental electronic discharge, I put a TVS array right behind the USB connector.

Power

Power Design

The power design for the sensor follows a relatively straightforward approach. To enable independent operation, a lithium polymer battery has been selected as the power source. Whenever the sensor is externally connected via USB, the battery is charged, and it directly supplies power to the high-power LEDs. Furthermore, the battery voltage is stepped down to 3.3V, which powers the microcontroller and other peripherals. It is important to note that this voltage dropout may not be ideal, considering that lithium batteries can discharge as low as 3.0V. However, this design decision was made to maintain consistency with the development kit and minimize deviations. In a future sensor revision, a significant reworking of this aspect is expected. To minimize battery discharge when the microcontroller is in low-power standby mode, an LDO (Low Dropout) regulator with a minimal quiescent current was carefully chosen, ensuring efficient power management.

Visual Feedback

Visual Feedback
Visual Feedback

For visual feedback to the user, a pair of high-power LED arrays was chosen. Since the microcontroller does not have the drive strength to drive the LEDs directly, the output is buffered using a 74573 logic buffer. This is a classic design from lost Intel 8051 days when microcontroller pins were in short supply, the logic latch can be enabled and disabled, freeing up the pins for other purposes. The 74HC logic levels permit a 3.3V logic input on one side and can drive higher voltages on the other side, making this a low-cost logic-level translator at the same time.

Motion Sensing

Motion Sensing
Motion sensing

Motion sensing is performed by an accelerometer from ST. The choice was essential fell on what is in stock and low-cost at LCSC. So I found this ST accelerometer that can interrupt the microcontroller when a certain acceleration (i.e. shock, smack…) is reached and provide haptic feedback to the user that a leg of their exercise routine has been completed.

Enclosure

Signal Light Enclosure
Signal Light Enclosure

Since I did not have the time to design a fully-fledged enclosure the PCB was designed to fit a signal light. The N-3071 line of signal lights provides a low-cost platform for the enclosure, even considering that you discard the original circuit. I tried to source lights that have a clear acrylic cover but could not source them in time.

Conclusion

This concludes the system overview of the electrical design of the sensor. I initially planned to include proximity sensing via an infrared distance sensor as well as audible feedback from an I2S amplifier and a speaker too, but I did not have enough space to route that out inside the chosen enclosure. In the next revision, these features may be added. The upcoming article will outline the software stack using RT-Tthread.

Posted in Contest, Embedded, Martial Arts, RISCV, RT-Thread, WCH | 1 Comment

IoT Contest – Next-Generation Reaction Trainer using RISCV and RT-Thead

I have been following Nanjing Qinheng Microelectronics (WCH) for a while. They have a very interesting line-up of low-cost RISCV microcontrollers with a lot of different connectivity options that rival big shots like ST or NXP. A couple of weeks ago I saw Patrick Yang advertising the RT-Thread IoT contest.

Although my experience with the CH32 lineup and RT-Thread is limited, I saw this as an excellent opportunity to revive my microcontroller and Bluetooth skills outside of my current work in Toshiba vision SoCs. I discovered this IoT contest when I was recovering from an ankle injury and searching for ways to restore explosive movements and fast-twitch muscles. My research led me to BlazePod, a reaction training system that measures reaction time based on vibration or tap input and provides feedback through haptic and LED indications. While this system is great, it lacks non-contact proximity sensing, making it unsuitable for movement drills in martial arts or non-contact reaction drills. I believe addressing this limitation could open up new applications for rehabilitation or even military training.

Reaction Trainer Concept
Reaction Trainer Concept

Next-Generation Interactive Fitness and Sports Training Device Proposal

We propose the development of a cutting-edge interactive fitness and sports training device that leverages innovative hardware and software technologies to enhance physical performance, cognitive skills, and reaction times. This device aims to provide a versatile and engaging training experience for athletes, coaches, fitness enthusiasts, and individuals in rehabilitation or physical therapy settings.

Objectives: The main objectives of the proposed device are as follows:

  1. Improve Physical Performance: The device will offer a range of customizable training programs, exercises, and drills that challenge agility, speed, strength, and coordination, aiming to enhance overall physical performance in various sports and fitness activities.
  2. Enhance Cognitive Skills: The device will incorporate neurocognitive training modes that target cognitive skills such as reaction time, decision-making, and sensory-motor coordination, aiming to improve cognitive performance and enhance sports performance.
  3. Provide Interactive and Engaging Workouts: The device will offer interactive and gamified workouts that add a dynamic and engaging element to traditional exercise routines, making workouts more enjoyable, motivating, and effective.
  4. Aid in Rehabilitation and Physical Therapy: The device will provide exercises and modes that can be utilized in rehabilitation and physical therapy settings to aid in the recovery process of individuals with injuries or impairments, targeting coordination, balance, and proprioception.
  5. Simulate Real-World Scenarios: The device will offer modes that simulate real-world sports and tactical scenarios, aiming to improve situational awareness, decision-making, and reaction times in sports and tactical training settings.

Methods: The proposed device will utilize state-of-the-art hardware and software technologies, including wireless and durable sensors, a user-friendly mobile app, and customizable training programs. The device will provide various training modes and exercises that can be customized to cater to different sports, fitness levels, and training objectives. The mobile app will offer real-time performance tracking, progress monitoring, and data analytics features to provide users with valuable insights and feedback on their training performance.

Expected Impact: The proposed device has the potential to revolutionize fitness and sports training, rehabilitation, neurocognitive training, and tactical training by offering an interactive, engaging, and versatile training experience. It is expected to enhance physical performance, cognitive skills, and reaction times, leading to improved sports performance, fitness outcomes, and rehabilitation outcomes.

The proposed interactive fitness and sports training device has significant potential to fill the gap in the market for a next-generation training system that offers a versatile, engaging, and effective training experience. With its innovative hardware and software technologies, the device aims to enhance physical performance, cognitive skills, and reaction times, making it a valuable tool in the fields of sports, fitness, rehabilitation, neurocognitive training, and tactical training. Further research and development efforts will be undertaken to bring this device to market and enable athletes, coaches, fitness enthusiasts, and individuals in rehabilitation or physical therapy settings to achieve their training goals and optimize their performance.

The next steps include

  1. Coming up with the full system design
  2. Waiting for the development kit to arrive
  3. Designing the first prototype board and enclosure
  4. Wireframing the Android application that goes with it, unfortunately, I do not have any Apple environment to target IOS before the submission deadline
  5. Trying the device with willing participants, possibly at my local martial arts club

Should I win the contest, I am going to use the winnings to turn this into a viable open-source training platform. Stay tuned for more updates.

Sources and schematics can be found here:

Posted in Contest, Embedded, Martial Arts, RISCV, RT-Thread, WCH | Leave a comment

Fixing a built-in Oven and Plyometrics

I was down with an ankle injury that kept me out of the Dojo for a bit. Somewhat obsessed with recovery while I couldn’t do much physically, I used the time to read myself into recovery and training theory and discovered plyometrics – a type of exercise that involves explosive movements like jumps, hops, and bounds. It seems this receives quite a bit of focus in Crossfit and Gymnastics. A simple tool to support such exercises is the famed Plyobox. A good branded one becomes expensive fast – too expensive for a “simple” plywood box. You get the idea (source: Critical Bench).

While I was getting excited about it our built-in stove in the kitchen broke. It is a Bosch combination unit and needed support to take it out as one person. I needed something to support it, like a “Plyobox”.

Plyobox for Support
Plyobox for Support

There is nothing better than fixing things around the house and inheriting a free piece of exercise equipment. My stove clearance was 16 inches. So I opted to build a box that measured 16x18x22 inches. We got the cheapest 4 x 8 ft 3/4in plywood sheet we could find at the local Home Depot. Luckily they provide cutting services, so we kept them quite busy.

The Cut 4x8 ft Sheet - Enough for Two Boxes
The Cut 4×8 ft Sheet – Enough for Two Boxes

Long story short the stove got fixed during which the kitchen looked a bit like my embedded lab at work.

Stove Dissection in the Kitchen
Stove Dissection in the Kitchen

After this was done I decided to pad the box. Keeping the budget low, I decided to buy the cheapest Yoga mat I could find and glue it to the sides with 3M-77. It was not a good fit for all sides, so I left one side bare and filled up the other remaining side with cuts. Any gaps were be reinforced with wide electrical or duct tape.

Glue + Cheap Yoga Mat = Padded Box for Barefoot Plyometrics

What I found was that plyometrics can be incredibly beneficial for improving athletic performance, including speed, power, and agility. And when combined with stability exercises on a plyobox, they can also help prevent injuries by strengthening the muscles and joints that support our movements.

Now, I know what you might be thinking – “But I can’t do pistol squats like Taylor May (a.k.a. Little Fitness) or other advanced plyometric exercises.” And that’s okay! Plyometrics can be scaled and modified to meet your current fitness level and abilities. Even someone like Bill Gates, who is known more for his work in technology than his athleticism, has shown that there is no excuse to shy away from plyometrics.

In conclusion, don’t let setbacks or the fear of not being able to do advanced exercises hold you back from incorporating plyometrics into your fitness routine. With some research, a bit of creativity, and a willingness to challenge yourself, you can experience the many benefits of plyometrics and stability exercises on a plyobox. Best of all, you can easily build one using readily-available materials from the next building supply store. Now I can’t wait for that 3M glue to dry…

Padded Plyobox
Padded Plyobox
Posted in Martial Arts | Leave a comment

32-bits at $0.10

In the previous year, I conducted research on 8051 processors and stumbled upon WCH during my investigation. I was impressed to find that they offer a wide range of interesting 8051 microcontrollers, which feature host and device USB support and are reasonably priced. Recently, the vendor announced the release of their value-line RISC-V microcontrollers, further expanding their product offerings. I got my hands on some development kits and am eager to explore this further.

WCH Development Kits
WCH Development Kits

In light of the recent Chinese sanctions on semiconductor exports, the country has been seeking to secure its domestic industry. It appears that many vendors have shifted their focus from commercially-licensed cores that are subject to export controls, to architectures that fall outside the scope of these controls such as RISC-V. WCH in particular has been massively expanding its RISCV offering.

Upon examination of the part nomenclature and firmware library organization, it is evident that WCH has drawn inspiration from STMicroelectronics’ widely popular STM8 and STM32 product lines. This is not the first instance of such imitation, as GigaDevice has previously released similar clones of STM32 devices. The naming conventions utilized in WCH’s provided software development kit (SDK) bear a striking resemblance to those found in STM32 SDKs prior to the introduction of STM32Cube. A comprehensive analysis of this situation can be found in an article by Hackaday.

CH32V003 Block Diagram
CH32V003 Block Diagram

The CH32V003 appears to be specifically designed as a replacement for the widely popular STM8S003-line, particularly in the low-cost 8-bit microcontroller market. Prior to the current silicon shortage, the STM8S003 series could be purchased for $0.2 in volume quantities. WCH seems determined to compete by offering a 32-bit alternative with double the flash and RAM at half the price, and running the internal oscillators at double the frequency. It will be necessary to conduct benchmarks to determine how the RISC-V code density compares to that of the STM8, in order to determine whether these features are advantageous or necessary. WCH’s offering also includes additional features such as a 64-bit unique ID and an integrated operational amplifier (although it is not gain programmable) that can be connected to the 10-bit ADC, which are notable additions compared to the STM8. Looking at the available package options this chip could also be used for other low-cost alternatives such as the NXP RS08 series, Microchip PIC10, or ATtiny. If this chip can be qualified for automotive applications the LIN support by the chip could reach even further into the Infineon or Renesas realm for body and motor-control applications.

WCH Link
WCH Link Debugger

An additional advantage of WCH’s microcontroller offerings is the inclusion of a single-wire debug interface. This is a significant improvement over the ST-Link found on the STM8, which utilizes more pins. Additionally, the WCH chip has an integrated mask loader that allows for flashing the chip directly via UART, enabling efficient development with minimal additional costs. Although the recommended debug probe is available at a low retail price of under $5. To have broad support for many different product lines from WCH, get the WCH LinkE instead of the WCH Link. MounRiver, the recommended development environment has a built-in OpenOCD-port for that tool that allows for seamless debugging. The user community has been pushing WCH for source releases of that tool and the OpenOCD-port sources are maintained by Karl Palsson.

WCH Link vs. Alternatives
WCH Link vs. Alternatives

The microcontrollers will soon be available for purchase on LCSC and can also be obtained in bulk directly from WCH. If the availability of these chips surpasses that of established vendors, it may be worth considering as a viable platform for development. WCH has been in business since 2004 and their 8051-product line has had a long and successful history. I believe that, if this chip gains wider adoption, it will have a lasting presence in the market. There is an active community on Discord. In upcoming blog posts, I will be examining the development environment, debugging options, low-power modes, setting up continuous integration using hardware-in-the-loop simulation, code-density benchmarks, and designing a custom PCB for the samples provided in the development kit.

Posted in Embedded, RISCV, WCH | Leave a comment

Retooling for 2023

A new year has begun. After an extended hiatus in Japan to visit friends and family (pictured here), I am back in the saddle and plan to respin this blog a bit. In hindsight, there was a good mix of martial arts and general embedded topics instead of the original retrocomputing focus. The new-years resolution from 2019 to dive deep into Z80 territory never came to fruition.
This year I am aiming for Karate Shodan. There will be more posts about that in the martial arts section.
I want to write more about advanced embedded topics, exploring RISC-V and FPGAs deeper without applying any “retro constraints”.

Dall-E generated concept for martial arts and embedded computing

I got some help from Dall-E to come up with artwork for this. This is a fantastic tool to generate artwork from text descriptions and chiselling the results into a masterpiece through inquisition. So far the background image has been updated.

I still like the Turbo-Vision-Esque layout though. I’ve spent way too many hours as a kid in front of Turbo Pascal, and Borland C++ for MS-DOS to kiss that look and feel goodbye. The same goes for the 5.25″ disk sound. I miss my old Eskom 80386-DX 40 with dual floppy and 170MB Connor hard drive sometimes.

Please check out our commercial blog too. Most of my time now is spent on product release. There will be engaging lessons there too.

Posted in Artificial Intelligence, Coding, Embedded, Life Perspectives, Martial Arts | Leave a comment

A Tiny Companion

Tiny Laptop

I finally received the laptop that I ordered a while back on Aliexpress. Given that I have a bunch of Christmas travel lined up and may spend hours being crammed in excessively priced airplane economy seats, I was seriously thinking of ways to reduce my electronic baggage. Typically I would have a phone, a big Thinkpad, a headset, and a slew of power adapters with me. Especially being shoulder-to-shoulder with random strangers you cannot have a long laptop sitting on an airplane, you need something small. I never liked tablets and have a real aversion to on-screen keyboards and decidedly limited features for hacking in Android or iOS. If it can not run a desktop operating system, it will not be worth it. I have to admit the Microsoft Surface was a close miss, but its size and price still put me off.

Twenty years ago, my Boss had a solution for this. He bought a used Toshiba Libretto and took this thing everywhere. He primarily used it to review papers. I was always amazed at how the Japanese managed to cram that much stuff into such a small package. For its time it was underpowered, too loud, had a terrible Trackpoint interface, and had too small keyboard buttons, but that was an acceptable compromise for being able to carry it anywhere.

So it looks like I found the modern-day equivalent for just $300 USD on Aliexpress. It does not have a model name, but neatly comes in an A5 format and packs a 4-core Celeron J4125, 12GB RAM, and can be upgraded with an M2 SSD to terabytes of persistent storage. The OEM did manage to install an unactivated version of Windows 11 Pro. In terms of raw compute performance, the Celeron barely outruns an Intel i5 mobile from almost a decade ago but comes with integrated graphics and hardware acceleration for pretty much any modern media codec to make up for it. As a whole package, this is good enough for daily use, but not a gaming laptop, or something I would hand AI developers.

Due to the lack of documentation and probably very creative ways to put this together in a cost-effective manner, the biggest challenge was to install some form of Linux on there to have a development environment for all my embedded needs, should something come up during travel.

As it turns out the local audio interface uses a non-standard audio amplifier after the Intel Sound card that seems to work on the pre-installed Windows 11, but there was no way I could get it to work in two flavours of Ubuntu. This is not a show stopper as you will be likely on a headset most of the time anyways and the Realtek WiFi and Bluetooth drivers worked out of the box.

VESA Framebuffer Rotated by 90 Degrees

The bigger challenge was that the VESA driver from the BIOS rotates the display by 90 degrees and hardwires hsync to a fixed 77Hz refresh rate. So the screen is rotated sideways during installation, and any mode set attempt will kill the screen. Installing Ubuntu 20.04 in compatibility mode got the i915 kernel driver to work. That driver can be instructed to avoid mode switches and for anything console-related, you can use fbcon to rotate the screen in VESA text mode and choose an appropriately sized font. The only thing that I could not rotate was the Grub OS selection. This probably hints that they likely hacked a tablet screen and make it appear as a laptop.

The next challenge was the mouse pointer. The AccuPoint accurately moves around the pointer, but the mouse buttons are actually recognized as keyboard strokes. It took some digging, but I was eventually able to remap them. On the Windows end the buttons of the mouse can only be enabled if the “MouseKeys” setting is enabled that normally would only map the numeric keypad as a mouse.

The power consumption is impressively low. While I was recompiling an entire Yocto Linux distribution from scratch I never saw more than 18W power consumed, and normal loads of less than 10W. It took a few hours and was running at full tilt, but I did not see any stability issues.

Power Consumption

I moved most of my office stuff into the Windows partition to mitigate some of these issues. Overall, this thing exceeded my expectations. It also comes in a sturdy Aluminum enclosure and has a five-point touch screen that worked accurately out of the box on both operating systems. The next tiny project is to modify the PSU in a way that it can be charged from a USB-C battery bank instead of just using the 12V AC adapter.

Posted in Coding, Linux | Leave a comment

The $2 PCB worked…

The parts are in to assemble the $2 PCB

In part one of this series, I showed how to design a breakout board for the RTC8901CE chip. They just arrived in the mailbag last week and I had a few minutes to piece them together and test them. Fast forward I am really happy with the quality and turn-around time of these PCBs. In the commercial world, 10 days turnaround from Asia usually incurs significant shipping charges. This was not the case here. The mating parts that I did not have in my prototyping box were the 4K7 0603 resistors and the 1uF 0603 regulator decoupling capacitor. I ordered them from LCSC and they arrived a day earlier.

SMT assembled

Fetching some long-expired solder paste and firing up the hot-air and the PCB was assembled in a few minutes. This is how it looked after the first wash. Then hand-soldering some headers on. Then testing the power-up configuration, does the chip work as 32.768KHz XO by default?

As you see my setup is a little dated, I had this Hameg oscilloscope since my high school days, way back in the 90s.

Default XO configuration at 32.768MHz

The really nice property of this Seiko-Epson chip is the very wide input voltage, you can work with this directly in 1.8V, 3.3V, or 5V logic domains without any level-shifters. I usually have an older Olimex Arduino clone in my handbag that came in handy as a 3.3V or 5V power source.

Work is really intense these days, I am regularly putting in 13h hour-days. If I get an extended coffee break I will test the other functions of this chip and publish them as an Arduino library in the same repository.

Posted in Embedded | Leave a comment