Official Blog of Silicon Labs

    Publish
     
      • I Was a Teenage Thunderboard Sense Developer

        Lance Looper | 06/179/2017 | 09:04 AM

        This summer we invited two high school students, Ian and Cade, to spend a couple of weeks getting to know Thunderboard Sense. Here they summarize what happened when they applied the sensor-to-cloud development kit to the game of tennis. 

         

        Who We Are

        Our names are Ian Wood and Cade Nowicki and we are two high school interns from the central Texas area. Our task was to find an activity or object that could be enhanced or improved by the Thunderboard Sense IoT Development Starter Kit (for example, using the heat temperature sensors to find your daily weather).

         

        IMG_5082.jpg

         

        Our Project        

        With this basic information, we wanted to do something fun and related to a summertime activity. With this in mind we decided to use tennis as our topic. We placed the Thunderboard Sense, which has a variety of sensors, on a tennis racket to see how different environmental factors and position of the athlete affect performance. Since the Thunderboard Sense gathers all kinds of data relating to the environment and position, we were pretty sure it could help us answer our question. 

         

        TB Sense1 copy.png

         

        What We Found

        We produced a variety of results during our experiments. The most fascinating was when we discovered that as UV increased, the amount of acceleration measured also increased. The two are directly proportional. The graphs below shows one with a UV of 0 and another with a UV of 9. The graph on the left show a slight change in acceleration while the graph on the right displays a more dramatic change in acceleration.

         

        Since the main difference between the two environments was UV, we can conclude that as UV increases so does the acceleration. Even though other environmental factors changed between the two trials, we believe that the change in UV is more likely to be the main difference because most other environmental factors changed very little as shown below in the spreadsheet.

         

        TB Data copy.png

         

         

        TB Sense Data.png

         

        The change in the Z axis, shown in the graphs, is us swinging the racket while the x and y axis is the angle of our hand position and body orientation.

         

        How the Thunderboard was Beneficial

        The Thunderboard Sense gave us the chance to learn more about how the future and technology is becoming more cohesive. Our experience using the Thunderboard Sense also gave us insight into the real world of electronics giving us students an idea of how technology is making the world a more connected place.

         

        Thunderboard Sense

        The chip in general was incredible! The size of the chip for the amount of sensors it had was amazing. This product was great when we tested our idea for the chip because it was capable of doing so many tasks, the use of the Thunderboard is seemingly endless. This task we were given has taught us so much about real life projects and it gave us a glimpse of what our futures may hold.

         

        Check out their video recap below:

         

        About Cade and Ian

        Cade Nowicki attends Dripping Springs High School in Dripping Springs Texas. He's interested in the engineering field and participates in his school's F1 competition, where a team designs and markets a mini F1 car. The team recently attended Nationals where they got some real world experience with engineering, but nothing like his experience with Thunderboard Sense.

         

        Ian Wood is a junior at James Bowie High School in Austin, Texas. He's also interested in engineering and plans to study it in college. Before his internship at Silicon Labs, he had little experience in real-world project management, but after this summer has a better understanding of how to schedule and manage projects.

      • Employee Spotlight - Alex Hakkola

        Lance Looper | 06/177/2017 | 01:54 PM

        Alex Hakkola joined the Silicon Labs Broadcast/Automotive team as Systems Engineer in July 2014. In his role, he works on the Radio DSP portion of Silicon Labs tuner parts.

         

        spotlight-banner1.jpg

         

        He is responsible for collaborating with a variety of groups to best serve all of Silicon Labs’ customers including: the MCU team to make sure parts are configured correctly, the validation apps team to ensure parts pass the necessary specifications, the design team to find the best way to make the chip work with hardware and software, and customers’ apps teams to resolve issues customers may have.

         

        Alex’s supervisor, Dana Tiapale said, “Alex is able to quickly design and debug the signal processing code we need. At the same time, he has mastered the skills needed to produce small footprint algorithms and code.” Tiapale was especially impressed when Hakkola managed third party developing code for a part. Tiapale remarked, “[Alex] produced the specifications, created the tool stream and pc images needed by the developer, oversaw their development and integrated those deliverables into our code base.”

         

        Hakkola’s favorite thing about working at Silicon Labs is “getting to ask questions of so many smart people” and having so many people to look up to professionally. His favorite corporate value is “We create customer value and commercial success through innovation and simplicity.” He said, “I like to think of this goal because it forces me to find the root cause and create a solution that addresses it quickly.”

         

        Something coworkers may not know about Hakkola is he loves motorcycles. Tiapale said, “You can really get him to geek out talking about his motorcycle suspension.” When asked if he had a time machine, what point in the past or future would he visit, Hakkola said, “ I’d visit the past me at the time that I was starting my work here and try to educate myself on the lessons that I learned so far.” He continued, “My hope would be that after I returned from this trip, I would find myself in a positive feedback loop where I kept visiting my past self and learning more with each visit. This would allow me to gain many more years of experience and maybe more important, humility. I would see my only two years’ prior self and realize how much I learned within those two years, and how much my colleagues have helped me be a better engineer in that time.”

         

        Smart answer from a smart engineer. We’re proud to have you on our team, Alex Hakkola. Keep up the great work!

        AlexH_Blog.jpg

      • June 2017 Member Spotlight: baarini

        Siliconlabs | 06/171/2017 | 11:08 AM

        We are featuring one of the Silicon Labs Community members who is active or new in the community on a monthly basis to help members connect with each other.

         

        Meet our June member of the month: baarini

         

        profile.png

         

        Q: Congrats on becoming our featured member of the month! Can you introduce yourself to our community members?

         

        I am an Electrical Engineer based in Jeddah, Saudi Arabia. I started programming since school days & continued through university. I started to show interest to smart lighting without adding extra cables & wires to control the lights (DALI system is an example) & to make the points "online" & controllable anytime anywhere.

         

        Q: How did you know about the Silicon Labs Community?

         

        Through research over the internet & Silabs dev. kits brochures

         

        Q: What features, products, services would you like to see in the future from Silicon Labs?

         

        - More commercial thermostat can be interfaced with other protocols widely used in the market
        - Industrial applications solutions (industries, plants ..)
        - Street Lighting control solutions

         

        Q: What advice would you give to someone new to the community?

         

        Community is very rich in subjects & solutions to common problems; just read

         

        Q: Thanks for answering the questions. Any final comment?

         

        I'd like to see in the near future more reference designs supporting EFR32MG SoCs especially HA applications.

      • Outstanding Performance by Silicon Labs’ Isolation in University Study

        Lance Looper | 06/170/2017 | 10:00 AM

        Recently, it was brought to my attention that Silicon Labs’ Isolators were part of a study at Aalto University in Finland. The study was conducted by Mikael Lumio as part of his Master’s program. The results are interesting and one of the most comprehensive, independent studies of isolation performance I have seen.

         

        The full thesis is available here.

         factory-floor copy.jpg

         

        Mr. Lumio approaches some of the concerns surrounding CMOS-based isolation straight on. In his thesis, he compares different types of CMOS isolation against each other and against the legacy optocoupler solutions. Capacitive-based isolators (the preferred technology from Silicon Labs), inductive (transformer)-based isolators, and magnetoresistive-based isolators are all included in the analysis. For many specs, the capacitive-based solutions outperform other technologies. Compared to optocouplers, Mr. Lumio’s analysis clearly shows advantages of CMOS-based isolation in common-mode transient immunity (CMTI), current consumption per channel, data rate, skew, and other timing specifications.

         

        In addition to comparing datasheet specifications, Mr. Lumio also compares isolation performance. Mr. Lumio’s thesis does an excellent job of describing the different isolation parameters that are commonly specified by international certifying agencies. Then, the thesis uses those descriptions to aide in the comparison of different CMOS isolation technologies. For all technologies, the isolation capability is on par with legacy optocoupler devices. The only lagging parameter is in surge immunity, but CMOS-based isolators are catching up fast.

         

        Mr. Lumio’s thesis is particularly focused on the application of isolation technology to variable frequency drive (VFD) systems. VFDs are increasingly used in all types of motor drive applications. Motor drive efficiency standards worldwide encourages the use of variable frequency drives wherever it is applicable to a motion application. The thesis lists, “blowers, compressors, conveyor belts, cooling and recirculating pumps, cranes, factory robotics, fans, elevators, hoists, mixers, paper mills, and printing presses,” as relevant applications where VFDs are prescribed for efficiency improvement.

         

        VFDs are usually powered from rectified AC line inputs and are used to provide a three-phase, AC output to a motor. The supply provides a high DC voltage for the rest of the system. Isolation is necessary in several parts of the typical system. The VFD is converting the DC supply into an AC signal through a multi-phase inverter stage. The inverter has switches connected to the high voltage power rail and isolation must be utilized to protect the control circuit. The output of the drive is connected to the windings of the motor. Often each winding has an isolated sensor connected for current and voltage measurement. Both safety isolation, for protection of operators and people interfacing with the system, and functional isolation, for circuit protection, are necessary in the system.

         

        Besides specific isolation requirements, Mr. Lumio looked at additional features of CMOS-based isolation to evaluate its suitability for use in VFDs. Electromagnetic compatibility (EMC) was of particular concern. ESD performance was also evaluated. Finally, the relative cost of the various CMOS isolators was considered.

         

        On the subject of cost, the thesis found that at mass production volumes CMOS-based isolators are less expensive. In his analysis, Mr. Lumio included not only the device cost but also indirect costs including the reduction in PCB area and component count. For the typical fieldbus serial communication application, Mr. Lumio’s research indicates a close to 1/5 cost reduction in moving from a legacy optocoupler solution to a modern isolation solution. For a more specific IGBT drive function, the cost reduction wasn’t as large. It was still significant, though, at approximately 1/10.

         

        EMC was a focus for Mr. Lumio’s thesis because of the environments in which VFDs operate. High voltage switching associated with motor drive means that the components used must be immune to a large amount of electromagnetic noise. Mr. Lumio found that modern CMOS-based isolators performed as expected even in the presence of large amounts of electromagnetic interference. Silicon Labs’ isolators showed great robustness in all test. For example, in the RF immunity evaluation, Silicon Labs’ isolator was free of errors even in the presence of 20 V/m RF energy.

         

        In his own words, Mr. Lumio writes, “Digital isolators from Silicon Laboratories were in the top group of manufacturers in all of the tests.” His thesis is additional evidence for the suitability of CMOS isolators in demanding applications that require high reliability, like motor drives. We’re proud that Silicon Labs’ capacitive based isolation fared well in all of Mr. Lumio’s analysis and it’s our goal to deliver higher performance, more reliable isolated circuits than competing solutions. For more information, visit our Isolations Solutions page.

         

      • Illuminating the Path to Health: IoT Hero Monitors Critical Vitamin D Intake with Style

        deirdrewalsh | 06/166/2017 | 09:02 AM

        We recently spoke with CEO Marina Nikeschina of e-Senses and Pim van der Meer, project lead development at HYB, a fresh team on the IoT scene that just celebrated its first birthday. e-Senses is focused on health and wellness and is determined to help people achieve the vitamin D levels they need in a way that’s never been done before - with a cutting-edge ring.

         

        Banner-esense.jpg

         

        For folks just now hearing about you, tell us about your business; how did you get started?

        Well, our original inspiration was actually due to a friend of the founders who had concerns about elderly patients. Essentially, in his research he realized that light had a profound effect on happiness and quality of life in the individuals he saw. Seniors who get outside are eating better, sleeping better, virtually everything better than people who stay inside. Older patients who are aren’t going outside, they get depressed, they get sick.

         

        So he asked if it was possible to make something that you can put on people to see how much light they receive. Troubleshooting this idea, we realized that the only two parts of our body typically not completely covered in clothes as the seasons come and go are our face and hands. So we decided to make a ring, because a ring is one accessory that’s unisex and just not really intrusive for people to adopt. That’s how our Helios Smart Ring was born, and it’s the first vitamin D tracker in the world.

         

        Starting out, we decided to look at a lot of medical studies about light, vitamin D, and sunlight. And we were surprised to learn about the many advantages you can get for free from the sunlight. So we ultimately decided to make a very serious product, not just a small, simple tool to measure basic light exposure, but a wearable device for everyone.

         

        And we designed a corresponding app that helps breathe life into the data the ring collects; it has three modes or “coaches.” Mode one is a “Vitamin D Coach” that shows how much vitamin D you are absorbing every day from the sun by the minute. Mode two is the “Sunlight Coach” that helps measure the strength of the sun and tells you how long you can stay outside without any danger. Then we have a “Daylight Coach” mode that calculates the minimum amount of light that you need every day and displays in percentages how far along you are for your daily goal.

         

         

        Tell us about some of the challenges you faced in developing such a small device. I know you had to hit some hurdles getting this much functionality out of such a small, unobtrusive object.

        I would say we faced two main challenges in development. The first challenge was how to charge the device. The first prototypes used contact points for charging, but the low pressure on the charging pins that the limited weight of the ring gives will result in bad contact due to corrosion of the contact points. So we retooled the ring to have its own charging coil inside and make the charging process exclusively wireless, eliminating that issue entirely.

         

        Secondly, achieving a long battery life was challenging. Our initial goal was to have at least a 24-hour battery life, but our initial prototypes were only holding a four- to six-hour charge. That obviously wasn’t acceptable to us. After what could only be described as a bout of sheer obsession to solve this problem, a very talented engineer got the battery life up to two to three days of wear, which we’re really pleased with because of the ease of use that grants our users. 

         

        Well, we think this is a really amazing health application. Can you also tell us what Silicon Labs products are you using in the Helios and why?
        We are using the Si1133 in the Helios Smart Ring. It was very difficult to find components for our recent circuit board because we were looking for the smallest components in the world. A ring is such a small form factor and you want durability as well. Everything we are using is the smallest, smallest, smallest. But we didn't want to compromise on quality. We were looking for sensors that can measure daylight and sunlight accurately, and that were small, light, and production-ready. We came across Silicon Labs’ solution and knew this was our winner.

         

         

        In your view, what does the future of IoT look like in the next 5–8 years given your experience?

        It’s obviously been amazing to witness how widespread the IoT has become now that network and power solutions have evolved to allow so many product designs actually come to life. That said, what we most hope to see is that we don’t overly automate the human experience itself. Such as with the Smart Home concept, it’s great that you can open and close a window and control a thermostat remotely—those are things that can save energy costs and add a level of convenience that is enriching for an end-user. But there is no reason to automate someone’s blankets being rolled off of them in the morning or every other small detail of every daily routine in life. We hope that the IoT’s biggest gains will be rooted in truly enriching people’s lives and health in ways that can matter the most.

         

         

         

      • 5 Trends for the Smart Home from Computex 2017

        Lance Looper | 06/159/2017 | 10:00 AM

        Jason Rock, a strategist in our IoT division, recently attended Computex 2017 in Taipei and shares with us some of the key take-aways from the event.

         

        I was excited to be coming back to Computex after a several year absence because unlike CES, this event is about technology companies showcasing their offerings to each other rather than to end users.

         

        Here’s a look at the five trends I noticed:

        • Multi-protocol smart home devices
        • Certifying for multiple ecosystems (Amazon, HomeKit)
        • Emergence of IoT gateways
        • Security and regulatory compliance is a default requirement
        • Partnerships are critical for success

        Computex Banner.jpg

         

        Multi-protocol Smart Home Devices

        One of the barriers to mainstream IoT adoption is the numerous wireless protocols being deployed: Bluetooth, Thread, Wi-Fi, zigbee, and z-wave. At the event, manufacturers were asking for support of these protocols on single radio chipset.  While some believe that these protocols will converge down into one predominate standard. If you look at the evolution of the mobile phone you will notice a trend that counter this prediction.

         

        There was a time where standards such as CDMA, GSM, and LTE along with differing carrier frequency spectrums kept phones limited to specific networks. As telecommunications evolved, what actually happened is the phones themselves were designed to communicate to these protocols, thereby allowing them instead roam across these varied mobile networks. In many respects IoT will likely follow the same path. End device manufacturers are adding radios from vendors such as Silicon Labs which can support multiprotocol communication. We are now seeing Bluetooth commissioning support being integrated into devices such as media hubs, light bulbs, and even smart plugs. These devices either switch protocols via power-cycling or can simultaneously support Bluetooth and another protocol such as zigbee dynamically with a single radio transceiver by time-slicing between protocols.

         

        Supporting multiple protocols makes device commissioning simpler with a mobile phone’s Bluetooth connection. Over time, the devices themselves will be able to adapt their protocol to an intended IoT ecosystem.

         

         Robot_Size.jpg

         

        Certifying for Multiple Ecosystems (Amazon, HomeKit)

        Though in the short term, even with devices being able to speak in various protocols and hubs now being integrated into gateways, today in order to leverage the latest voice platforms, device manufacturers need to build devices and go through a certification process with the key voice intelligence providers. In response, semiconductor providers are supplying ecosystem software development kits and user guides to help accelerate this development process.

         

        Emergence of IoT Gateways

        As the IoT continues to expand, the popular IoT radio protocols will be internally supported within everyday gateway platforms. We’re beginning to see an increase in requirements by device manufacturers for the integration of IoT radios into platforms that were strictly using Wi-Fi for wireless communication. Those small protocol bridges and hubs one needed to connect zigbee lights onto one’s home network are now being integrated into the latest WiFi mesh platforms such as Samsung Connect Home TM and are being integrated into internet access modems from service providers such as Comcast’s newest XB6 platform.  As these 2.4GHz radios become tightly co-located into a single platform, manufacturers are utilizing managed wireless coexistence algorithms to ensure each radio has access to the shared frequency spectrum.  This helps prevent the possibility of high-speed video streaming of one’s favorite show impacting the ability to adjust the smart lights from their mobile phone while on the couch.

         

        Security and Regulatory Compliance is a Default Requirement

        Thanks to recent regulatory oversight, manufacturers can no longer ignore security vulnerabilities and further must prevent users from modifying antenna transmit levels beyond tested levels. In turn, these manufacturers are turning to their suppliers to ensure their features meet these strict requirements.

         

        As examples: the U.S. Federal Trade Commision (FTC) has gone after device manufacturers of gateways for not having adequate security.  Additionally, in recent news the U.S. Federal Communications Commission (FCC) has withheld certifying products that allow end users the ability to bypass tested transmit level settings set at the factory. The results of these actions have come in the form of fines, negotiated settlements, and delays in receiving regulatory certifications.

         

        Partnerships are Critical for Success

        Even today, providing a complete IoT ecosystem from device-to-cloud is still too hard for a single company to deploy. As result, it requires platform vendors being open to allowing devices from one another manufacturer to gain entry onto their platform through tested and assured compliance.

         

        In turn, a platform vendor will then work with ecosystem providers to enable cloud services such a voice intelligence (Amazon, Google to name a few).  And further, we’re seeing cloud services cross-license access to each other’s device data to provide their customers a richer user experience with their IoT devices.

         Computex_Demo_Sized.jpg

         

        I believe these trends indicate that today’s IoT products are within reach of a larger mainstream market.  With this realization in mind, I’m looking forward to seeing what Computex 2018 has in store.

         

         

      • Chapter 6 Addendum: Input Modes Explained - Part 3

        lynchtron | 06/156/2017 | 05:06 PM

        ch6_addendum.png

        In the last section, the ACMP peripheral was used as an analog input device to level-shift the light detected from an LED on the light sensor.  In this section, we will configure the TIMER peripheral to receive input edges that can be used to decode a quadrature encoder.  We will also configure the PCNT as an input counter to count pulses from the blinking LED of the prior sections. 

         

        TIMER

        The TIMER peripheral was first covered in chapter 5 and used for measuring time or generating output waveforms, but it is also a versatile counter that is capable of capturing edges on the input pins to the MCU. 

         

        In another mode called Quadrature Decoder mode, the TIMER module can be used across two TIMER capture pins to measure the speed and direction of a wheel.  The quadrature mode can work in either X2 or X4 modes, which simply means that both rising and falling edges of one or both pins can trigger counting events. 

         

        To demonstrate the basic operation of the TIMER input mode, we will configure it to capture the direction and speed of a wheel using a quadrature encoder.  The ACZ11 mechanical encoder can be purchased on Mouser here, or you can find them on Amazon.  This one has 20 detents, which means that the rotation of the shaft provides a clicking feel and generates edges on the encoder pins with each click.  We can use such an encoder in X1, X2, or X4 modes.  The TIMER peripheral cannot count in X1 mode, but the PCNT module in the following section can only count in X1 mode. 

        ACZ11_SPL.jpg

        The ACZ11 has five pins: three pins on one side make up the encoder, the middle pin is ground, and the encoder mechanically connects the outside pins to this ground pin as the shaft rotates.  It is up to us to connect the outside pins to a pullup resistor so we can detect when the encoder is connecting a pin to ground.  The other two pins (on the other side of the encoder) make up a Single Pole Single Throw (SPST) switch when you push in on the knob, just like the volume/power knob on some automobile radios.

        6_quadrature_decoder_scope_setup.png

        When we rotate the encoder clockwise, edges on pin B lead pin A.  When we rotate counterclockwise, edges on pin A lead pin B. The width of the pulses is determined by the speed of rotation, and the signals are always at 50% duty cycle to one another. 

         

         The timer has three compare/capture pins, CC0, CC1, and CC2.  All of the pins can be used to clock the TIMER CNT field, but only CC0 and CC1 can be used to run the quadrature decoder.

        6_quadrature_waveforms.png
        No resistors are needed when using the encoder with the EFM32.  One of the input modes available on the GPIO peripheral is input mode with pullup, where the inputs provide ~40k ohm pullups to VCC.  This mode makes the connections easy.  Just connect one of the outside pins of the encoder to PD1, and the other to PD2.  These are TIMER0 location #3 compare and capture pins.

        6_quadrature_decoder_connections.png

        When TIMER is used as an input peripheral, it is counting incoming edges and not keeping track of time.  In quadrature mode, it is determining position or some fraction of rotation and not the rate of rotation.  To measure the rate of rotation, you need another timer to keep track of the sample period.

        First, we will re-use the one second timer and interrupt from the ADC section of this chapter.  TIMER1 will keep track of time and interrupt after one second.  Then, we will set up TIMER0 as a quadrature counter connected to PD1 and PD2.

         

        // This timer doesn't keep track of time, but edges on the input pins
        void setup_quadrature_timer()
        {
              CMU_ClockEnable(cmuClock_TIMER0, true);
              CMU_ClockEnable(cmuClock_GPIO, true);
         
              // Set CC0 channel defaults
              TIMER_InitCC_TypeDef timerCCInit = TIMER_INITCC_DEFAULT;
              timerCCInit.edge       = timerEdgeBoth;          // X4 mode
              timerCCInit.filter     = true;
         
              // Configure CC channel 0
              TIMER_InitCC(TIMER0, 0, &timerCCInit);
         
              // Configure CC channel 1 in exactly the same way
              TIMER_InitCC(TIMER0, 1, &timerCCInit);
         
              // Set TIMER0 defaults
              TIMER_Init_TypeDef timerInit = TIMER_INIT_DEFAULT;
              timerInit.mode       = timerModeQDec;      // Quadrature mode
              timerInit.quadModeX4 = false;             // X2
         
              // Configure TIMER0
              TIMER_Init(TIMER0, &timerInit);
         
              // Route the input pins to TIMER0 from Location 3 and enable CC0 and CC1 in the route
              TIMER0->ROUTE = (TIMER0->ROUTE & ~_TIMER_ROUTE_LOCATION_MASK) | TIMER_ROUTE_LOCATION_LOC3;
              TIMER0->ROUTE |= TIMER_ROUTE_CC0PEN;
              TIMER0->ROUTE |= TIMER_ROUTE_CC1PEN;
         
              // Enable the GPIO pins needed
         
              // CC0 on Location 3 is PD1
              GPIO_PinModeSet(gpioPortD, 1, gpioModeInputPullFilter, 1);
         
              // CC1 on Location 3 is PD2
              GPIO_PinModeSet(gpioPortD, 2, gpioModeInputPullFilter, 1);
        }

        I have enabled the filter on the CC0/CC1 configuration because I saw switch bounce on the signals on the mechanical encoder when viewing the output on the oscilloscope.

         

        After setting up the two timers, the main while resets the TIMERs on each loop, then goes to sleep until TIMER1 wakes the MCU up after one second.  If we set up a variable called detents as an int16_t, only the TIMER0->CNT value is needed to fetch both direction and the number of detents detected.  This is because TIMER0->CNT is a 16-bit register, and the quadrature counter counts backwards when the shaft is rotated counterclockwise, producing a negative count.  However, in the code, you can also see how to fetch the direction bit from TIMER0->STATUS, and the results are consistent between the two methods.

         

              while (1)
              {
                    // Reset the timers
                    TIMER0->CNT = 0;
                    TIMER1->CNT = 0;
         
                    // Sleep until the timer expires
                    EMU_EnterEM1();
         
                    // One second has passed, fetch the number of detents
                    int16_t detents = TIMER0->CNT;
         
                    // Correct for X2 to X1 mode
                    detents = detents / 2;
         
                    if (detents != 0)
                    {
                          // Fetch the direction
                          uint8_t direction = (TIMER0->STATUS & 0b10) >> 1;
         
                          // calculate the speed of rotation per minute, RPM
                          int16_t rpm = (detents * 60) / 20;
         
                          // Print out the message
                          if (direction == 1)
                          {
                                printf("Shaft Direction:CCW Detents:%d RPM:%d\n", detents, rpm);
                          }
                          else
                          {
                                printf("Shaft Direction:CW Detents:%d RPM:%d\n", detents, rpm);
                          }
                    }
              }

        I had to correct the count from X1 to X2 by dividing the TIMER0->CNT by 2 on every click of the encoder.   Note that you must do this calculation after TIMER->CNT has been converted to an int16_t or else you will lose the sign bit.  The check of detents != 0 ensures that we don’t see any output on the SWO debug printf console until there is rotation on the encoder.  The revolutions per minute (RPM) can be calculated by the number of detents times 60 seconds, divided by 20 detents per revolutions of the encoder.

         

        You should see something like the following on the SWO console when you run the code, first by hand, and then by using a cordless drill to turn the knob at the drill's fastest setting.

         

        Chapter 6: Input Modes!
        Shaft Direction:CW Detents:1 RPM:3        << Turning by hand once each direction
        Shaft Direction:CCW Detents:-1 RPM:-3
        Shaft Direction:CW Detents:7 RPM:21
        Shaft Direction:CW Detents:5 RPM:15
        Shaft Direction:CW Detents:9 RPM:27
        Shaft Direction:CW Detents:11 RPM:33      << Fastest able to turn by hand
        Shaft Direction:CW Detents:112 RPM:336   
        Shaft Direction:CW Detents:445 RPM:1335   << Using a ~1500 RPM drill
        Shaft Direction:CW Detents:480 RPM:1440
        Shaft Direction:CW Detents:480 RPM:1440
        Shaft Direction:CW Detents:186 RPM:558
        Shaft Direction:CCW Detents:-1 RPM:-3
        Shaft Direction:CCW Detents:-145 RPM:-435
        Shaft Direction:CCW Detents:-445 RPM:-1335  << Drill in reverse
        Shaft Direction:CCW Detents:-447 RPM:-1341
        Shaft Direction:CCW Detents:-120 RPM:-360
        Shaft Direction:CCW Detents:-1 RPM:-3

        My cordless drill lists the RPM spec at 1500 RPM, which is within 4% of what I measured in the clockwise direction, and 11% in the counterclockwise direction.  Since I have owned the drill for many years, this is within expectations.

         

        More details about the TIMER peripheral can be found in Application Note AN0014 TIMER.

         

        Pulse Counter (PCNT)

        The Pulse Counter (PCNT) counts and measures incoming pulses to the MCU, even while the core is in EM3 sleep state.  Rather than wake the MCU on every edge on a GPIO pin, the PCNT counts pulses until a specific count is reached, which then wakes up the MCU if the PCNT interrupt is enabled.   Most EFM32 models have an 8-bit PCNT counter, capable of counting up to 255, but some models have a 16-bit counter on PCNT0.

         

        The PCNT peripheral is a little less versatile than the TIMER peripheral, as it can only count either positive edges or negative edges, but not both in “single output oversampling” or “externally clocked single input” modes.  It can also work with quadrature encoders, but only in X1 mode.  It cannot operate in X2 or X4 quadrature modes.  However, it can keep counting all the way in EM3 energy mode if it is externally clocked by the pulses on the input pin, whereas the TIMER can only operate down to EM2 energy mode.

         

        To demonstrate the basic operation of the PCNT, we can re-use our blinking LED and ACMP output to feed that output to the PCNT and count the number of LED pulses over time.  Once the count is reached, we can use the PCNT to interrupt the system and print the time to the SWO console.

        6_pcnt.png
        To re-use our blinking LED from the earlier section, all we need to do is place a wire jumper between PE2 (ACMP0_O) and PD0, which is our S0 pin for PCNT2.  There are two pins available for each PCNT, each with several locations, but the function that we want for S0 in this case is to clock the PCNT counter.  The optional S1 signal modifies the count of the S0 signal (forward or backwards), so be careful how you connect these pins. 

         

        The following code configures PCNT’s S0 pin on PD0 to count in LFACLK oversampling mode.

         

        #define PCNT_OVERFLOW                     (LED_BLINK_RATE / 2) -1
        // Setup PCNT2 input on PD0, to count up to LED blink rate then generate interrupt
        void setup_PCNT()
        {
              /* Select LFRCO as clock source for LFA */
              CMU_ClockSelectSet(cmuClock_LFA, cmuSelect_LFRCO);
              CMU_ClockEnable(cmuClock_HFLE, true);     /* Enable renamed CORELE clock */
              CMU_ClockEnable(cmuClock_PCNT2, true);
              CMU_ClockEnable(cmuClock_GPIO, true);
         
              /* Set configuration for pulse counter */
              PCNT_Init_TypeDef pcntInit = PCNT_INIT_DEFAULT;
              pcntInit.mode       = pcntModeOvsSingle;  /* clocked by LFACLK */
              pcntInit.counter    = 0;                  /* Set initial value to 0 */
              pcntInit.top        = PCNT_OVERFLOW;      /* Set top to max value */
         
              /* Initialize Pulse Counter */
              PCNT_Init(PCNT2, &pcntInit);
         
              // Clear the interrupt flag
              pcnt_interrupt = false;
         
              /* Enable PCNT overflow interrupt */
              PCNT_IntEnable(PCNT2, PCNT_IF_OF);
         
              /* Enable PCNT2 interrupt vector in NVIC */
              NVIC_EnableIRQ(PCNT2_IRQn);
         
              /* Route PCNT2 input to location 0 -> PCNT2_S0IN on PD0 */
              PCNT2->ROUTE = PCNT_ROUTE_LOCATION_LOC0;
         
              // Enable the pin PD0 for the PCNT2_S0IN input
              GPIO_PinModeSet(gpioPortD, 0, gpioModeInput, 0);
         
              // Clear the count again, because enabling the already-high PD0 adds 1 to the count
              PCNT_CounterSet(PCNT2, 0);
        }

        Once the PCNT is configured, any pulse on the GPIO pin will trigger a count, even if the first pulse is provided simply by configuring the PD0 pin to enable the input mode if the PD0 pin happens to be at a high state when that occurs.  Therefore, the PCNT2 is reset to 0 after the GPIO mode is set to input.

        At the module level (outside the main function), we define a global variable called pcnt_interrupt.

        bool pcnt_interrupt = false;

        We then setup a PCNT2 interrupt handler that simply sets pcnt_interrupt to true whenever the interrupt occurs.

         

        void PCNT2_IRQHandler(void)
        {
              /* Clear PCNT0 overflow interrupt flag */
              PCNT_IntClear(PCNT2, PCNT_IF_OF);
         
              pcnt_interrupt = true;
        }

        Now, in the main while loop, the pcnt_interrupt flag can be monitored and a message can be printed whenever the PCNT interrupt is triggered.

         

            setup_ACMP();
            setup_elapsed_timer();
            setup_blink_timer();
            setup_PCNT();
         
            TIMER1->CNT = 0;
            TIMER0->CNT = 0;
         
              while (1)
              {
                    // Sleep until the timer expires
                    EMU_EnterEM1();
         
                    if (pcnt_interrupt)
                    {
                          printf("PCNT Interrupt! Elapsed CNT:%d\n", TIMER1->CNT);
                          pcnt_interrupt = false;
                          TIMER1->CNT = 0;
                    }
              }

        Since TIMER1 is being used to track time and TIMER0 is being used to blink the LED, they are synchronized to 0 (as much as possible) before the while loop begins, just so that the counts can be compared easily and we don’t miss any early edges.  TIMER1 is cleared after every pcnt_interrupt occurs so we can use the TIMER1 CNT value directly without requiring any overflow logic.

         

        If all goes well, you should see a listing of TIMER1 clock counts that occur between each PCNT2 interrupt.  Remember that you only have 16-bits on the TIMER peripheral, which means that it only counts from 0 to 65,535, and 8-bits (on most EFM32 models) for PCNT, which only counts from 0 to 255.  In this case, that works well because we expected to find 10 LED pulses in one second on PCNT, which is 13672 TIMER clock counts.  If your events take longer or your TIMER is configured with a lower divisor, you could run out of room in the CNT register before the required pulses arrive.

         

        Chapter 6: Input Modes!
        PCNT Interrupt! Elapsed CNT:13681
        PCNT Interrupt! Elapsed CNT:13669
        PCNT Interrupt! Elapsed CNT:13669
        PCNT Interrupt! Elapsed CNT:13669
        PCNT Interrupt! Elapsed CNT:13669
        PCNT Interrupt! Elapsed CNT:13670
        PCNT Interrupt! Elapsed CNT:13669
        PCNT Interrupt! Elapsed CNT:13669
        PCNT Interrupt! Elapsed CNT:13669
        PCNT Interrupt! Elapsed CNT:13670
        PCNT Interrupt! Elapsed CNT:13669
        PCNT Interrupt! Elapsed CNT:13669

        For some reason, the first loop had a little bit more error than subsequent loops, but the overall error of TIMER1’s 13672 clock count to PCNT’s 13669 to 13681 clocks between interrupts is only a 0.1% measurement error.

         

        In oversampling mode, the PCNT has a maximum count rate of the LFACLK/2, which means that it can work reliably up to 32kHz.  If your pulses are faster than that, you will need to run the PCNT from the external clock pulses directly on the S0 pin, rather than sample the S0 pin with the LFACLK.  When you go that route, the PCNT peripheral has no internal clock, and your PCNT configuration write cycles will have no effect until there are three pulses on the S0 pin.  To make things easier, you can do your configuration of PCNT first while running on the LFACLK, and then switch to external S0 clocking after the PCNT is configured.  In externally-clocked mode, the PCNT can operate at a frequency up to the maximum specified rate of the MCU core clock.

         

        The PCNT can be used to count objects passing by a sensor, where an LED or an infrared LED is emitted and detected by a light sensor.  When objects block the LED, the light sensor sees pulses/edges and the PCNT can then count the number of objects passing the sensor.  It can also be used to count revolutions of a wheel, either with the same light emitter/sensor or with current-inducing pulses created by magnets on the wheel that pass by a stationary sensor.

         

        More details about the PCNT peripheral can be found in Application Note AN0024 Pulse Counter.

         

        This wraps up our coverage of MCU input mechanisms.