A Trace Tool for Embedded Systems

Tracing tools monitor what is going in a program’s execution by logging low-level and frequent events. Thus tracing can detect and help debug performance issues in embedded system applications.

In Circuit Cellar’s April issue, Thiadmer Riemersma describes his DIY tracing setup for small embedded systems. His system comprises three parts: a set of macros to include in the source files of a device under test (DUT), a PC workstation viewer that displays retrieved trace data, and a USB dongle that interfaces the DUT with the workstation.

Small embedded devices typically have limited-performance microcontrollers and scarce interfaces, so Riemersma’s tracing system uses only a single I/O pin on the microcontroller.

Designing a serial protocol that keeps data compact is also important. Riemersma, who develops embedded software for the products of his Netherlands-based company, CompuPhase, explains why:

Compactness of the information transferred from the embedded system to the workstation [which decodes and formats the trace information] is important because the I/O interface that is used for the transfer will probably be the bottleneck. Assuming you are transmitting trace messages bit by bit over a single pin using standard wire and 5- or 3.3-V logic levels, the transfer rate may be limited to roughly 100 Kbps.

My proposed trace protocol achieves compactness by sending numbers in binary, rather than as human-readable text. Common phrases can be sent as numeric message IDs. The trace viewer (or trace ‘listener’) can translate these message IDs back to the human-readable strings.

One important part of the system is the hardware interface—the trace dongle. Since many microcontrollers are designed with only those interfaces used for specific application needs, Riemersma says, typically the first step is finding a spare I/0 pin that can be used to implement the trace protocol.

In the following article excerpt, Riemersma describes his trace dongle and implementation requiring a single I/O pin on the microcontroller:

This is the trace dongle.

This is the trace dongle.

Photo 1 shows the trace dongle. To transmit serial data over a single pin, you need to use an asynchronous protocol. Instead of using a kind of (bit-banged) RS-232, I chose biphase encoding. Biphase encoding has the advantage of being a self-clocking and self-synchronizing protocol. This means that biphase encoding is simple to implement because timing is not critical. The RS-232 protocol requires timing to stay within a 3% error margin; however, biphase encoding is tolerant to timing errors of up to 20% per bit. And, since the protocol resynchronizes on each bit, error accumulation is not an issue.

Figure 1 shows the transitions to transmit an arbitrary binary value in biphase encoding—to be more specific, this variant is biphase mark coding. In the biphase encoding scheme, there is a transition at the start of each bit.

Figure 1: This is an example of a binary value transferred in biphase mark coding.

Figure 1: This is an example of a binary value transferred in biphase mark coding.

For a 1 bit there is also a transition halfway through the clock period. With a 0 bit, there is no extra transition. The absolute levels in biphase encoding are irrelevant, only the changes in the output line are important. In the previous example, the transmission starts with the idle state at a high logic level but ends in an idle state at a low logic level.

Listing 1 shows an example implementation to transmit a byte in biphase encoding over a single I/O pin. The listing refers to the trace_delay() and toggle_pin() functions (or macros). These system-dependent functions must be implemented on the DUT. The trace_delay() function should create a short delay, but not shorter than 5 µs (and not longer than 50 ms). The toggle_pin() function must toggle the output pin from low to high or from high to low.

For each bit, the function in Listing 1 inverts the pin and invokes trace_delay() twice. However, if the bit is a 1, it inverts the pin again between the two delay periods. Therefore, a bit’s clock cycle takes two basic “delay periods.”

Listing 1: Transmitting a byte in biphase encoding, based on a function to toggle an I/O pin, is shown.

Listing 1: Transmitting a byte in biphase encoding, based on a function to toggle an I/O pin, is shown.

The biphase encoding signal goes from the DUT to a trace dongle. The dongle decodes the signal and forwards it as serial data from a virtual RS-232 port to the workstation (see Photo 2 and the circuit in Figure 2).

Photo 2: The trace dongle is inserted into a laptop and connected to the DUT.

Photo 2: The trace dongle is inserted into a laptop and connected to the DUT.

This trace dongle interprets biphase encoding.

Figure 2: This trace dongle interprets biphase encoding.

