Execute Open-Source Arduino Code in a PIC Microcontroller Using the MPLAB IDE

The Arduino single-board computer is a de facto standard tool for developing microcomputer applications within the hobbyist and educational communities. It provides an open-source hardware (OSH) environment based on a simple microcontroller board, as well as an open-source (OS) development environment for writing software for the board.

Here’s an approach that enables Arduino code to be configured for execution with the Microchip Technology PIC32MX250F128B small-outline 32-bit microcontroller. It uses the Microchip Technology MPLAB X IDE and MPLAB XC32 C Compiler and the Microchip Technology Microstick II programmer/debugger.

Your own reasons for using this approach will depend on your personal needs and background. Perhaps as a long-term Arduino user, you want to explore a new processor performance option with your existing Arduino code base. Or, you want to take advantage of or gain experience with the Microchip advanced IDE development tools and debug with your existing Arduino code. All of these goals are easily achieved using the approach and the beta library covered in this article.

Several fundamental open-source Arduino code examples are described using the beta core library of Arduino functions I developed. The beta version is available, for evaluation purposes only, as a free download from the “Arduino Library Code for PIC32” link on my KibaCorp company website, kibacorp.com. From there, you can also download a short description of the Microstick II hardware configuration used for the library.

To illustrate the capabilities in their simplest form, here is a simple Blink LED example from my book Beginner’s Guide to Programming the PIC32. The example shows how this custom library makes it easy to convert Arduino code to a PIC32 binary file.

ARDUINO BLINK EXAMPLE 1
The Arduino code example is as follows: Wire an LED through a 1-K resistor to pin 13 (D7) of the Arduino. An output pin is configured to drive an LED using pinMode () function under setup (). Then under loop () this output is set high and then low using digitalWrite () and delay () functions to blink the LED. The community open-source Arduino code is:

Listing 1forwebPIC32 EXAMPLE 1 CODE MODIFICATIONS
The open-source example uses D13 or physical pin 13 on the Arduino. In relation to the PIC32MX, the D13 is physical pin 25. Pin 25 will be used in prototyping wiring.

Now, let’s review and understand the PIC32 project template and its associated “wrapping functions.”  The Arduino uses two principal functions: setup () to initialize the system and loop () to run a continuous execution loop. There is no Main function. Using the Microchip Technololgy XC32 C compiler, we are constrained to having a Main function. The Arduino setup () and loop () functions can be accommodated, but only as part of an overall template Main “wrapping” function. So within our PIC32 template, we accommodate this as follows:

Listing 2

This piece of code is a small but essential part of the template. Note that in this critical wrapping function, setup () is called once as in Arduino and loop () is configured to be called continuously (simulating the loop () function in Arduino) through the use of a while loop in Main.

The second critical wrapping function for our template is the use of C header files at the beginning of the code. The XC32 C compiler uses the C compiler directive #include reference files within the Main code. Arduino uses import, which is a similar construct that is used in higher-level languages such as Java and Python, which cannot be used by the MPLAB XC32 C.

The two include files necessary for our first example are as follows:

Listing 3

System.h references all the critical Microchip library functions supporting the PIC32MX250F128B. The Ardunio.h provides the Arduino specific library function set. Given these two key “wrapper” aspects, where does the Arduino code go? This is best illustrated with a side-by-side comparison between Arduino code and its Microchip equivalent. The Arduino code is essentially positioned between the wrapper codes as part of the Main function.

Blink side-by-side comparison

Blink side-by-side comparison

This approach enables Arduino code to execute on a Microchip PIC32 within an MPLAB X environment. Note that the Arduino code void setup () now appears as void setup (void), and void loop () appears as void loop (void). This is a minor inconvenience but again necessary for our C environment syntax for C prototype function definitions. Once the code is successfully compiled, the environment enables you to have access to the entire built-in tool suite of the MPLAB X and its debugger tool suite.

RUNNING EXAMPLE 1 CODE
Configure the Microstick II prototype as in the following schematic. Both the schematic and prototype are shown below:

Exercise 1 schematic

Exercise 1 schematic

Exercise 1 prototype

Exercise 1 prototype

