Official Blog of Silicon Labs

      • Chapter 5 MCU Clocking Part 2 --The SysTick Interrupt

        lynchtron | 06/180/2015 | 02:58 AM



        SysTick Interrupt Handler

        The easiest interrupt source to use in an ARM-based MCU is the System Timer, or SysTick.  The free-running System Timer built into the ARM core can be enabled and configured to generate a periodic SysTick Interrupt whenever the associated countdown register reaches zero.  What’s nice about this interrupt source is that you can configure it with a single call provided by the core libraries, so no #include files are needed at all, and you can implement the SysTick interrupt handler function anywhere in your code, and the compiler will find your function and execute it whenever the SysTick Interrupt occurs.


        Although this interrupt source is easily configured, the down side to the SysTick is that it doesn’t have a lot of configurable options beyond the countdown value, and since it is tied directly to the core frequency of the MCU, it further limits its flexibility.


        Here is how we configure the SysTick interrupt so that it is enabled and running at 1ms interrupts:


        SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 1000));


        The SysTick_Config function automatically starts the System Timer, sets the countdown value as its only input, and enables the SysTick interrupt.  By dividing the core frequency by 1,000, we are saying that we want each SysTick to occur every millisecond.  For example, if the clock is running at 32MHz, the countdown value is 320,000.  With that clock speed, that number of counts occur every 1ms.  If the clock is running at 14MHz, the countdown value is 140,000, which also happens every 1ms.   


        Beware of setting this countdown value divider too low, i.e. values under 100 which would result in interrupts every 100 microseconds or less.  When the MCU executes the interrupt handler lookup and then enters the SysTick interrupt handler, it uses about 12 core clock cycles.  You need to make sure that you have enough time to enter the SysTick interrupt handler, execute whatever instructions are in the handler, and then exit the SysTick well before the next SysTick interrupt occurs.  Otherwise, the rest of your program won’t run, since the only thing the MCU will be doing is executing the SysTick interrupt handler over and over.


        If we don’t create a function to handle the SysTick interrupt when it occurs, the MCU will generate a Hard Fault, which will halt execution of the program.  So we must create the interrupt handler function to be called to handle the timer-based event:

        void SysTick_Handler(void)
          // Your code goes here


        This interrupt handler code can be placed in any of your included files.   The core libraries already have a prototype of this function name, so the compiler will be looking for this function’s implementation when the SysTick interrupt occurs.


        So now we have a function that gets called every millisecond, which could be a useful thing to perform some periodic instructions.  Beware that the timing will change if the system clock frequency changes, which you may want to do at some point to save power, since the SysTick count is calculated to correspond to a single system clock frequency.  Therefore you will need to rerun the SysTick_Config function after every core clock frequency change to keep a consistent interrupt rate.


        SysTick as a Delay Function Generator

        The examples in some of the Simplicity Studio application notes use the SysTick as a way to create a delay in a sequential program.  For example, the essence of the following code can be found in many of the included examples:

        #define DEBUG_BREAK           __asm__("BKPT #0");
        /* Counts 1ms timeTicks */
        volatile uint32_t msTicks = 0;
        void Delay(uint32_t dlyTicks)
              uint32_t curTicks;
              curTicks = msTicks;
              while ((msTicks - curTicks) < dlyTicks) ;
        void SysTick_Handler(void)
              /* Increment counter necessary in Delay()*/
        int main(void)
              // Chip errata
              if (SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 1000))
              while (1)
                    // Do something that will happen every second


        Notice that I have placed the SysTick_Config inside of an if statement and calls a DEBUG_BREAK in case the SysTick can’t be configured for the supplied divider value.  This differs from the examples included with the kit examples to make it easier to spot problems in my code.  


        The compiler will replace DEBUG_BREAK in my code with the special assembly command BKPT #0, which tells the ARM core to drop into a debug mode and halt the processor. I will use these DEBUG_BREAK statements in my code wherever I need to spot something that is going wrong from the IDE.  As long as the debugger is attached to the system, you will see that the IDE breaks into debug mode and shows you where things have gone wrong.  Otherwise the system would lock up or act erratically and there would be no indication that things had gone wrong.  Once you are ready to deploy your firmware in the field for production, the DEBUG_BREAK code can be redefined as an empty string, and the compiler will remove all instances of the BKPT #0 command from your production code.


        Once the System Timer is configured, the execution of the SysTick_Handler will interrupt any running program once every millisecond and update the global msTicks variable by adding one to the count.  The MCU will then return execution to the point in the sequential program where it was when the interrupt occurred.


        The Delay function can be called anywhere in your sequential program where you need to insert a time delay (except inside the SysTick_Handler itself.   More on that in a moment.) The Delay function will wait the number of dlyTicks (in this case, the number of milliseconds) before exiting the Delay function.  Since the execution of the Delay function’s while loop is being interrupted by the SysTick interrupt handler, the msTicks variable is being updated in the background outside of the Delay function’s knowledge or control.  That is why msTicks is defined as volatile, which tells the compiler that this variable can change by a background process.  This keeps the compiler from optimizing ineffective statements out of your program when it appears to the compiler that msTicks would never change.  As long as the SysTick interrupt is firing, the Delay function will eventually find that msTicks is larger than curTicks by dlyTicks and allow the function to exit, returning program control to the main() while loop.  You can easily test this code by placing a breakpoint on the line of the Delay(1000) statement.  Upon running the code, you should notice that the code breaks on the line.  Then, when you press the resume button, it should break again after a second.  Set the value to Delay(10000) and recompile.  After the first break-and-resume operation, you should now see the breakpoint being triggered after 10 seconds every time you resume the program.


        The reason why the Delay function cannot be used inside of the SysTick handler is because interrupts in the ARM core are not reentrant.  This means that once the handler is executing, even if a millisecond has passed and another SysTick interrupt occurs, the handler will exit and then re-enter the interrupt  immediately to service the blocked interrupt source.  In this case, msTicks will never increment, so the Delay function will never exit, and the whole thing locks up.


        This is a quick and dirty way to create a delay function, and it is a bit better than our instruction-based delay function that we created in the past lessons to introduce a pause by keeping the MCU mindlessly busy in order to blink the LED at a certain rate.  The SysTick method can be configured to keep accurate time at any clock frequency, but they both keep the processor in a high-power state at all times.  And, both can be impacted by any code that implements interrupt handlers or disables interrupts for timing-critical procedures.  This will add more delay to your delay function that what you expect, and your timing will change in unexpected ways.  As you start building more complex programs, these intricate interactions could give you a hard time.


        The big problem with the above code to generate a delay is that the variable msTicks is used to count off the number of milliseconds that have elapsed, but the SysTick interrupt is not guaranteed to be triggered at regular intervals if the code inside the SysTick handler is not quick enough to exit before the next SysTick interrupt occurs, so msTicks will not get updated as routinely as expected.  And, the entry into the SysTick interrupt handler can be delayed by any code that temporarily disables interrupts.  This means that the count that is kept by this procedure may be inconsistent depending on what is going on with the rest of the system. 


        The bottom line is that the SysTick interrupt can be used anytime that you need something to happen on a roughly periodic basis, but beware that it can be “starved” for time on the MCU, so don’t rely upon it for accurate time keeping purposes.  It has plenty of good uses, but it is not your only tool for timing-based functions.


        In the next lesson, I will introduce the peripheral timers on the EFM32 series of MCUs to create more accurate timing functions.



      • Chapter 5 Clocking Part 1 -- MCU Clocks and Introduction to Interrupts

        lynchtron | 06/167/2015 | 02:02 PM


        This chapter may seem trivial at first glance, but it is surprisingly difficult to create reliable dimming, fading and animation effects on an LED or a set of LEDs.  I’ll describe the layers of timing that is necessary, and you will build a sweeping animation similar to the red scanner bar that we saw on the hood of the Michael Knight’s Firebird on the 80’s TV show, Knight Rider.  In the process of completing the task, you will learn all about MCU clock sources and scaling, interrupts and their handlers, and how to manage all of that from a system level.  You need to get much of this under your belt as the foundation for more complex lessons that are coming.


          Materials Needed for This Lesson

        • Solderless breadboard & hookup wire
        • Through-hole LEDs x 3
        • Through-hole 2k-ohm resistors x 3


        MCU Clocking

        Most clocks used in an MCU in the core and by peripherals are not the kind that are used for keeping time.  A clock in computer hardware is used to give the electronic circuits a heartbeat so that everything works in lock step.  Clocks are used to adjust the operating speed of the part.  A peripheral with a slow clock uses the least amount of power.  Higher frequencies result in more power consumption.  


        When you are trying to get your gadget working, the last thing you want to think about is how to configure the clocks.  But if you get the configuration wrong, you will pay for it with a system that stubbornly refuse to function.  So do yourself a favor and read through this short overview.  I’m trying to pull out the most important things that you should know for now.  The following figures may give you another perspective on how some of the components of a clocking architecture relate.



        General Topology of the Clock Architecture


        All clocks in the EFM32 MCU are digital waveforms that are controlled by the Clock Management Unit (CMU) and are usually sourced from analog oscillators.  The oscillators in the EFM32 family are either a quartz-based crystal or a Resistor-Capacitor (RC) network.  The quartz-based crystal oscillator must be installed in the printed circuit board along with two capacitors and enter the MCU on a pair of pins.  The resonant frequency of the crystal oscillator is fixed and must be chosen when the board is assembled.  The RC clock sources exist inside the MCU and the resonant frequency can be controlled through configuration registers.  Crystal oscillators have higher precision than the RC oscillators, the latter of which have tuning mechanisms driven by the MCU that are used to continually compensate for their inaccuracies.


        There are two available frequency bands for clock sources.  The low-frequency band is sourced at 32.768 kHz and the high frequency band is sourced in an adjustable range of 1 to 32 MHz (except on Zero Gecko which is limited to 24MHz.)  There is a Low Frequency Crystal Oscillator (LFXO) source and a High-Frequency Crystal Oscillator (HFXO) source as well as a Low-Frequency RC Oscillator (LFRCO) source and a High-Frequency RC Oscillator (HFRCO) source.  The clock sources are chosen based on the needs of the application.  Tradeoffs can be made for accuracy versus extra board components, fast execution time versus low power.  The clock source can be changed while the MCU is operational in order to adjust the power consumption to the task at hand.  The HFRCO has a very fast wake up time and is therefore the default source to start up the MCU from reset. 

        There are also two special clock sources, the first of which is called AUXCLK that runs at 14 MHz for flash programming and SWO output, and an Ultra-Low Frequency RC Oscillator (ULFRCO) that runs at 1 kHz and used for deep sleep states to run the Watchdog Timer peripheral.


        Once you have chosen a clock source, the digital clocks that are generated from those sources have adjustable operating frequency and are routed through a clock multiplexer.  They are controlled via configuration registers within the MCU.  Once a clock is routed to a peripheral, it is only possible to scale the clock speed downward (i.e. it cannot multiply the clock source to create a faster clock than its source) and is accomplished with something called a prescaler or clock divider.  A prescaler setting of one is the highest possible frequency.  The upper limits of clock division (producing the slowest possible operating clocks) are described in the Reference Manual for your MCU.  The digital clocks can themselves become clock input sources to other peripherals on the design.



        Configurable Clock Path Through the EFM32 MCU


        There is a lot more to know about clocks, and I will be covering that as we move into each peripheral.  If you want to know more, you can read more about it in the Reference Manual for your MCU as well in the Application Notes found using the tile in Simplicity Studio.   Use the Clock Management Unit (CMU) software tools available in em_cmu.h to control your clock sources.


        Why is all of this stuff important?  Because in order to keep track of time for our programming, it is necessary to understand how many operations can be done per second, and we also need to make sure that the number of operations is consistent in each and every second.  Otherwise, you will end up with a solution that drifts, creating a poor user experience.


        Sequential versus Interrupt-based Programming

        So far, we have written code that is strictly sequential in nature.  Execution starts at the top of a program, steps through the code and the logic of each line directly controls the inputs and outputs of the device and determines which lines of code will execute next.  Sequential code is easy to understand because you can kick back and trace through the program line by line from the comfort of your armchair with a printout and a pipe in your mouth (or not) and figure out what is going to happen next.  You don’t need to worry about anything happening outside of your little program.  The drawback to this is that you can only do one thing at a time.  If you want make it appear that you are doing more than one thing at a time, you must create a fast-running while loop and kick off the different events one after another.  We did that in the last lesson when we would look for a button press, and then blink an LED one time on each pass through the while loop. 


        When programming a system that is running an Operating System (OS), our programs run as threads or as processes.  Each thread or process can be written in a perfectly sequential manner and then OS will take care of giving each thread or process time on the CPU to do its work, creating the illusion that multiple things are happening at once, even on a single CPU core.  It is possible to run an OS in an embedded system on the EFM32 family, but it requires a lot of resources just to run the OS itself and it is not always the most cost-effective way to do it.  And because resources are limited and non-standard, an embedded OS brings its own share of headaches.


        In order to handle multiple tasks at once without an OS, firmware designers turn to interrupt sources (also known as Interrupt Requests or IRQ’s) that trigger interrupt handlers (also known as Interrupt Service Routines or ISR’s) to leap into action only when a specific event happens.  In fact, OSes are built on top of interrupts and abstract them from the programmer.  The EFM32 family has a great many available interrupt sources that you can configure and then write an interrupt handler to do something at the exact moment when the interrupt event happens.  We could rewrite our example from the last lesson with timer-based interrupts, and it would make the logic simpler in this case.  If you recall, we used an input button to select whether or not an LED was blinking.  One press would start it blinking and another press would turn it off.  We also had added the ability to put it into a deep sleep EM4 mode when the LED was off.  The procedure to do the same thing using interrupts follows.


        configure GPIOs
        wait for input button to be unpressed
        configure EM4 wake up mechanism
        configure button press interrupt
        configure LED timer interrupt
        LED_state = false
        define button pressed interrupt handler function:
        turn off LED
        wait for button to be unpressed
        enter EM4 sleep state
        define LED blink timer interrupt handler function:
              if LED_state == false
                    turn on the LED
                    LED_state = true
                    turn off the LED
                    LED_state = false
        while (true)
        enter EM3 sleep state


        By the way, I will use this pseudocode occasionally to communicate the intention of code without getting mired in the syntax of a C program. 


        The pseudocode assumes that we configure the timer for an appropriate interrupt period to be used to toggle the LED on and off, and configure the button interrupts for the correct pin and polarity.   The procedure is easy to understand and has the enormous benefit of being more power efficient because there is no while loop running all of the time.  The MCU will stay in a low power state nearly all of the time, only waking up when someone presses a button, or when a timer expires and it has to flip a single GPIO to a different state, and then it goes right back to sleep.


        The use of interrupts for our simple blinking LED is optional.  We have easily handled it with sequential programming.  But in order to create dimmers, faders, and “chasers” on multiple LEDs, while also handling the logic of whatever problem you are trying to solve, it would get pretty complicated to do all of that in a single while loop.  Interrupts and hardware timers are usually the right choice and will let our solution run on batteries for a longer period of time.


        We will pick up this conversation with the SysTick Interrupt in the next lesson.



      • Wireless Small Cells Represent a Big Opportunity

        phcallah-timing | 06/167/2015 | 09:33 AM

        I have been defining and marketing high performance timing and networking solutions for over 15 years. The new Silicon Labs Si5380 directly addresses a growing challenge in the wireless industry: exploding data demand.


        The wireless industry is deploying more wireless coverage using small cells to address high data demand areas. These small cells are growing rapidly with wireless service providers, but they present design challenges because they must be, well, small.


        “Small” means less board space, less plastic, and lower cost. Also, because the small cells may be outside on top of a roof or hanging on the side of a building, or in some cases inside in a closet, their performance needs to be immune to changes in operating temperature from heat, cold or power.


        Goodbye Cascaded PLL Timing. Hello Si5380, the New Hotness.

        Small cell timing and synchronization components today are based on traditional analog-based solutions called cascaded phase lock loops (PLL). The new Si5380 ultra-low phase noise clock generator revolutionizes this older solution on every count.


        Cascaded PLL solutions are 1) big, 2) power hungry, and 3) prone to disturbance from noise sources such as power supplies and vibration.


        Cascaded PLL

        Cascaded PLL Block Diagram


        In contrast, the new Si5380 is 1) 66% smaller, 2) 30% lower power, and 3) relatively insensitive to power supply noise and vibration effects. We achieve these impressive numbers using Silicon Labs’ breakthrough architecture, DSPLL.



        DSPLL Architecture


        Why the Si5380 is Better Than Cascaded PLLs

        As you might assume, DSPLL uses patented digital techniques to tune an integrated, low power, analog VCO (voltage controlled oscillator).


        What you might not assume is that the Si5380’s fourth-generation DSPLL technology provides a fully programmable bank of 12 reference clocks.  These clocks are used to provide very precise timing for the analog-to-digital (ADC) and digital-to-analog (DAC) converters used in today's multi-channel, multi-antenna radios required for high bandwidth LTE communications.


        Further, its phase noise performance, the spec that really matters in these applications, is better (i.e., lower) and more reliable across temperature, time and noise than any current solution on the market, including the bigger, more power hungry, less flexible, cascaded PLLs.


        Taking a closer look at integration, the Si5380 pulls almost all the external components required by cascaded PLLs, including the expensive VCXO and loop filtering components.


        Our Application engineers tore down dozens of small cells to measure the space required for cascaded PLL solutions versus our new hotness. The Si5380 reduces board space requirements by an average 187 mm2. That is about the size of the face of a Las Vegas tumbling die.


        Board Space Savings

        Board space savings of the Si5380 compared to cascaded PLLs


        From a power point of view, the Si5380 saves about 1/3 of the power required by cascaded PLLs. In a small cell form factor, this reduction can make the difference between an over-heated cell or one that doesn’t need a service call for years.


        Power Savings

        Power savings of the Si5380 compared to cascaded PLLs


        Small cells are often mounted in areas with noisy industrial equipment like HVACs and cooling equipment. Any vibration from that equipment can affect the delicate, expensive VCXO (~$2.00 - $4.00 in volume) required by the cascaded PLL.


        But not the Si5380. It uses a standard, low-cost crystal (~$0.20-$0.30 in volume) to provide a frequency reference for the Si5380.


        In other words, it doesn’t matter if the Si5380 is next to something that is vibrating. The system’s reference clocks will still be rock solid.


        Summary and Further Reading

        The Si5380’s fourth generation DSPLL has truly reached a pinnacle of simplicity, performance and integration. You can configure its 12 flexible outputs in your labs with simple desktop or iPhone software and immediately benefit from its lower power, smaller size and improved performance. Silicon Labs’ breakthrough innovation and simple setup makes your life easier.


        If you would like to read a deeper technical paper on the Si5380, click here.

        If you would like to go to the Si5380 page, click here.

      • Review of the SENSOR-PUCK

        Alx | 06/165/2015 | 06:58 PM

        1. Hardware

        The sensor puck is a nice peace of hardware in a tiny package. The features I'm mostly interested in are:


        • Battery powered so it could be put in a beehive to monitor environmental parameters
        • Sensors to monitor humidity and temperature (the included light sensor is not needed)
        • Bluetooth LE to get the sensor reading without opening the hive
        • Low power consumption for long lasting battery

        Additionally the schematics for the hardware is available as well as the source of the firmware running on the SENSOR-PUCK which is always good in case some things needed changing.


        2. Software

        The sensor puck comes pre flashed with a demo application that is sending the sensor readings via BLE broadcasts. It is really easy to download and install the corresponding application form the android app store. As soon as the application is launched it shows the current readings from the selected SENSOR-PUCK:




        4. Documentation

        The SENSOR-PUCK Users's Guide is very detailed and no question is left after reading it. Seeing the actual schematics of the SENSOR-PUCK is nice an adds greatly to the understanding of the capabilities of the SENSOR-PUCK beyond what the demo firmware provides.


        5. Usage as a Beehive Monitor

        The SENSOR-PUCK is a great demonstrator of the capabilities of SILICON LABS. The power consumption of the SENSOR-PUCK while measuring and broadcasting the sensor data (indicated by the green flashing LED) is average 1.5 mA which means according to the Users's Guide the battery on the SENSOR-PUCK will last approximately five days. Which is really great knowing the measurement is taken every second. So that makes approximately 432,000 measurements and bluetooth broadcasts on a single 3V coin cell battery. When it comes to beehives and environmental changes the update rate of 1 Hz is a bit of an overkill for the application as a beehive monitor. An update rate of about an hour would be sufficient which could mean a battery life of greater 60 days. I hope I can change the firmware to match my application needs and try the SENSOR-PUCK under some harsh conditions like the one in the picture below.




        Thank you Silicon Labs for letting my try out this great product.

      • Winning the Wrist—Wearables, Health and Fitness

        lethawicker | 06/163/2015 | 11:33 AM

        winthewrist.jpgThe present technology available in wearables is impressive. We’ve all seen someone (or worn ourselves) fitness trackers from Fitbit, Misfit Wearables, Polaris, Garmin, and so on. These track our steps, monitor our sleep and sleep quality, and track our heartrates when we exercise. They provide valuable information that gives us the power to make informed decisions about our own activity levels.


        Beyond step-tracking, though, is a whole frontier of wearable health applications. A partnership between Polaris Health Directions and the MD Anderson Cancer center uses the Apple Watch with breast cancer patients. The device will track everything from sleep to side effects, and promotes instantaneous feedback and action to make treatments as effective as possible.


        In another science fiction-accented application, the Bill and Melinda Gates foundation used wearables in India to connect children recovering from malaria to remote clinics. Since access to clinics is directly related to the survival rate, this application of wearable technology is literally saving lives.


        If these applications fill us with a sense of hope, then the future holds wonders galore. Imagine tattoos with technology implanted, or microchips that live under your skin. A little hard-core, maybe, but even a temporary tattoo could monitor health information for a specific period of time (say, a hospital stay) without invasive monitoring devices. A press-on patch could monitor your baby’s vital signs and give you more peace of mind than the fanciest baby monitor. The possibilities are endless.


        So how do we get there?

        Designing a wearable that breaks the mold and treads new ground is key to winning in the wearables market. With innovation flying ahead at lightspeed, how can you make sure that you’re staying ahead of the curve? It comes down to three things things—fine-tuning the design process itself, allowing function to dictate form, and using the best possible components to improve user experience.


        The design processRunner Wearing Fitness Watch

        Designing for a wearable tends to turn the design experience you’re used to on its head. Instead of listing out features and functions, you need to start from the user experience:

        1. Define the user experience—decide how your product will look to the user and on the user (Too bulky? Too flimsy? Just right?). Answer the all-important question: what will this device bring to the wearer’s life? Is it functional and easy to use? According to Times, thirty percent of wearables are abandoned after only six months—don’t let yours be one of them!
        2. Defining the use case—based on the analysis of the user experience, build the use case. Include the tasks your device will perform, resources it will require and the conditions of operation (dust, underwater, etc.), along with the data types you want it to track and collect. From there, you can start to identify the components that meet the requirements.

        Will Your Wearable Have to Withstand Severe Conditions?Allow function to dictate form (on the inside, at least)

        Now that you know what your wearable experience will be like, it’s time to evaluate its actual construction. Here’s an example. Wearables will almost universally require extremely long battery life, while demanding a lot of data gathering in between. Those seem at first glance to be contradictory goals, but:

        1. Is there an MCU that’s capable of gathering and processing a great deal of data while using little power?
        2. You might think of a wearable as ‘always-on,’ but it isn’t in practice. It sends bursts of data and is idle in between. Does your prospective MCU have the capability to go into deep sleep mode in between bursts of data, while still allowing periperhals like sensors to work independently?
        3. Once you answer those questions, you have a big part of the puzzle—your MCU—all spec’ed out.

        That’s just one example, but it drives home the importance of evaluating the form your wearable takes on the workbench based on the function you want to perform for the user.


        Using the best possible componentsUsing the Best Components

        When deciding on components, it’s a good practice to look at what other successful wearable manufacturers have used in their products. If they perform well (both in reviews and sales), you know that they’re doing the build right. Here are a couple of teardowns that show popular wearable fitness watches with their Silicon Labs components.


        Misfit Shine by Sparkfun

        Misfit Shine via Sparkfun

        That’s a Silicon Labs EFM32 Leopard Gecko MCU providing the Shine’s long battery life.


        Fitbit Surge by ifixit

        Fitbit Surge via ifixit


        Again, you can see that the engineers for Fitbit chose a Silicon Labs Gecko MCU, only this time they went with the Giant Gecko model with its ARM Cortex M-3 processor.


        These choices, from Misfit and Fitbit, harken back to our discussion on form following function. They wanted long battery life, with lots of processing power. So they chose Silicon Labs MCUs.


        If you’d like more information on winning the wrist, grab our whitepaper “Winning Design Strategies for the Wearable Market” and dive right in!


        If you have any questions or thoughts, please feel free to share them below.

      • Controlling External Devices: Part 4: Button Input and Deep Sleep States

        lynchtron | 06/161/2015 | 09:51 AM



        Controlling the LED Strip with a Button Input

        So far, our simple little embedded program is completely hard coded to do one thing over and over again, forever.  Let’s change that and start or pause the blinking with a pushbutton switch.  There are two pushbuttons on the Starter Kit, and like the onboard LEDs, the pushbuttons circuits are detailed in the Starter Kit Schematics:




        Both pushbuttons are pulled up to VMCU (the supply voltage for the MCU) with 1M-ohm resistors.  These are considered to be weak pullup resistors but they are enough to keep the MCU-side of the switches held high to VMCU until a user pushes a button.  At that time, the 100-ohm resistor that is tying the circuit to ground sets up a resistor divider that is 100,000 times closer to ground than it is VMCU, and the pushbutton circuit is pulled low.  The normally high circuit is momentarily pulled low, and we can detect that change in our firmware.


        You might think that UIF_PB0 and UIF_PB1 map back to port B, pin 0 and 1.  But they actually map to port B, pins 9 and 10.  PB0 stands for pushbutton 0 and PB1 stands for pushbutton 1.  Let this be your first lesson in to never assume anything in embedded systems development!  There is usually no feedback when you read from the wrong pin and no real way to figure it out except to double check all your connections.


        Let’s enable one of these pins as an input and read values from it in our loop.  We can use that input to cause the LED strip to blink only when the pushbutton is pushed.


        First, create a function to hold a single on/off cycle of LED blinking:

        void blink_one_cycle(void)
              // Turn on the LED
              GPIO_PinModeSet(LED_PORT, LED_PIN, gpioModePushPull, 1);
              // Add some delay
              for(volatile long i=0; i<100000; i++)
              // Turn off the LED
              GPIO_PinModeSet(LED_PORT, LED_PIN, gpioModePushPull, 0);
              // Add some more delay
              for(volatile long i=0; i<100000; i++);
        Then, create #defines for PB9 as an input button and call that function from within the new code:
        #define BUTTON_PORT     gpioPortB
        #define BUTTON_PIN      9
        int main(void)
          /* Chip errata */
          CMU_ClockEnable(cmuClock_GPIO, true);
          GPIO_PinModeSet(BUTTON_PORT, BUTTON_PIN, gpioModeInput, 0);
          while (1)
                // Grab the state of the button, 1 for high voltage, 0 for low
                bool live_button_state = GPIO_PinInGet(BUTTON_PORT, BUTTON_PIN);
                // If the button is currently pushed, blink a single cycle
                if (live_button_state == 0)

        If you have everything wired correctly, pressing the button will blink the LED strip and releasing it will stop the blinking.


        Now, let’s make the LED strip toggle, where one button press turns it on and a second press turns it off.  In order to do that, we have to keep track of the button state, as follows:

        int main(void)
          /* Chip errata */
          CMU_ClockEnable(cmuClock_GPIO, true);
          GPIO_PinModeSet(BUTTON_PORT, BUTTON_PIN, gpioModeInput, 0);
          // The initial state of the button is high when not pushed
          bool past_button_state = 1;
          // Start out not blinking
          bool blinking = false;
          while (1)
                // Grab the state of the button, 1 for high voltage, 0 for low
                bool live_button_state = GPIO_PinInGet(BUTTON_PORT, BUTTON_PIN);
                // Invert the blinking mode every time a button is pressed
                // which generates a low voltage on a pin
                if (past_button_state == 1 && live_button_state == 0)
                      past_button_state = 0;
                      // Invert the blinking mode, so that it is buffered and will
                      // keep blinking/not blinking when the button is released
                      blinking = !blinking;
                // Reset the past state when the button is released
                if (live_button_state == 1)
                      past_button_state = 1;
                // Finally decide if there is going to be a blink cycle or not
                if (blinking)


        So there you have it, you are now controlling the MCU from an input pin with a user interface.  But the MCU is just looping for infinity looking for a button press.  That wastes power, and since we probably want to embed this MCU into a battery-operated device, we can put it to sleep while we wait. 


        Put the MCU to Sleep While it Waits

        We can nearly turn the MCU off with a state called EM4, the lowest possible energy state in the MCU.  Upon exit of the state, it has nearly the same effect on the MCU as if we had pressed reset, so we cannot expect any of our variables to be preserved when entering and exiting EM4 state.  That’s OK for this example.  But you should treat EM4 as a “soft off” state.


        Unfortunately, the pins that are used for the pushbuttons on the Starter Kit are not capable of waking the part up from EM4, so if we put it into EM4, the only way we can ever wake it back up again is by removing power or pushing the reset button.  That’s not what we want.  Fortunately, we can use a jumper wire to connect the pushbutton circuit to an input pin that has the capability to wake the system up from EM4.

        The best place to find this information is in the Reference Manual, in the GPIO section, toward the end of the register section, you will find a few configuration registers that control EM4 Wake Up as part of the EMU peripheral.


        Configuration registers are used to control how the MCU peripherals operate and should not be confused with the ARM core registers.  The registers inside the core are used for executing assembly code.  Configuration registers are built in hardware and mapped by the memory controller into the normal memory address space, so that they are easily accessible by your firmware program. The header files for the MCU library created #define’s for all peripheral configuration registers, so you will see that I use those in the code below.  You can always hover your mouse over the name of a register, and the IDE will show you the actual memory location, if you are curious.


        Inside the GPIO configuration register space, the register called GPIO_EM4WUEN is the enable, which is also used to select the pin (or pins, if we want) to be used to wake the system up.  The GPIO_EM4WUPOL register holds the polarity of the wakeup pin, so we can configure it to wake up on a high or low voltage.  Note that we will also need to turn off nearly all GPIO’s in use manually since we are going to need to leave the GPIO module powered in order to look for a wake up signal on one of the GPIOs.  If we leave GPIO pins in an output mode, they will continue to drive those pins, consuming power.  That might be a good thing for your design, if you need to continue to drive a GPIO in a deep-sleep mode, but it could just waste power.


        I’ll pick pin PC9 for the EM4 wake up pin, since that is the only one I could find that is brought out on the Starter Kit and it is on the J100 jumper.  I will make a physical connection between the switch input pin PB9 and PC9, and then enable PC9 in the GPIO_EM4WUEN register.  So now the pushbutton not only enters the MCU on PB9, it also enters the MCU on PC9.  We could switch all of our code over to PC9 if we want or use them both.  They are electrically connected copies.




        Since the system is essentially waking up in a reset state when it comes out of EM4, we need to give the system an initial state that the user will think is just a continuation of the operation.  The user never knows that the system went to sleep and entered the EM4 state. 


        You will need to add the em_emu.c file to your emlib directory from the em_src directory, just like we did last lesson for em_gpio.c and em_cmu.c.  Then, add the header file to the top of your source code i.e. #include "em_emu.h".


        Then, create a new function called enter_em4() and call it from within the code that stops blinking.  Then, in order to set things up so that exiting em4 causes things to blink, I set the blinking variable to 1.  Then it will remain blinking until the button is pushed again.


        #define EM4_PORT              gpioPortC
        #define EM4_PIN               9
        #define EM4_WAKEUP_ENABLE     0x04  // Must change when changing w/u pin
        void enter_em4(void)
              // Set PC9 as an input, used to wake the system
              GPIO_PinModeSet(EM4_PORT, EM4_PIN, gpioModeInputPull, 1);
              EMU_EM4Init_TypeDef em4_init = EMU_EM4INIT_DEFAULT;
              // Retain GPIO modes while in EM4, to wake it up with button press
              GPIO->CTRL = 1;
              GPIO->EM4WUEN = EM4_WAKEUP_ENABLE;
              GPIO->EM4WUPOL = 0;     // Low signal is button pushed state
              // Wait for the button to be released before we go to sleep
              // or else we will immediately wake back up again
              while (!GPIO_PinInGet(EM4_PORT, EM4_PIN))
              // Add some delay to let the switch settle
              for(volatile long i=0; i<100000; i++);
              GPIO->CMD = 1;          // EM4WUCLR = 1, to clear all previous events

        Once inside of the enter_em4() function, we set up the chip to wake up to the PC9 GPIO pin on low polarity.  I added while loop to wait until the button is released, otherwise the MCU would immediately go to sleep, find the PC9 GPIO low, and exit from EM4 state.


        Finally, in the main code I switched the initial state of the blinking variable and added an else condition:

        int main(void)
          /* Chip errata */
          CMU_ClockEnable(cmuClock_GPIO, true);
          GPIO_PinModeSet(BUTTON_PORT, BUTTON_PIN, gpioModeInputPull, 1);
          // Wait for the button to be released before we start blinking
          // or else we will immediately go back to sleep
          while (!GPIO_PinInGet(BUTTON_PORT, BUTTON_PIN))
          // Add some delay to let the switch settle
          for(volatile long i=0; i<100000; i++);
          // The initial state of the button is high when not pushed
          bool past_button_state = 1;
          // Start out blinking at first
          bool blinking = true;
          while (1)
                // Grab the state of the button, 1 for high voltage, 0 for low
                bool live_button_state = GPIO_PinInGet(BUTTON_PORT, BUTTON_PIN);
                // Invert the blinking mode every time a button is pressed
                // which generates a low voltage on a pin
                if (past_button_state == 1 && live_button_state == 0)
                      past_button_state = 0;
                      // Invert the blinking mode, so that it is buffered and will
                      // keep blinking/not blinking when the button is released
                      blinking = !blinking;
                // Reset the past state when the button is released
                if (live_button_state == 1)
                      past_button_state = 1;
                // Finally decide if there is going to be a blink cycle or not
                if (blinking)

        If you run this code, you will see that the LED strip is flashing upon the initial start up.  When you press the pushbutton, the IDE will tell you that it lost contact with the Starter Kit and your LED will stop flashing.  That is because it has gone into deep sleep and it shut down the debug port.  When you press the pushbutton again, the LED strip starts blinking immediately, but it will not automatically connect to the debugger. 


        TIP: If you want to examine the state of a running system, you can do that by picking Run -> Attach To in the IDE menu.  This will connect to a running system without loading the flash nor issuing a reset to the MCU.  This only works if the system is powered on and blinking, and not in EM4 state. 


        Now your MCU is only consuming microwatts of power when the LED strip is off.  It’s a first step toward running your projects on a coin cell battery, solar power, or even on an energy harvesting solution. 


        If you are wondering if the MCU could drop into a deep sleep state while the LED is lit, to be awakened by a timer when it is time to turn off the LED strip while in the blinking mode, you are already thinking ahead to the next chapter.  I will cover one more foundational topic to cover on clocks, timers and interrupts on tap for the next chapter before we start working on other peripherals.



      • The Download on Drones and Data from IoT Hero Rich Hughes

        deirdrewalsh | 06/160/2015 | 05:25 PM


        Rich Hughes, IBM

        What do drones, Facebook, and the 1936 US Olympics basketball team have in common?  They were all topics of my fascinating interview with IoT Hero and data warehousing expert at IBM, Rich Hughes


        So, Rich, tell me a bit about yourself. 

        I've been working in IT and big data roles for years.  I also authored a book on the original dream team - the 1936 US Olympics basketball team - that was comprised of oil refinery laborers and film industry stagehands.


        How did you become interested in the Internet of Things?

        I've been a data guy for quite some time, so IoT is in some respects, was just natural growth-- just another data source. Manufacturing has been instrumented for at least 30 years, and Telco wireless networks have been spewing out call detail records for two decades.


        I know another area you are passionate about is drones. Public opinion varies widely on this topic. What’s the one thing you wished everyone understood?

        Drones (or Unmanned Aerial Vehicles) are playing a decidedly positive role in society.  Drones big advantage is to operate in air space where there are no alternatives-- so drones do help improve safety by inspecting public infrastructure (like bridges) and oil refinery gas emissions.


        What are some of the most interesting applications of connected drones today?

        Reminiscent of the early automotive manufacturing days, people everywhere seem to be acting on their drone dreams.  Facebook founder, Mark Zuckerberg, is implementing his dream of bringing high-speed Internet connectivity to all of humanity—carried on UAV wings longer than the 767s. Zuckerberg’s implementation, entitled, will require 1,000 UAVs. Each drone is mostly all wing and weighs less than a car.


        Flying high above weather and beyond the regulatory air space authority in most nations, these solar-powered drones will each maintain flight for at least three months at altitudes of 60,000 to 90,000 feet. Perched 13 miles above the earth,’s fleet is in its beta test phase, and although it faces many challenges, it is beaming connectivity to remote parts of the underdeveloped world.


        So cool! What are some interesting industrial applications?

        UAVs are being deployed in a variety of industry settings. One example is for reducing the complexity of managing large construction projects by using UAV-delivered site photos. Seeing the developing progress unfold through pictures taken in daily flyovers, Bechtel, among others, is better able to plan its supply chain construction schedule. 


        Also, by using the aerial perspective, many energy sector companies are advantageously monitoring their large installations.  Petroleum refineries, for example, have always feared explosions from gas leakage, and have found drone-enabled imagery a useful ally. An accepted drone practice is to continuously stream data to the cloud platform, prompting quick response to newly discovered gas leaks. BP complies with environmental laws by using drone photos to document gravel extraction work. First Solar inspects its panels through the use of UAVs, thus enhancing its maintenance plans. In these examples, energy sector safety, regulatory compliance and operational efficiency are being improved by the early adoption of drone technology.


        What role do hobbyists play in drones?

        The casual hobbyist can now enjoy programmed flight under their direction.  In general, drones are reshaping the personal electronics market. For example, GoPro camera–equipped drones are easy to operate and are easily within consumer reach at under 1,000 dollars. This disruptive technology is having an impact on government entities, as the consequences of drones flying for months in what amounts to low-earth orbit are being considered. Commercial flight safety and privacy concerns will certainly be tested by the introduction of flight from many thousands of hobbyists. Add up these impacts, and without a doubt UAVs are reshaping our world view.


        It’s a big question, but in your opinion, what does the future of IoT look like?

        By trade I am a non-fiction writer and the IoT reminds me of everything science fiction. Take your pick with everything, especially humans, being instrumented-- there is the chance for both great improvement and the sinister in the IoT era of the future.

      • Bluetooth Classic and Bluetooth Smart Live Happily Ever After

        lethawicker | 06/159/2015 | 04:13 PM

        Running App


        Your relationship with Bluetooth Smart and Bluetooth Classic has always been a little bit strained. How were you supposed to mediate between the two, when one required low power and the other a high data rate? There are millions of legacy mobile phones, PCs and tablets still using Bluetooth Classic, but the newest wearables and connected home gadgets use Bluetooth Smart. We’re here to tell you that your struggle for harmony is over.


        Today, Silicon Labs announces the new BT121 Bluetooth Smart Ready module and software, and with it, the ability to develop for Bluetooth Smart and Bluetooth Classic on a single module. The BT121 module includes a pre-certified, fully-integrated, high-performance solution that is comprised of a Bluetooth radio, MCU and on-board Bluetooth software stack supported by our Bluetooth Smart Ready SDK and our easy-to-use BGScript™ scripting language.


        BT121 Module


        What all this means for your designs is faster time-to-market, and reduction in development costs and compliance risks. You get a versatile, plug-and-play Bluetooth solution that’s ideal for applications that require connectivity to legacy devices that only support Bluetooth Classic, alongside applications that that use Bluetooth Smart.


        This “best of both worlds” solution delivers:

        • Ultra-low power and high-data-rate Bluetooth connectivity in one module
        • Bluetooth radio range of up to 400 meters
        • Low-power ARM® MCU
        • Fully certified Bluetooth Smart Ready protocol stack
        • A compact 11 mm X 14 mm package

        Finally, and perhaps best of all, no RF or Bluetooth protocol development experience is needed to work with the BT121 module in Bluetooth designs. You can use the module as a peripheral along with an external host MCU, or applications can be embedded into the built-in MCU with the Bluegiga BGScript scripting language. You’ll be able to create a completely standalone design with minimal external components.


        Find out more about the BT121 module and share your thoughts below!

      • Digging Data--A Celebration of My Favorite Goonie

        lethawicker | 06/155/2015 | 10:36 AM

        You’ve been under a social media rock if you haven’t heard it’s the 30th anniversary of The Goonies, a classic 80s film that has attained cult status among kids of all ages. I’m sure there are Internet fights galore over who’s the ‘best’ Goonie, but I can only tell you my favorite—Data. I love Data because even though his gadgets fail (frequently), he just keeps on inventing. That’s a trait I think engineers and innovators everywhere can relate to!


        A fun game to play is to imagine how today’s technology, particularly the Internet of Things, could have transformed the way Data made his gadgets, and boosted their success rate. In other words, if Data were inventing today, what would he invent? How would he invent?


        First, let’s look at the big pictureImage courtesy of

        Data’s storage and deployment method was, to be fair, a little bit bulky and unreliable. What if instead of a mess of extender arms and belts and ties, he had a utility belt he could control from a wrist-top wearable? I can see Data hacking into one of the larger fitness wearables and turning it into a control system for his gadgets, which he could connect to the watch with wireless chips using Bluetooth™ to create a near-field network of all the devices. Then selecting and deploying one would be as easy as pulling it around the front of the utility belt and hitting the button on the watch.


        Now for some specifics

        However Data chooses to control and select his gadgets, you can’t argue that they’re anything less than brilliant. Let’s take a look at a few of my favorites, and how Data could put a new spin on them using today’s technology.


        Image courtesy of TheComplex.comOil-Spitting Sneakers

        You know what would be an awesome upgrade to an already awesome idea? What if Data found a way to use modern sensors for temperature, humidity and pressure to change the tread of his sneakers so they’d always be just right for the terrain at hand? That way he could squirt out the oil and be sure to keep his own footing.


        Chattering Teeth Grappling GunImage via

        Okay, so I have to suspend my disbelief on this one, but it’s still a huge favorite. Let’s play the what-if game here, too. What if instead of a manual deployment, which could always come too late (oh no!), the mechanism had an accelerometer and deployed automatically if it sensed an abrupt change in position? This could have a few down sides, but really, we’re assuming chattering teeth can hold up a pre-teen. I think it could work.


        Dual Pop-Out Flashlights

        Remember when Data was all excited to bring light to the darkness? Only to have his lights fizzle out after a few seconds? Ouch! Today, he could use low-power microcontrollers and LEDs to get incredibly long battery life for his pop-out flashlights.


        The sky is literally the limit for Data when he has modern technology inspired by the IoT at his disposal. And with all the boards and know-how out there on the Internet, he could learn how to design and program in no time!


        Image via twitter.comSpecial Bonus Round

        At the end of the film, Data’s dad tries to use his own invention—a pop-out flash camera. I thought of the perfect ultra-high-tech solution for Data’s dad. What do you think?


        So who’s your favorite Goonie? Do you have any ideas of how Data could have used modern technology to help out his friends? Share below!

      • Industrial Automation Webinar Series

        Nari | 06/154/2015 | 10:57 AM

        IA webinar series.png


        Join us for an Industrial Automation Webinar Series where we take a deep dive into the areas making the largest impact in this revolution.


        Webinar topics

        • Are you Completely Isolated? Digital and Power

        Isolation design challenges and others will be covered on this webinar by subject matter experts from Silicon Labs.


        Americas: Tuesday, June 23rd 10:00 AM PST

        EMEA: Wednesday, June 24th 10:00 AM BST

        APAC: Wednesday, June 24th 10:00 AM HKT


        • Bluetooth for your Industrial Needs

        This webinar will cover Silicon Labs’ Bluetooth module solutions and the benefits they provide for Industrial designs:

        -              Long Range

        -              Ease of use ( No RF or Bluetooth experience required)

        -              Standalone operation using BGScript™


        Americas: Wednesday, June 24th 10:00 AM PST

        EMEA: Thursday, June 25th 10:00 AM BST

        APAC: Thursday, June 25th 10:00 AM HKT


        • 8-bit or 32-bit to get your motor running

        This webinar will cover the technology behind these solutions.

        -              Intelligent PWM control

        -              Lowest EMI Isolated gate drivers

        -              Software and Tool support


        Americas: Thursday, June 25th 10:00 AM PST

        EMEA: Friday, June 26th 10:00 AM BST

        APAC: Friday, June 26th 10:00 AM HKT