The buffer is there to protect the microcontroller’s input pin from spikes and to translate the DUT’s logic levels to 5-V TTL levels. I wanted the trace dongle to work whether the DUT used 3-, 3.3-, or 5-V logic. I used a buffer with a Schmitt trigger to avoid the “output high” level of the DUT at 3-V logic, plus noise picked up by the test cable would fall in the undefined area of 5-V TTL input.

Regarding the inductor, the USB interface provides 5 V and the electronics run at 5 V. There isn’t room for a voltage regulator. Since the USB power comes from a PC, I assumed it might not be a “clean” voltage. I used the LC filter to reduce noise on the power line.

The trace dongle uses a Future Technology Devices International (FTDI) FT232RL USB-to-RS-232 converter and a Microchip Technology PIC16F1824 microcontroller. The main reason I chose the FT232RL converter is FTDI’s excellent drivers for multiple OSes. True, your favorite OS already comes with a driver for virtual serial ports, but it is adequate at best. The FTDI drivers offer lower latency and a flexible API. With these drivers, the timestamps displayed in the trace viewers are as accurate as what can be achieved with the USB protocol, typically within 2 ms.

I chose the PIC microcontroller for its low cost and low pin count. I selected the PIC16F1824 because I had used it in an earlier project and I had several on hand. The microcontroller runs on a 12-MHz clock that is provided by the FTDI chip.

The pins to connect to the DUT are a ground and a data line. The data line is terminated at 120 Ω to match the impedance of the wire between the dongle and the DUT.

The cable between the DUT and the trace dongle may be fairly long; therefore signal reflections in the cable should be considered even for relatively low transmission speeds of roughly 250 kHz. That cable is typically just loose wire. The impedance of loose wire varies, but 120 Ω is a good approximate value.

The data line can handle 3-to-5-V logic voltages. Voltages up to 9 V do not harm the dongle because it is protected with a Zener diode (the 9-V limit is due to the selected Zener diode’s maximum power dissipation). The data line has a 10-kΩ to 5-V pull-up, so you can use it on an open-collector output.

The last item of interest in the circuit is a bicolor LED that is simply an indicator for the trace dongle’s status and activity. The LED illuminates red when the dongle is “idle” (i.e., it has been enumerated by the OS). It illuminates green when biphase encoded data is being received.

After the dongle is built, it must be programmed. First, the FT232RL must be programmed (with FTDI’s “FT Prog” program) to provide a 12-MHz clock on Pin C0. The “Product Description” in the USB string descriptors should be set to “tracedongle” so the trace viewers can find the dongle among other FTDI devices (if any). To avoid the dongle being listed as a serial port, I also set the option to only load the FTDI D2XX drivers.

To upload the firmware in the PIC microcontroller, you need a programmer (e.g., Microchip Technology’s PICkit) and a Tag-Connect cable, which eliminates the need for a six-pin header on the PCB, so it saves board space and cost.

The rest of the article provides details of how to create the dongle firmware, how to add trace statements to the DUT software being monitored, and how to use the GUI version of the trace viewer.

The tracing system is complete, but it can be enhanced, Riemersma says. “Future improvements to the tracing system would include the ability to draw graphs (e.g., for task switches or queue capacity) or a way to get higher precision timestamps of received trace packets,” he says.

For Riemersma’s full article, refer to our April issue now available for membership download or single-issue purchase.

New 8-bit PIC Microcontrollers: Intelligent Analog & Core Independent Peripherals

Microchip Technology, Inc. announced Monday from EE Live! and the Embedded Systems Conference in San Jose the PIC16(L)F170X and PIC16(L)F171X family of 8-bit microcontrollers (MCUs), which combine a rich set of intelligent analog and core independent peripherals, along with cost-effective pricing and eXtreme Low Power (XLP) technology. Available in 14-, 20-, 28-, and 40/44-pin packages, the 11-member PIC16F170X/171X family of microcontrollers integrates two op-amps to drive analog control loops, sensor amplification and basic signal conditioning, while reducing system cost and board space.

PIC16F170X/171X MCUs reduce design complexity and system BOM cost with integrated op-amps, zero cross detect, and peripheral pin select.