BETA LIBRARY
Table 1 compares Arduino core functionality to what is contained in the Microchip PIC32 expanded beta library. In the beta version, I added additional C header files to accomplish the necessary library functionality. Table 2 compares variable types between Arduino and PIC32 variable types. Both Table 1 and Table 2 show the current beta version has a high degree of Arduino core library functionality. Current limitations are the use of only one serial port, interrupt with INT0 only, and no stream capability. In addition, with C the “!” operator is used for conditional test only and not as a complement function, as in Arduino. To use the complement function in C, the “~” operator is used. The library is easily adapted to other PIC32 devices or board types.

Table 1

Table 1: Arduino vs Microchip Technology PIC32 core library function comparison

Talble 2

Table 2: Arduino vs Microchip Technology PIC32 core library variable types

INTERRUPTS
If you use interrupts, you must identify to C the name of your interrupt service routine as used in your Arduino script. See below:

Interrupt support

Interrupt support

For more information on the beta release or to send comments and constructive criticism, or to report any detected problems, please contact me here.

LIBRARY TEST EXAMPLES
Four test case examples demonstrating additional core library functions are shown below as illustrations.

Serial communications

Serial communications

Serial find string test case

Serial find string test case

Serial parse INT

Serial parse INT

Interrupt

Interrupt

Editor’s Note: Portions of this post first appeared in Tom Kibalo’s book Beginner’s Guide to Programming the PIC32 (Electronics Products, 2013). They are reprinted with permission from Chuck Hellebuyck, Electronic Products. If you are interested in reading more articles by Kibalo, check out his two-part Circuit Cellar “robot boot camp” series posted in 2012 : “Autonomous Mobile Robot (Part 1): Overview & Hardware” and “Autonomous Mobile Robot (Part 2): Software & Operation.”

 

Tom Kibalo

Tom Kibalo

ABOUT THE AUTHOR
Tom Kibalo is principal engineer at a large defense firm and president of KibaCorp, a company dedicated to DIY hobbyist, student, and engineering education. Tom, who is also an Engineering Department adjunct faculty member at Anne Arundel Community College in Arnold, MD, is keenly interested in microcontroller applications and embedded designs. To find out more about Tom, read his 2013 Circuit Cellar member profile.

DIY IoT: Build a ‘Net-Connected System Today

It’s time to join the Internet of Things (IoT) revolution. Try building a ‘Net-enabled design with WIZnet’s W5500 “smart” Ethernet chip. It’s easier than you think.

In a thorough introduction to the technology, Tom Cantrell presented a garage door monitoring design. He explained:

The W5500 (see Figure 1) starts with a standard 10/100 Ethernet interface (i.e., MAC and PHY) but then goes further with large RAM buffers (16-KB transmit and 16-KB receive) and hardware TCP/IP protocol processing. I discovered WIZnet’s first chip, the  W3100, way back in 2001. Of course by now, as with all things  silicon, the new W5500 is better, faster, and  lower cost. But the concept is still exactly  the same: “Internet enable” applications by  handling the network chores in hardware so  the application microcontroller doesn’t have to do it in software.

Cantrell - WIZ550io

Figure 1: The WIZnet W5500 is an Ethernet chip with a difference—large RAM buffers and hardware TCP/IP processing that make it easy for any microcontroller to go online.

The large RAM buffers help decouple the  microcontroller from network activity. In a  recent project (see my article, “Weatherize  Your Embedded App,” Circuit Cellar 273,  2013), I used the RAM to receive an entire  10-KB+ webpage, completely eliminating the  need for the microcontroller to juggle data at  network speed. And any of the 32-KB on-chip  RAM that isn’t needed for network buffering  is free for general-purpose use, a big plus for  typically RAM-constrained microcontrollers. The other major WIZnet hardware assist  is TCP/IP processing using IP addresses, sockets, and familiar commands including OPEN, CONNECT, SEND, RECEIVE, DISCONNECT.  The high-level interface to the network frees  up microcontroller cycles and code space that  would otherwise be needed for a software TCP/IP stack.

Cantrell goes on to present his design for a ‘Net-connected garage door monitoring system.

For prototyping, check out the WIZnet  ioShield (see Photo 1), which is a baseboard  for the WIZ550io that includes an SD card  socket. There are ioShields for different  platforms (e.g., Arduino, LaunchPad,  mbed, etc.), and with 0.1” headers they are  breadboard friendly.

Photo 1: If you want a fancy server with lots of eye candy, a microSD card is the way to go. The WIZnet ioShields include the card socket and are available for various platforms. The Arduino version is shown here.

Photo 1: If you want a fancy server with lots of eye candy, a microSD card is the way to go. The WIZnet ioShields include the card socket and are available for various platforms. The Arduino version is shown here.

Cantrell prototyped a client version of what he calls his “garage  door ‘Thing’ using an Arduino  and a WIZ550io connected to Exosite (see Photo 2).

A prototype of the client version of my garage “Thing” is shown.

Photo 2: A prototype of the client version of my garage “Thing”

Wondering how to get two clients (e.g., ) to interact with each other? Cantrell used Exosite.

Over on the Exosite website, after signing up for a  free “Developer” account, it was a quick and easy mainly point-and-click exercise to configure my “Device,” “Data,”  “Events,” and “Alerts” (see Photo 3).  As a client, there’s no need to keep the “Thing’s”  Ethernet link powered all the time. Data only needs to  be sent when the garage door opens or closes, but I also  recommend sending a periodic heartbeat just in case. My  garage door monitor will only generate a minute or two  of network activity (i.e., door state changes and hourly  heartbeats) per day, so there’s opportunity for significant  energy savings compared to a 24/7 server.

It only takes a few minutes to set up a simple Exosite dashboard including an e-mail alert. I can “see“ my  garage door without getting off the couch and now, via Exosite, from the farthest reaches of the web.

It only takes a few minutes to set up a simple Exosite dashboard including an e-mail alert. I can “see“ my garage door without getting off the couch and now, via Exosite, from the farthest reaches of the web.

You can download the entire article,  “Connect the Magic: An Introduction to the WIZnet W550,” for free to learn about Cantrell’s garage door control system built with a WIZnet and an Arduino Uno.

Editor’s note: If you have an idea for an innovative, ’Net-enabled electronics system, this is your opportunity to share your original design with the world. Enter the WIZnet Connect the Magic 2014 Design Challenge for a chance to win a share of $15,000 in prizes and gain recognition by Elektor International Media and Circuit Cellar. WIZnet is the sponsor. Eligible entries will be judged on their technical merit, originality, usefulness, cost-effectiveness, and design optimization. The Entry submission deadline is 12:00 PM EST August 3, 2014. How to enter: Implement WIZnet’s WIZ550io Ethernet module, or W5500 chip, in an innovative design; document your project; and then submit your entry. The complete rules and regulations are available on the Challenge webpage.

 

A Coding Interface for an Evaluation Tool

John Peck, a test engineer at Knowles Electronics in Itasca, IL, has used ASCII interfaces to test equipment since he was a graduate student.

“I love test equipment with open, well-documented, ASCII command sets,” he says. “The plain text commands give a complicated instrument a familiar interface and an easy way to automate measurements.”

So when Peck needed to automate the process of reading his ultrasonic range finder’s voltage output, he wanted an ASCII interface to a voltmeter. He also wanted the meter to convert volts into distance, so he added an Atmel AVR Butterfly microcontroller into the mix (see Photo 1). “I thought it would be easy to give it a plain text interface to a PC,” he says.

Atmel AVR Butterfly

Atmel AVR Butterfly

The project became a bit more complex than he expected. But ultimately, Peck says, he came up came up with “a simple command interface that’s easy to customize and extend. It’s not at the level of a commercial instrument, but it works well for sending a few commands and getting some data back.”

If you would like to learn more about how to send commands from a PC to the AVR Butterfly and the basics of using the credit card-sized, single-board microcontroller to recognize, parse, and execute remote commands, read Peck’s article about his project in Circuit Cellar’s May issue.

In the italicized excerpts below, he describes his hardware connections to the board and the process of receiving remote characters (the first step in receiving remote commands). Other topics you’ll find in the full article include setting up a logging system to understand how commands are being processed, configuring the logger (which is the gatekeeper for messages from other subsystems), recognizing and adding commands to extend the system, and sending calibration values.

Peck programmed his system so that it has room to grow and can accommodate his future plans:

“I built the code with AVR-GCC, using the -Os optimization level. The output of avr-gcc –version is avr-gcc (Gentoo 4.6.3 p1.3, pie-0.5.1) 4.6.3.

“The resulting memory map file shows a 306-byte .data size, a 49-byte .bss size, and a 7.8-KB .text size. I used roughly half of the AVR Butterfly’s flash memory and about a third of its RAM. So there’s at least some space left to do more than just recognizing commands and calibrating voltages.”

“I’d like to work on extending the system to handle more types of arguments (e.g., signed integers and floats). And I’d like to port the system to a different part, one with more than one USART. Then I could have a dedicated logging port and log messages wouldn’t get in the way of other communication. Making well-documented interfaces to my designs would help me with my long-term goal of making them more modular.”

These are the connections needed for Atmel’s AVR Butterfly. Atmel’s AVRISP mkII user’s guide stresses that the programmer must be connected to the PC before the target (AVR Butterfly board).

Figure 1: These are the connections needed for Atmel’s AVR Butterfly. Atmel’s AVRISP mkII user’s guide stresses that the programmer must be connected to the PC before the target (AVR Butterfly board).

WORKING WITH THE AVR BUTTERFLY
The AVR Butterfly board includes an Atmel ATmega169 microcontroller and some peripherals. Figure 1 shows the connections I made to it. I only used three wires from the DB9 connector for serial communication with the PC. There isn’t any hardware handshaking. While I could also use this serial channel for programming, I find that using a dedicated programmer makes iterating my code much faster.

A six-pin header soldered to the J403 position enabled me to use Atmel’s AVRISP mkII programmer. Finally, powering the board with an external supply at J401 meant I wouldn’t have to think about the AVR Butterfly’s button cell battery. However, I did need to worry about the minimum power-on reset slope rate. The microcontroller won’t reset at power-on unless the power supply can ramp from about 1 to 3 V at more than 0.1 V/ms. I had to reduce a filter capacitor in my power supply circuit to increase its power-on ramp rate. With that settled, the microcontroller started executing code when I turned on the power supply.

After the hardware was connected, I used the AVR downloader uploader (AVRDUDE) and GNU Make to automate building the code and programming the AVR Butterfly’s flash memory. I modified a makefile template from the WinAVR project to specify my part, programmer, and source files. The template file’s comments helped me understand how to customize the template and comprehend the general build process. Finally, I used Gentoo, Linux’s cross-development package, to install the AVR GNU Compiler Collection (AVR-GCC) and other cross-compilation tools. I could have added these last pieces “by hand,” but Gentoo conveniently updates the toolchain as new versions are released.

Figure2

Figure 2: This is the program flow for processing characters received over the Atmel AVR Butterfly’s USART. Sending a command terminator (carriage return) will always result in an empty Receive buffer. This is a good way to ensure there’s no garbage in the buffer before writing to it.

HANDLING INCOMING CHARACTERS
To receive remote commands, you begin by receiving characters, which are sent to the AVR Butterfly via the USART connector shown in Figure 1. Reception of these characters triggers an interrupt service routine (ISR), which handles them according to the flow shown in Figure 2. The first step in this flow is loading the characters into the Receive buffer.

Figure 3: The received character buffer and pointers used to fill it are shown. There is no limit to the size of commands and their arguments, as long as the entire combined string and terminator fit inside the RECEIVE_BUFFER_SIZE.

Figure 3: The received character buffer and pointers used to fill it are shown. There is no limit to the size of commands and their arguments, as long as the entire combined string and terminator fit inside the RECEIVE_BUFFER_SIZE.

Figure 3 illustrates the Receive buffer loaded with a combined string. The buffer is accessed with a pointer to its beginning and another pointer to the next index to be written. These pointers are members of the recv_cmd_state_t-type variable recv_cmd_state.

This is just style. I like to try to organize a flow’s variables by making them members of their own structure. Naming conventions aside, it’s important to notice that no limitations are imposed on the command or argument size in this first step, provided the total character count stays below the RECEIVE_BUFFER_SIZE limit.

When a combined string in the Receive buffer is finished with a carriage return, the string is copied over to a second buffer. I call this the “Parse buffer,” since this is where the string will be searched for recognized commands and arguments. This buffer is locked until its contents can be processed to keep it from being overwhelmed by new combined strings.