PIC16F170X/171X MCUs reduce design complexity and system BOM cost with integrated op-amps, zero cross detect, and peripheral pin select.

These new devices also offer built-in Zero Cross Detect (ZCD) to simplify TRIAC control and minimize the EMI caused by switching transients. Additionally, these are the first PIC16 MCUs with Peripheral Pin Select, a pin-mapping feature that gives designers the flexibility to designate the pinout of many peripheral functions.

The PIC16F170X/171X are general-purpose microcontrollers that are ideal for a broad range of applications, such as consumer (home appliances, power tools, electric razors), portable medical (blood-pressure meters, blood-glucose meters, pedometers), LED lighting, battery charging, power supplies and motor control.

The new microcontrollers feature up to 28 KB of self-read/write flash program memory, up to 2 KB of RAM, a 10-bit ADC, a 5-/8-bit DAC, Capture-Compare PWM modules, stand-alone 10-bit PWM modules and high-speed comparators (60 ns typical response), along with EUSART, I2C and SPI interface peripherals. They also feature XLP technology for typical active and sleep currents of just 35 µA/MHz and 30 nA, respectively, helping to extend battery life and reduce standby current consumption.

The PIC16F170X/171X family is supported by Microchip’s standard suite of world-class development tools, including the PICkit 3 (part # PG164130, $44.95), MPLAB ICD 3 (part # DV164035, $189.99), PICkit 3 Low Pin Count Demo Board (part # DM164130-9, $25.99), PICDEM Lab Development Kit (part # DM163045, $134.99) and PICDEM 2 Plus (part # DM163022-1, $99.99). The MPLAB Code Configurator is a free tool that generates seamless, easy-to-understand C code that is inserted into your project. It currently supports the PIC16F1704/08, and is expected to support the PIC16F1713/16 in April, along with all remaining microcontrollers in this family soon thereafter.

The PIC16(L)F1703/1704/1705 microcontrollers are available now for sampling and production in 14-pin PDIP, TSSOP, SOIC and QFN (4 x 4 x 0.9 mm) packages. The PIC16F1707/1708/1709 microcontrollers are available now for sampling and production in 20-pin PDIP, SSOP, SOIC and QFN (4 x 4 x 0.9 mm) packages. The PIC16F1713/16 MCUs are available now for sampling and production in 28-pin PDIP, SSOP, SOIC, QFN (6 x 6 x 0.9 mm) and UQFN (4 x 4 x 0.5 mm) packages. The PIC16F1718 microcontrollers are expected to be available for sampling and production in May 2014, in 28-pin PDIP, SSOP, SOIC, QFN (6 x 6 x 0.9 mm) and UQFN (4 x 4 x 0.5 mm) packages. The PIC16F1717/19 microcontrollers are expected to be available for sampling and production in May 2014, in 40/44-pin PDIP, TQFP and UQFN (5 x 5 x 0.5 mm). Pricing starts at $0.59 each, in 10,000-unit quantities.

Source: Microchip Technology, Inc.

MCU-Based Experimental Glider with GPS Receiver

When Jens Altenburg found a design for a compass-controlled glider in a 1930s paperback, he was inspired to make his own self-controlled model aircraft (see Photo 1)

Photo 1: This is the cover of an old paperback with the description of the compass-controlled glider. The model aircraft had a so-called “canard” configuration―a very modern design concept. Some highly sophisticated fighter planes are based on the same principle. (Photo used with permission of Ravensburger.)

Photo 1: This is the cover of an old paperback with the description of the compass-controlled glider. The model aircraft had a so-called “canard” configuration―a very modern design concept. Some highly sophisticated fighter planes are based on the same principle. (Photo used with permission of Ravensburger.)

His excellent article about his high-altitude, low-cost (HALO) experimental glider appears in Circuit Cellar’s April issue. The MCU-based glider includes a micro-GPs receiver and sensors and can climb to a preprogrammed altitude and find its way back home to a given coordinate.

Altenburg, a professor at the University of Applied Sciences Bingen in Germany, added more than a few twists to the 80-year-old plan. An essential design tool was the Reflex-XTR flight simulation software he used to trim his 3-D glider plan and conduct simulated flights.

Jens also researched other early autopilots, including the one used by the Fiesler Fi 103R German V-1 flying bomb. Known as buzz bombs during World War II, these rough predecessors of the cruise missile were launched against London after D-Day. Fortunately, they were vulnerable to anti-aircraft fire, but their autopilots were nonetheless mechanical engineering masterpieces (see Figure 1)

“Equipped with a compass, a single-axis gyro, and a barometric pressure sensor, the Fiesler Fi 103R German V-1 flying bomb flew without additional control,” Altenburg says. “The compass monitored the flying direction in general, the barometer controlled the altitude, and the gyro responded to short-duration disturbances (e.g., wind gusts).”

Figure 1: These are the main components of the Fieseler Fi 103R German V-1 flying bomb. The flight controller was designed as a mechanical computer with a magnetic compass and barometric pressure sensor for input. Short-time disturbances were damped with the main gyro (gimbal mounted) and two auxiliary gyros (fixed in one axis). The “mechanical” computer was pneumatically powered. The propeller log on top of the bomb measured the distance to the target.

Figure 1: These are the main components of the Fieseler Fi 103R German V-1 flying bomb. The flight controller was designed as a mechanical computer with a magnetic compass and barometric pressure sensor for input. Short-time disturbances were damped with the main gyro (gimbal mounted) and two auxiliary gyros (fixed in one axis). The “mechanical” computer was pneumatically powered. The propeller log on top of the bomb measured the distance to the target.

Altenburg adapted some of the V-1′s ideas into the flight control system for his 21st century autopilot glider. “All the Fi 103R board system’s electromechanical components received an electronic counterpart,” he says. “I replaced the mechanical gyros, the barometer, and the magnetic compass with MEMS. But it’s 2014, so I extended the electronics with a telemetry system and a GPS sensor.” (See Figure 2)

Figure 2: This is the flight controller’s block structure. The main function blocks are GPS, CPU, and power. GPS data is processed as a control signal for the servomotor.

Figure 2: This is the flight controller’s block structure. The main function blocks are GPS, CPU, and power. GPS data is processed as a control signal for the servomotor.

His article includes a detailed description of his glider’s flight-controller hardware, including the following:

Highly sophisticated electronics are always more sensitive to noise, power loss, and so forth. As discussed in the first sections of this article, a glider can be controlled by only a magnetic compass, some coils, and a battery. What else had to be done?

I divided the electronic system into different boards. The main board contains only the CPU and the GPS sensor. I thought that would be sufficient for basic functions. The magnetic and pressure sensor can be connected in case of extra missions. The telemetry unit is also a separate PCB.

Figure 3 shows the main board. Power is provided by a CR2032 lithium coin-cell battery. Two low-dropout linear regulators support the hardware with 1.8 and 2.7 V. The 1.8-V line is only for the GPS sensor. The second power supply provides the CPU with a stable voltage. The 2.7 V is the lowest voltage for the CPU’s internal ADC.

It is extremely important for the entire system to save power. Consequently, the servomotor has a separate power switch (Q1). As long as rudder movement isn’t necessary, the servomotor is powered off. The servomotor’s gear has enough drag to hold the rudder position without electrical power. The servomotor’s control signal is exactly the same as usually needed. It has a 1.1-to-2.1-ms pulse time range with about a 20-ms period. Two connectors (JP9 and JP10) are available for the extension boards (compass and telemetry)..

I used an STMicroelectronics LSM303DLM, which is a sensor module with a three-axis magnetometer and three-axis accelerometer. The sensor is connected by an I2C bus. The Bosch Sensortec BMP085 pressure sensor uses the same bus.

For telemetry, I applied an AXSEM AX5043 IC, which is a complete, narrow-band transceiver for multiple standards. The IC has an excellent link budget, which is the difference between output power in Transmit mode and input sensitivity in Receive mode. The higher the budget, the longer the transmission distance.

The AX5043 is also optimized for battery-powered applications. For modest demands, a standard crystal (X1, 16-MHz) is used for clock generation. In case of higher requirements, a temperature-compensated crystal oscillator (TCXO) is recommended.

The main board’s hardware with a CPU and a GPS sensor is shown. A CR2032 lithium coin-cell battery supplies the power. Two regulators provide 1.8  and 2.7 V for the GPS and the CPU. The main outputs are the servomotor’s signal and power switch.

Figure 3: The main board’s hardware with a CPU and a GPS sensor is shown. A CR2032 lithium coin-cell battery supplies the power. Two regulators provide 1.8 and 2.7 V for the GPS and the CPU. The main outputs are the servomotor’s signal and power switch.

Altenburg’s article also walks readers through the mathematical calculations needed to provide longitude, latitude, and course data to support navigation and the CPU’s most important sensor— the u-blox Fastrax UC430 GPS. He also discusses his experience using the Renesas Electronics R5F100AA microcontroller to equip the prototype board. (Altenburg’s glider won honorable mention in the 2012 Renesas RL78 Green Energy Challenge, see Photos 2 and 3).

The full article is in the April issue, now available for download by members or single-issue purchase.

One of the final steps is mounting the servomotor for rudder control. Thin cords connect the servomotor horn and the rudder. Two metal springs balance mechanical tolerances.

Photo 2: One of the final steps is mounting the servomotor for rudder control. Thin cords connect the servomotor horn and the rudder. Two metal springs balance mechanical tolerances.

Photo 2: This is the well-equipped high-altitude low-cost (HALO) experimental glider.

Photo 3: This is the well-equipped high-altitude low-cost (HALO) experimental glider.

Embedded Programming: Rummage Around In This Toolbox

Circuit Cellar’s April issue is nothing less than an embedded programming toolbox. Inside you’ll find tips, tools, and online resources to help you do everything from building a simple tracing system that can debug a small embedded system to designing with a complex system-on-a-chip (SoC) that combines programmable logic and high-speed processors.

Article contributor Thiadmer Riemersma describes the three parts of his tracing system: a set of macros to include in the source files of a device under test (DUT), a PC workstation viewer that displays retrieved trace data, and a USB dongle that interfaces the DUT with the workstation (p. 26).

Thaidmer Riemersma's trace dongle is connected to a laptop and device. The dongle decodes the signal and forwards it as serial data from a virtual RS-232 port to the workstation.

Thaidmer Riemersma’s trace dongle is connected to a laptop and DUT. The dongle decodes the signal and forwards it as serial data from a virtual RS-232 port to the workstation.

Riemersma’s special serial protocol overcomes common challenges of tracing small embedded devices, which typically have limited-performance microcontrollers and scarce interfaces. His system uses a single I/O and keeps it from bottlenecking by sending DUT-to-workstation trace transmissions as compact binary messages. “The trace viewer (or trace “listener”) can translate these message IDs back to the human-readable strings,” he says.

But let’s move on from discussing a single I/0 to a tool that offers hundreds of I/0s. They’re part of the all-programmable Xilinx Zynq SoC, an example of a device that blends a large FPGA fabric with a powerful processing core. Columnist Colin O’Flynn explores using the Zynq SoC as part of the Avnet ZedBoard development board (p. 46). “Xilinx’s Zynq device has many interesting applications,” O’Flynn concludes. “This is made highly accessible by the ZedBoard and MicroZed boards.”

An Avnet ZedBoard is connected to the OpenADC. The OpenADC provides a moderate-speed ADC (105 msps), which interfaces to the programmable logic (PL) fabric in Xilinx’s Zynq device via a parallel data bus. The PL fabric then maps itself as a peripheral on the hard-core processing system (PS) in the Zynq device to stream this data into the system DDR memory.

An Avnet ZedBoard is connected to the OpenADC. (Source: C. O’Flynn, Circuit Cellar 285)

Our embedded programming issue also includes George Novacek’s article on design-level software safety analysis, which helps avert hazards that can damage an embedded controller (p. 39). Bob Japenga discusses specialized file systems essential to Linux and a helpful networking protocol (p. 52).

One of the final steps is mounting the servomotor for rudder control. Thin cords connect the servomotor horn and the rudder. Two metal springs balance mechanical tolerances.

Jens Altenburg’s project

Other issue highlights include projects that are fun as well as instructive. For example, Jens Altenburg added an MCU, GPS, flight simulation, sensors, and more to a compass-controlled glider design he found in a 1930s paperback (p. 32). Columnist Jeff Bachiochi introduces the possibilities of programmable RGB LED strips (p. 66).

The Future of Small Radar Technology

Directing the limited resources of Fighter Command to intercept a fleet of Luftwaffe bombers en route to London or accurately engaging the Imperial Navy at 18,000 yards in the dead of night. This was our grandfather’s radar, the technology that evened the odds in World War II.

This is the combat information center aboard a World War II destroyer with two radar displays.

This is the combat information center aboard a World War II destroyer with two radar displays.

Today there is an insatiable demand for short-range sensors (i.e., small radar technology)—from autonomous vehicles to gaming consoles and consumer devices. State-of-the-art sensors that can provide full 3-D mapping of a small-target scenes include laser radar and time-of-flight (ToF) cameras. Less expensive and less accurate acoustic and infrared devices sense proximity and coarse angle of arrival. The one sensor often overlooked by the both the DIY and professional designer is radar.

However, some are beginning to apply small radar technology to solve the world’s problems. Here are specific examples:

Autonomous vehicles: In 2007, the General Motors and Carnegie Mellon University Tartan Racing team won the Defense Advanced Research Projects Agency (DARPA) Urban Challenge, where autonomous vehicles had to drive through a city in the shortest possible time period. Numerous small radar devices aided in their real-time decision making. Small radar devices will be a key enabling technology for autonomous vehicles—from self-driving automobiles to unmanned aerial drones.

Consumer products: Recently, Massachusetts Institute of Technology (MIT) researchers developed a radar sensor for gaming systems, shown to be capable of detecting gestures and other complex movements inside a room and through interior walls. Expect small radar devices to play a key role in enabling user interface on gaming consoles to smartphones.

The Internet of Things (IoT): Fybr is a technology company that uses small radar sensors to detect the presence of parked automobiles, creating the most accurate parking detection system in the world for smart cities to manage parking and traffic congestion in real time. Small radar sensors will enable the IoT by providing accurate intelligence to data aggregators.

Automotive: Small radar devices are found in mid- to high-priced automobiles in automated cruise control, blind-spot detection, and parking aids. Small radar devices will soon play a key role in automatic braking, obstacle-avoidance systems, and eventually self-driving automobiles, greatly increasing passenger safety.

Through-Wall Imaging: Advances in small radar have numerous possible military applications, including recent MIT work on through-wall imaging of human targets through solid concrete walls. Expect more military uses of small radar technology.

What is taking so long? A tremendous knowledge gap exists between writing the application and emitting, then detecting, scattered microwave fields and understanding the result. Radar was originally developed by physicists who had a deep understanding of electromagnetics and were interested in the theory of microwave propagation and scattering. They created everything from scratch, from antennas to specialized vacuum tubes.

Microwave tube development, for example, required a working knowledge of particle physics. Due to this legacy, radar textbooks are often intensely theoretical. Furthermore, microwave components were very expensive—handmade and gold-plated. Radar was primarily developed by governments and the military, which made high-dollar investments for national security.

Small radar devices such as the RFBeam Microwave K-LC1a radio transceiver cost less than $10 when purchased in quantity.

Small radar devices such as the RFBeam Microwave K-LC1a radio transceiver cost less than $10 when purchased in quantity.

It’s time we make radar a viable option for DIY projects and consumer devices by developing low-cost, easy-to-use, capable technology and bridging the knowledge gap!
Today you can buy small radar sensors for less than $10. Couple this with learning practical radar processing methods, and you can solve a critical sensing problem for your project.

Learn by doing. I created the MIT short-course “Build a Small Radar Sensor,” where students learn about radar by building a device from scratch. Those interested can take the online course for free through MIT Opencourseware or enroll in the five-day MIT Professional Education course.

Dive deeper. My soon-to-be published multimedia book, Small and Short-Range Radar Systems, explains the principles and building of numerous small radar devices and then demonstrates them so readers at all levels can create their own radar devices or learn how to use data from off-the-shelf radar sensors.

This is just the beginning. Soon small radar sensors will be everywhere.