Sending commands faster than they can be processed will generate an error and combined strings sent to a locked parse buffer will be dropped. The maximum command processing frequency will depend on the system clock and other system tasks. Not having larger parse or receive buffers is a limitation that places this project at the hobby level. Extending these buffers to hold more than just one command would make the system more robust.

Editor’s Note: If you are interested in other projects utilizing the AVR Butterfly, check out the Talk Zombie, which won “Distinctive Excellence” in the AVR Design Contest 2006 sponsored by ATMEL and administered by Circuit Cellar. The ATmega169-based multilingual talking device relates ambient temperature and current time in the form of speech (English, Dutch, or French). 

Remote-Control Powered Trapdoor Lift

William Wachsmann, a retired electronic technologist from Canada, has more than 35 years of experience working with minicomputers, microcomputers, embedded systems, and programming in industries ranging from nuclear and aerospace to voicemail and transportation systems.

But despite the complexity of the work he has done over the years, when it came to building a remote-controlled, powered trapdoor lift system for his home, he had two priorities: simplicity and price.

“Although it can be fulfilling to design your own hardware, why reinvent the wheel if you don’t have to? Many reasonably priced modules can be wired together,” Wachsmann says in his article about the project, which appears in Circuit Cellar’s May issue. “Add some software to express the functionality required and you can quickly and inexpensively put together a project. Not only is this method useful for a homebuilt one-of-a-kind application, but it can also be used for proof-of-concept prototyping. It leaves you free to concentrate on solving the problems pertinent to your application.”

Wachsmann’s project relies on off-the-shelf modules for the electrical functions of a trapdoor lift system that provides access to his basement.

“Lifting the trapdoor was hard on my wife’s back,” he says. “If her arms were full when she came upstairs and the door was open, she had to twist her body to release the mechanical latching mechanism while simultaneously stopping the door from falling on her head.”

The multidisciplinary project includes mechanical, electronic, and software components. For the full details—including programming of the project’s Freescale Semiconductor FRDM-KL25Z microprocessor using the mbed online IDE—check out the May issue now available for membership download and single-issue purchase.

(And if you’re interested in other articles about remote-control projects, check out Raul Alvarez’s Home Energy Gateway system, which enables users to remotely monitor home energy consumption and monitor household devices. Alvarez’s project won second place in the 2012 DesignSpark chipKIT challenge administered by Circuit Cellar.)

Excerpts from Wachsmann’s article below describe his system’s mechanical and hardware elements.

INS AND OUTS
I used a screw lift from an old treadmill. It has a 48-VDC motor that draws about 1 A under a 100-lb load. The screw mechanism has a 6” travel distance. Built-in limit switches shut off the motor when the screw reaches the end of its travel in each direction. The screw’s length is nominally 30” when closed and 36” when open. The length can be adjusted slightly by rotating the screw by hand, but the overall travel distance is still 6”.

A simple switch would have sufficed to control the screw lift’s DC motor, but I wanted it to be remotely controlled so the trapdoor could be raised and lowered from anywhere upstairs and from the basement. When someone is in the basement with the trapdoor closed there is no visible way for them to know if the door is obstructed. Initially, I was going to install a warning beeper that the door was opening, but that wouldn’t help if an inanimate object (e.g., a bag of groceries) was on top of the door. I needed to incorporate some form of sensing mechanism into the design.

Figure 1: This diagram represents the trapdoor mechanics. The arm’s down position is shown in red; the up position is shown in blue. Vertical red arrows are labeled with the downward force in pounds

Figure 1: This diagram represents the trapdoor mechanics. The arm’s down position is shown in red; the up position is shown in blue. Vertical red arrows are labeled with the downward force in pounds

THE MECHANICS
I needed a levered system design that used a pivoted bar and the motorized screw lift. The lift also had to enable the door to be manually opened in case of a power failure.
I used IMSI/Design’s TurboCAD program for the mechanical design. By using CAD software, I could experiment with the pivot position, moment arms, and torque requirements to meet the mechanical constraints imposed by the screw lift and the trapdoor’s size and weight.

Photo 1: The screw lift and pivot arm mechanism with a spring assist are shown.

Photo 1: The screw lift and pivot arm mechanism with a spring assist are shown.

Figure 1 shows a diagram of the trapdoor, which is hinged on the left. The opposite side of the door exerts a 15.2-lb downward force. This means the torque (force × distance) required to open the door is 509.2 in-lbs. The pivot arm in red is the position when the door is closed. The blue pivot arm shows the position when the door is open to an 80° angle.

To keep within the 6” lift constraint, I used a 4.25” moment arm to pull down on the pivot arm. This left me with the force required to initially lift the door at 119.5 lb. Also this did not include the added torque due to the pivot arm’s weight.

After mulling this over for a couple of days (and nights) I had an idea. I realized that 119.5 lb is only needed when the door is completely closed. As the door opens, the torque requirement lessens. I incorporated a heavy spring (see Photo 1). When the door is closed the spring extension provides an additional downward force of about 35 lb. This is enough to lessen the load on the screw lift and to compensate for the pivot arm’s additional 2.2 lb. Using a screw lift meant the arm would not spring up if the door was manually opened.

I used an angle iron for the pivot arm. It is 28” long because it had to push up on the door to the right of the door’s center of gravity at 16.75” without adding too much additional torque. The roller is the type used as feet on beds. I used an arbor and 0.75”-diameter bolt through the floor joist for the pivot (see Photo 2).

An arbor is used as a bearing with a 0.75” bolt through the floor joist. The lift mechanism pivots at this point.

Photo 2: An arbor is used as a bearing with a 0.75” bolt through the floor joist. The lift mechanism pivots at this point.

THE HARDWARE
I had set an arbitrary $100 limit for the rest of the system and I quickly realized I would easily come in under budget. I used a $24.25 two-channel RF wireless garage door remote-control receiver, which I purchased from eBay (see Photo 3). This controller can be used in a latched or an unlatched mode. The latched mode requires a momentary push of one of the buttons to cause one of the relays to switch and stay in the On position. When the controller is in unlatched mode, you must hold the button down to keep the relay switched.

Photo 3: The two-channel wireless remote control is shown with the cover removed from the receiver. It came with two keychain-style remotes, which I marked with Up and Down arrows.

Photo 3: The two-channel wireless remote control is shown with the cover removed from the receiver. It came with two keychain-style remotes, which I marked with Up and Down arrows.

Unfortunately, this remote control and any similar ones only come with single-pole double-throw (SPDT) relays. What I really wanted were double-pole double-throw (DPDT) relays to switch both sides of the motor to enable current reversal through the motor.
A remote control system with two remotes seemed ideal and was possible to design with SPDT, so I purchased the relays. Figure 2 shows the circuit using two bridge rectifier DC power supplies. It turns out there were problems with this approach.

SW1 and SW2 represent the Up and Down relays. In latched mode, the door would open when SW1 was energized using the A button on a remote. Pressing the A button again would stop the motor while the door was opening. So would pressing the B button, but then to continue opening the door you needed to press the B button again. Pressing the A  button in this state would cause the door to close because SW2 was still energized. Added to this confusion was the necessity of pressing the A button again when the door was fully opened and stopped due to the internal limit switches. If you didn’t do this, then pressing the B button to close the door wouldn’t work because SW1 was still energized.

Figure 2: It would be theoretically possible to use dual-power supplies and single-pole double-throw (SPDT) switches to control a motor in two directions. When SW1 (b,c) is connected, current flows through D2. When SW2 (b,c) is connected, current flows through D1 in the opposite direction.

Figure 2: It would be theoretically possible to use dual-power supplies and single-pole double-throw (SPDT) switches to control a motor in two directions. When SW1 (b,c) is connected, current flows through D2. When SW2 (b,c) is connected, current flows through D1 in the opposite direction.

I decided to just use the door in unlatched mode and continuously hold down the A button until the door was fully open. What was the problem with this? Noise! Interference from the motor was getting back into the control and causing the relay to frequently switch on and off. This is not good for mechanical relays that have a finite contact life.

After playing around for a while with both operation modes, I noticed that even in the latched mode the motor would sometimes stop and it would occasionally even reverse itself. This was really bad and it became worse.

If both SW1 and SW2 happened to switch at the same time and if the current was at a maximum and there was arcing at the terminal, there could conceivably be a momentary short through a diode in each of the bridge rectifiers that would burn them out. Arc suppression devices wouldn’t help because when active at high voltages, they would almost look like a short between the switch’s terminals A,C. I needed to step back and rethink this.

I found an $8.84 two-channel DPDT relay switch board module on eBay. The module enabled me to use a single-power supply and isolated the motor current from the remote-control board. These relays boards have TTL inputs, so it is tricky to use relays on the remote control board to control the relays on the second relay board. You have to contend with contact bounce. Even if I incorporated debounce circuits, I still didn’t have a way stop the door from opening if it was obstructed.

It was time to get with the 21st century. I needed to use a microcontroller and handle all the debounce and logic functions in firmware.

I bought a $12.95 Freescale Semiconductor FRDM-KL25Z development board, which uses the Kinetis L series of microcontrollers. The FRDM-KL25Z is built on the ARM Cortex-M0+ core. This board comes with multiple I/O pins, most of which can be programmed as required. It also has two micro-USB ports, one of which is used for downloading your program onto the microcontroller and for debugging (see Figure 3).

Figure 3: This is the system’s complete wiring diagram. On the left is a 48-V AC supply and an unregulated 12-V DC motor. A 2.7-Ω, 5-W resistor, which is used for current sensing, is in series with the motor.

Figure 3: This is the system’s complete wiring diagram. On the left is a 48-V AC supply and an unregulated 12-V DC motor. A 2.7-Ω, 5-W resistor, which is used for current sensing, is in series with the motor.

Active ESD Protection for Microcontrollers (EE Tip #129)

Microcontrollers need to be protected from of electrostatic discharge (ESD). You can use the circuit described in this post when you have an application requires a greater degree of ESD protection than what you get from an IC on its I/O pins. Although there are many ESD clamping devices out there, they don’t typically enable you to precisely limit voltage overshoots and undershoots.

Normally, when dealing with a microcontroller or other digital circuit the connections on the device are protected against electrostatic dis­charge. Nevertheless engineers are 4ever taking special precautions when handling such devices to avoid the risks of ESD: the lab will have an anti-static covering on the floor, and nylon clothes and shoes with soles made of insulating material are avoided. And, in case that is not enough, it is normal to wear an anti-static wrist band when moving devices from their anti-static bags to the anti-static bench surface. But what exactly do we mean when we talk about ESD?

HUMAN BODY MODEL

The first model for static discharge, mentioned as early as the 19thcentury, was the “human body model” (HBM). This takes as its starting point a voltage of up to 40 kV, a body capaci­tance of a few hundred picofarads, and a (skin) resistance of 1.5 kΩ. We find that even with a static voltage of only 10 kV, as might easily be acquired by walking across an artificial fiber car­pet in shoes with synthetic soles, it is possible to discharge through a fingertip at peak cur­rents of up to 20 A! The discharge also hap­pens in a very short period, perhaps measured in nanoseconds.

The HBM was adopted in the electronics industry in the 1970s with the introduction of sensitive JFET devices in space applications. The compo­nents were tested using a simple RC circuit like the one shown in Figure 1. The discharge cur­rent depends only on the resistance in the cir­cuit, and the damped discharge curve is largely free of oscillation and is accurately reproducible.

Figure 1—Standard test circuit and current waveform for the human body model

Figure 1—Standard test circuit and current waveform for the human body model

There are also other models that deal with dis­charge through a sensitive component, for exam­ple when a low-resistance electrical connection is made between two devices (the “machine model,” or MM), or when a static charge present on the device itself is discharged (the “charged device model,” or CDM)…

ESD CLAMP CIRCUITS

Figure 2 shows the typical protection circuitry provided on a microcontroller’s I/O port. This example is from an Atmel ATmega. Other microcontrol­lers and logic devices use similar arrangements. Two bipolar protection diodes conduct discharge currents that could cause undershoots or overshoots to one of the supply rails, either VCC or ground. However, the diodes take about 6 ns before they conduct fully.

Figure 2—Typical ESD protection circuit, as found in an Atmel microcontroller

Figure 2—Typical ESD protection circuit, as found in an Atmel microcontroller

Since ESD transients can sometimes be considerably shorter than this, it is possible that the CMOS circuit structures will be damaged long before the diodes spring into action. The parasitic capacitance of the pin is around 6 pF, and this is quickly charged up by the energy in the electrostatic discharge. Unfortunately, we cannot increase this capacitance with­out increasing the impedance of the pin, which is not desirable.

Standard ESD protection circuits like this one are designed to meet the particular requirements set by the ESD Association. However, it is becoming apparent that the traditional models are not appropriate for modern applications. Recent efforts have been directed toward developing a new “system level model” (SLM), which takes into account the different aspects of the older models. This model employs two stored charges that are discharged in different ways, creating a high-amplitude current pulse that decays very quickly plus a low-amplitude pulse that dies away more slowly. The energy transferred in a dis­charge under the SLM can be very much higher than that in the traditional models (Figure 3).

Figure 3—Current waveform under the system-level model

Figure 3—Current waveform under the system-level model

It is readily apparent that the conventional I/O pin circuitry on the IC is not sufficient to provide ESD protection under this model. Also, the con­tinuing industry pressure to make smaller and more complex structures makes it very difficult for design engineers even to maintain current levels of ESD protection, let alone improve on them. In other words: the silicon area needed to provide ESD protection in accordance with the SLM is simply not available! For this reason, external ESD clamp circuits are becoming more rele­vant. If a component provides only a low level of ESD protection (or even none at all) it is possible to add such a circuit at the points most at risk. The clamp circuits usually use so-called transient suppression diodes (transils or tranzorbs) which, like Zener diodes, start to conduct at a specified threshold voltage. However, unlike Zener diodes, they react quickly and can withstand much higher current transients. There are many variations on the circuit design, but none has exceptional performance and none offers precise clamping of voltage undershoots and overshoots.

STATE-OF-THE-ART ESD CLAMPING

If we are in the lucky position of not having to worry about the last cent of materials cost or the last square millimeter of board area, we can easily cre­ate a state-of-the-art active ESD protection circuit from discrete components (Figure 4).

Figure 4—This protection circuit clamps voltage transients outside defined upper and lower thresholds

Figure 4—This protection circuit clamps voltage transients outside defined upper and lower thresholds

The transistor circuit forms a kind of regulated voltage divider. The current through the two resistors R2 and R3 is such that the voltages across them are just enough that transistors T1 and T4 start to conduct and T2 and T3 are just short of saturation. So we have one base-emitter voltage (about 600 mV) across each of these two resistors, which means in turn that the emitters of T2 and T3 are 600 mV below VCC and above ground respectively. The circuit as shown is suitable for a 5 V supply; R1 can be changed to suit supplies of 3.3 V or 2.7 V if needed.

What is the point of this complexity? If the I/O pin is high (at +5 V) the upper 1N4148 switching diode will conduct fully as its cathode is at only 4.4 V. If a positive voltage transient should occur it will be conducted by the 1N4148, without switching delay, to the positive rail by 1N5817 Schottky diode D2, which acts quickly and has a low forward voltage. The same thing happens with polarities reversed when a negative voltage transient (below ground) occurs. Hence the digital inputs and outputs are protected against voltage excursions outside the range of the supply rails. In addition, voltage peaks are limited by the use of suppression inductors. The Murata BLM series inductor presents a relatively high impedance to signals in the 100 MHz range and so can significantly reduce the level of transients.

Although the approach we have described works well with digital levels, it is not suitable for use with signals destined for the analog-to-digital converter (ADC) on a microcontroller. In this case a reverse-biased diode between the signal and each supply rail is required to clamp overshoots and undershoots, with a pair of 10 kΩ series resistors to limit the transient current.

The series-connected capacitors C2 and C3 present a low-impedance path for transients between VCC and ground, and hence spikes on the supply rails will also be conducted away.—P. Kruger, “Active ESD Protection,” Elektor January/February 2014

Editor’s note: This article originally appeared in Elektor January/February 2014. It was shortened and updated for publication on CircuitCellar.com, which is an Elektor International Media Publication.

 

RESOURCES

www.teseq.de/de/de/service_support/technical_information/01_Transient_ immunity_testing_e.pdf

www.ti.com/lit/sg/sszb130b/sszb130b.pdf

www.semtech.com/circuit-protection/esd-protection/

www.murata.com/products/emc/basic/feature/bl_intro.html