You are on page 1of 20

PULSE

EEWeb

Issue 51 June 19, 2012

EEWeb.com

Tamara Schmitz
Intersil

Electrical Engineering Community

EEWeb
Electrical Engineering Community
Contact Us For Advertising Opportunities

advertising@eeweb.com www.eeweb.com/advertising

1.800.574.2791

TA B L E O F C O N T E N T S
Tamara Schmitz
INTERSIL
Interview with Tamara Schmitz - Applications Manager for Optical Sensors

4 10 12 16 20

TABLE OF CONTENTS

Featured Products Illogical Logic - Part 3: D-Type Flip Flops


BY PAUL CLARKE WITH EBM-PAPST
Understanding the most common logic blocks in todays computers and digital electronics - the edge-triggered D-Type flip-flop.

Arduino for Mere M0rtals: Part 4


This installment will take a closer look at the blinking LED Arduino sketch for processing programming.

BY ROBERT BERGER WITH RELIABLE EMBEDDED SYSTEMS

RTZ - Return to Zero Comic

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

INTERVIEW

Tamara Schmitz Intersil


company. Also, a freight train line had tracks just beyond our back fence and I used to run outside when I heard the train coming so I could wave at the engineers, count the cars and see if anyone was in the caboose. (Trains dont seem to have cabooses anymore.) When I graduated from wanting to be a firefighter, I told people I wanted to be an engineer. I meant the train kind, but most others assumed the science/math/problem solver. Over the years I guess it just stuck. I do

FEATURED INTERVIEW

How did you get into engineering and when did you start? It sounds silly, but the spark came from my Grandpa. His nickname was Sparky and he was an electrician for Pullman Railroad

Tamara Schmitz - Applications Manager for Optical Sensors

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

INTERVIEW
love solving problems, so becoming an engineer was the right fit. Most people just dont start by wanting to drive a train. As for electrical engineering, thats much clearer. Mechanical engineering made sense because bridges could withstand earthquakes. Chemical engineering made sense because material science helped me see that durable paints could be developed for cars. Electrical engineering spanned a wide array of topics, but I was fascinated by one: how did radio waves travel through the air? I wanted to understand what magic was sending signals around and through me. It seemed that whoever controlled those would have disproportionate amounts of power to affect people for entertainment, for medical diagnosis and even for dangerous exposure. I wanted answers and access to this amazing field. Besides, it made Sparky proud. What are your favorite hardware tools that you use? Im going to assume you mean in the lab. My favorite tool is the spectrum analyzer. It breaks apart a signal into its frequency components and grants me insights that can be hidden in the time domain. What are your favorite software tools that you use? I really like Matlab. And, of course, I have to mention SPICE. The ability to simulate circuits and systems is incredibleand improving constantly. Since Im in an optical sensors group now, Im finding a great appreciation for SolidWorks and FRED. What is your favorite debugging tool? The human body. Think of all of the tools that you have for free. Skin is a temperature sensor. Eyes and ears are bandpass filters. Noses are fantastic over-current detection devices. Tongues are decent battery testers, but I dont recommend that unless you are stranded on an What is the hardest/trickiest bug you have ever fixed? Whichever one Im working on right now. Bugs arent usually so complicated that it takes a team of geniuses to find them. Its like finding Waldo. If hes half an inch tall, hes easy to spot on a baseball card. However, if hes half an inch tall and hes somewhere on a wall mural, its probably going to take a lot longer. The tricky part is finding the bug. Too many people guess without a plan. The best thing to do is to draw a box around the problem, to quote one of my colleagues, Ken Dyer. Then you know the bug is somewhere in the box. Methodically go through the system and verify whether each block is working properly. Eventually, you will be able to shrink the box around the problem area and focus your efforts more efficiently. The exception to this method is the case where you have loads of experience. Experience can inform you of the most likely places to look. In those cases, Id start there. What is on your bookshelf? Some old databooks that I havent recycled yet, a copy of my PhD thesis on RF CMOS low phase noise oscillators, the Art of Electronics, the ARRL Handbook, a picture of me pretending to pitch to a full-size statue of Babe Ruth at the Baseball Hall of Fame, various textbooks, a roaring Godzilla doll and a photo of my 3 dogs. Do you have any tricks up your sleeve? Its all about the basics. Start

FEATURED INTERVIEW

Follow your dreams. I know it sounds corny, but find something you love to do. Jobs these days stretch way beyond 40 or 50 hours. There are times when my driving time, my evenings and my dreams are still churning away on a problem.
island or something. Fingers are crude capacitances; touching a node can add 100pF or so which might help you quickly figure out a compensation problem. These are the kind of observations and tools engineers dont usually record in their lab notebooks.

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

INTERVIEW
simple. Power and ground. Check the voltage on every node/pin. Dont assume anything. Once the basics/ bias checks out, start varying over ranges. Do min and max input get expected output? Then follow the signal through the system. What has been your favorite project? My favorite project was constructing a horn antenna to be used at the Big Dish on Stanford Universitys campus. The operating frequency was 330MHz, so the horn was about the size of a coffin. I soldered copper clad pieces together and built a wooden exoskeleton for support. It was awesome to see the mathematics come to life, to test the antenna response in a warehouse at SRI, and then to mount it on that big, beautiful dish and see it work! Well, it worked until a bird decided that it was a wonderful place to build a nest. Do you have any note-worthy engineering experiences? Im particularly proud of the Test Development Engineering Program I championed at San Jose State University. After noticing that electrical engineering students were finding jobs as apps, test and product engineers, I joined with a team of folks from Agilent, National Semiconductor, Teradyne and Intersil to put together a program to teach skills needed for these areas. Students spent the spring semester learning lab techniques like measurement and soldering. They designed a PCB to test an IC and presented their work to a panel from the supporting companies. In the summer they had internships with the sponsors. In the fall, they returned to school and proceeded in their workthis time on ATEs. Along the way, they learned a lot about the semiconductor industry and where they would fit in. Every student got a job. They even nominated me for an IEEE certificate of appreciation. Cool stuff. If I was to tell you some of the cool things I work on now, it would break customer confidentiality. Lets just How is academia different than industry? Huge difference. From the students perspective, you learn a lot of math in college. You can solve KVL and KCL with Thevenin and Norton equivalents. You can take derivatives with respect to time and to voltage. In industry, the derivatives are with respect to cost and to customer interest. Its hard to put those into matrices (yet MBAs and economists do it all the time). From a professor standpoint, you are trying to get as many students through the system as possible. There is so much that could be taught, but there are also so many regulations about teaching (think ABET accredited). Many professors teach the same material because it is approved. Its a lot of work to put a class together and it is too easy to use the same material one more time. Besides, the point of school is to learn the basics, right? The basics dont change much. Still, the motivation and end goals do change. Our university classrooms are not at the forefront of technology. (One could argue that the research labs at a university house the forefront of technology. Yes, a ittybitty slice of it.) Remember, though, that engineering is growing and changing every day. University curriculums, therefore, must theoretically teach more and more each year. Students dont stay in school longer, so sacrifices have to be made. Often that means tough choices. I, personally, prefer the real world where the technological innovation creates a product or device that enables product differentiation or

FEATURED INTERVIEW

The global work force is adjusting its footprint. While it might be advantageous to use cheaper labor, the time, cultural and communication differences are a big stumbling block for projects that span multiple continents.
say that its fun to walk around Best Buy and see all of the products that use an IC from Intersilespecially one of the light sensors.

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

INTERVIEW
new platforms. People use money to say what they like and dont like. It is impossible to survive in the semiconductor industry if you produce the same product year after year. This ever-present drive to improve and innovate is what makes it fun. What are you currently working on? I am the new manager for the applications group focused on optical sensors. (These are ambient light or proximity (IR) sensors.) I have the privilege of leading a talented team of engineers as we work with the greatest electronics manufacturers around the world. Sensors are special because it isnt just an electrical system. Its an optical and mechanical one, too. Will the device be behind some kind of glass? Will there be plastic with a hole to allow access for the light? How much light can bounce around inside the product? How reflective is an object you want to target? (Black hair happens to be very non-reflective, yet the cell phone manufacturers want to turn off the touch screen before you bring the phone to your ear. They dont want it to only work for blondes) What direction do you see your business heading in the next few years? Sensors are growing like crazy! Consumer devices want to interact more naturally with their users. They want to save us power by turning down the backlight of a screen in low-light conditions, so we can enjoy longer battery life. They want to understand our questions and interpret our gestures. They want to anticipate our desires and prepare. They want to help camera understand what kind of lighting conditions they operate in so we can take better pictures. There are so many more examples. What challenges do you foresee in our industry? There are lots of challenges. The global work force is adjusting its footprint. While it might be advantageous to use cheaper labor, the time, cultural and communication differences are a big stumbling block for projects that span multiple continents. Still, money is a stronger driving force (especially in the limping recession) so we are willing to accept the challenge. Another challenge is the next big thing. Cell phones kept getting smaller and then acquired touch screens. They have great cameras and organize our personal and professional lives. Really, though, we havent seem much that is new. The platform seems to be moving from hardware to software. Its not What can the silicon do, but more What can we do with the silicon? Almost everyone has a cell phone. What is the next device everyone will have?

FEATURED INTERVIEW

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

INTERVIEW
Is there anything that you have not accomplished yet, that you have your sights on accomplishing in the near future? My goals have morphed over the years. I wanted to be a professor and achieved that goal. I wanted to show that I was a real engineer and could contribute in industry. I have achieved that goal, too. (And it pays much better than the professor gig.) At times I get frustrated with upper management and have a desire to see if I could do better. Ok, I have that desire even when Im not frustrated with upper management. I like looking at choices, defining challenges, setting goals and inspiring a team. I believe a good leader is a good listener, is a wise businessman and can bring out the best in people. Engineering is a spectacular skill and medium we share. We can learn to deliver premium products and the highest quality service for a fair price. Its a win-win. Any advice you would like to give the engineering community? Follow your dreams. I know it sounds corny, but find something you love to do. Jobs these days stretch way beyond 40 or 50 hours. There are times when my driving time, my evenings and my dreams are still churning away on a problem. If I dont love what I do, Id be exhausted and miserable a lot. I might be exhausted at times, but Im proud of my team and my work. That satisfaction is important to me. I want to own a house, drive my truck, take my dogs to the beach, take care of my aging parents, enjoy the time with my coworkers and make some kind of difference. I feel like I can do that here at Intersil. I hope you find your place, too.

FEATURED INTERVIEW

EEWeb
Electrical Engineering Community

Join Today
www.eeweb.com/register

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

Avago Technologies LED Lighting Solutions

One LED. Infinite colors. Worlds first waterproof package.


Avago Technologies Tri-color High Brightness PLCC6 SMT LEDs gives you a reliable, long life product for ease of design in full color interior and exterior signs
Tri-color High Brightness SMT LEDs from Avago Technologies
Avagos PLCC-6 SMT LEDs are high brightness, high reliability, high performance, IPX6 compliant and are water and dust proof. They are designed with a separate heat path for each LED die, enabling it to be driven at higher current. They deliver super wide viewing angle at 120 together with the built in reflector pushing up the intensity of the light output.

Features
Water-resistance (IPX6*) per IEC 60529:2001 Very small PLCC6 package dimensions 3.4 x 2.8 x 1.8mm In-line RGB dies configuration Available in White Surface, Black-Surface and Full Black-Body Wide operating temperature range: -40 to +110
For more information or to request a sample please go to:

Applications
Indoor and outdoor full color display LED advertisement panels Decorative lighting

www.avagoresponsecenter.com/led

F E AT U R E D P R O D U C T S
Switch Family for 24V Battery Systems
New 24V eXtreme switches designed for applications such as lamps, LEDs, solenoids and motors used in trucks, buses and special engines. Freescales intelligent, dual high-side eXtreme switches for 24V systems feature current capability ranging from 1 to 12A DC and are fully footprintand software-compatible. Each output can be programmed to be used for most kinds of loads, including lamps, LEDs, motors or solenoids. This allows customers to design a flexible module that can be optimized for a specific application through software. Freescales 24V eXtreme switch solution provides robust design, intelligence and safety needed for truck applications. Due to increased integration, use of the switch results in lighter-weight, smaller systems and a reduced component count. For more information, click here.

FEATURED PRODUCTS

Automotive-Qualified Power MOSFETs


International Rectifier today introduced a family of automotive-qualified power MOSFETs housed in a rugged TO-220 fullpak package for automotive applications including BLDC motors, pumps and cooling systems.The new 55V planar devices are available as standard and logic level gate drive MOSFETs in N and P channel configuration, and offer a maximum on-state resistance (Rds(on)) as low as 8mOhm. The TO-220 fullpak package eliminates the need for additional insulating hardware to simplify design and improve overall system reliability. For more information, please click here.

Low Loss High Bandwidth Coaxial Cables


Designed for superior monitoring and control of radar, military vehicles, satellite, space, missile, RF ablation and test and measurement equipment, Temp-Flex coaxial cable solutions are insulated with a fluoropolymer dielectric. A helically wrapped silver-plated copper flat wire shield and braid are applied to all cable sizes to achieve superior shielding effectiveness. The standard solid core (low loss) construction coaxial cable delivers 70 percent velocity of propagation (VOP), while the air enhanced dual monofilament design (ultra-low loss) achieves 85 to 88 percent velocity of propagation and improved insertion loss at high frequencies.For more information, click here.

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

10

Get the Datasheet and Order Samples


http://www.intersil.com

4-Channel LED Driver with Independent Channel Control for Dynamic Dimming
ISL97686
The ISL97686 is a PWM controlled LED driver that supports 4 channels of LED current, for Monitor and TV LCD backlight applications. It is capable of driving 160mA per channel from a 9V to 32V input supply, with current sources rated up to 75V absolute maximum. The ISL97686s current sources achieve typical current matching to 1%, while dynamically maintaining the minimum required VOUT necessary for regulation. This adaptive scheme compensates for the non-uniformity of forward voltage variance in the LED strings. The ISL97686 dimming can be controlled by a high speed SPI interface for independent channel control for dynamic dimming function synthesized on chip at 10-bit resolution. The ISL97686 has an advanced dynamic headroom control function, which monitors the highest LED forward voltage string, and regulates the output to the correct level to minimize power loss. This proprietary regulation scheme also allows for extremely linear PWM dimming from 0.02% to 100%. The LED current can also be switched between two current levels, giving support for 3D applications. The ISL97686 incorporates extensive protections of string open and short circuit detections, OVP, and OTP

Features
4 x 160mA, 75V Rated Channels with Integrated Channel Regulation FETs Channels can be Ganged for High Current - 2 x 350mA - 1 x 700mA 9V~32V Input Voltage Dimming Modes: - Independent Channel Dimming Control with SPI - PWM Dimming with Adjustable Output Frequency - 10-bit Dimming Resolution - VSYNC Mode 2 Selectable Current Levels for 3D Applications Current Matching of 1% Integrated Fault Protection Features such as String Open Circuit Protection, String Short Circuit Protection, Overvoltage Protection, and Over-Temperature Protection 28 Ld 5x5mm TQFN and 28 Ld 300mil SOIC Packages Available

Applications
Monitor/TV LED Backlighting General/Industrial/Automotive Lighting

Related Literature
See Application note for ISL97686IBZ_EVALZ for SOIC Application

VIN: 9V~32V

Fuse D1 VIN VDC VLOGIC EN CLK SDI SDO /CS EN_VSYNC CSEL ISET1 ISET2 OSC PWM_SET/PLL CH1 CH2 CH3 CH4 OVP SLEW GD CS Q1 RSENSE
160mA MAX PER STRING

110 100 CHANNEL CURRENT (mA) 90 80 70 60 50 40 30 20 10 0 0 20 40 60 80 100 I_CH2 I_CH3 I_CH1 I_CH4

PGND COMP

DIMMING DUTY CYCLE (%)

FIGURE 1. ISL97686 APPLICATION DIAGRAM

FIGURE 2. PWM DIMMING LINEARITY

April 23, 2012 FN7953.0

Intersil (and design) is a registered trademark of Intersil Americas Inc. Copyright Intersil Americas Inc. 2012 All Rights Reserved. All other trademarks mentioned are the property of their respective owners.

Part 3 - D-Type Flip-Flops


Paul Clarke
Electronics Design Engineer

Illogical Logic

TECHNICAL ARTICLE

TECHNICAL ARTICLE

When it came to illogical logic circuits, I must say, I was always scratching my head at edge-triggered D-type flip-flops. These are one of the most common logic blocks in todays computers and digital electronics. Its a bit like saying the transistor is the most common component in modern electronicsbut how many of us understand how a D-Type works? To begin the voyage to the edge-triggered D-type flip-flop, we will start with the common element thats used inside it: the SR flip-flop. This is the simplest flip-flop to understand as it only contains two logic gates and NAND gates. It is also the easiest to see a common issue in digital electronics, the race condition or a glitch. These states occur when the logic output of a circuit is undefined for a few brief microseconds. We have to remember that logic gates are, after all, analog circuits full of transistors. These circuits take time for the charge on the devices, like FETs, to rise or fall. This means that the voltage thresholds are not clear and transistors may or may not be switched on. Within the gate, this means that a clear decision about output levels has not been made hence undefined. This also happens during changes to the input as it takes time for the gate to react and generate a new output, if one is required. So in our SR flip-flop there is a race condition at switch on where the gates

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

12

TECHNICAL ARTICLE
Set

by adding a NOT gate between the S and R inputs and renaming the S input as D (Figure 3). Our new D-Type works just like the SR flip-flop as its possible to change the output while the clock is high multiple times during that period. We need a circuit that only latches in the D signal when the clock edge is rising. To simplify this to begin with, lets think about the ability to generate race conditionsor in this case, a glitch. If there was only a way to make the clock pulse really really small on the positive duration, then there would not be enough time to switch back (Figure 4).

TECHNICAL ARTICLE

Reset

H
Figure 1: SR FLIP-FLOP

power up and try to work out their output state. This becomes more complex as the outputs are fed back to the inputs. This means that the output is affecting the input, hence the decision making and hence the output itself. Confused? Well thats how the gate feels. However after a few microseconds the gate settles and a stable state persists.

S 0 0 1 1

R 0 1 0 1

Q ! 1 0 X
CLK
Figure 3: D-TYPE FLIP-FLOP

H
Figure 4: GLITCH CIRCUIT

Figure 2: SR TRUTH TABLE

The truth table for the SR flip-flop is therefore as follows: The most interesting states are the Set and Reset states and the Do Nothing stateso remember these for later. The next thing to add is our clock input, which is done by adding two more NAND gates to the front end of our SR circuit. This becomes a gated SR flip-flop. The Set and Reset still work as before, but as the name suggests, its gated so the output only happens at certain times, when the clock input is high. This is all very good, however, its possible for the circuit to change its output multiple times during a clock high, which is not what we want at all. Its also not a D-type yet. However, this is easy to fix This circuit uses the idea that it takes time for the gates to switch. Lets assume for a moment that the input is LOW. One side of the AND gate is set to LOW as per the input and the other is logic HIGH because the NOT gate has inverted the input. In a perfect world, if the input changes, the NOT gate would change instantaneously and this input to the AND gate would swap and the output remain unaffected. However, because it takes time for the NOT gate to react and drive the output, there is, in fact, a small moment in time were both the inputs to the AND gate are HIGH. This sets off the chain reaction in the gate that will

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

13

TECHNICAL ARTICLE
In order to have both, you need two SR flip-flops that act as Set and Reset circuits. By connecting these circuits in opposite modes, its then possible to use the data input to decide which one latches and holds and which one flips back and forth with the clock input (Figure 5). First thing to notice is that the NOT gate that was used on the SR to turn it into a D-Type is simplified by using the NOT Q output on one of the SR flip-flops (in this case the bottom one). This lower flip-flop generates this NOT signal as a feedback or input to the top flip-flop, which in turn generates a NOT signal back to the first. This causes the two SR flip-flops to latch in opposite modes. The clock signal is also fed to both SR flip-flops and because of this the lower flip-flop need to have a three input NAND gate. The overall effect is that these two flipflops generate a very useful signal. One will, as I said, latch and the other flip with the clock input. These two signals can then be used to drive a third SR flip-flop that functions as before with the DO NOTHING condition, only changing its output once the D-signal has changed and when the clock edge is seen, in this case, on the rising edge. Its quite a difficult circuit to put into words because of the number of states it can be in. I could post lots of pictures showing them, but nothing works better than an animation. If you have not seen this website before, then http://www.falstad.com is great and has a really nice little circuit simulator. Follow the link below to load the simulator and the following instruction to bring up the edge-triggered D-type flip-flop. From the menus click here, select Circuits, then Sequential Logic. Then click on Flip-Flops and then Edge-Triggered D Flip-Flop. About the Author Digital Electronics Engineer with strong software skills in assembly and C for embedded systems. At ebmpapst Im developing embedded electronics for thermal management control solutions for the air movement industry. These controllers monitor environmental inputs like Temperature, Humidity and Pressure and then control the speed of our fans based on various profiles. Our controls also interface with other systems over RS232/485 or TCP/IP as well as a host of other user or control interfaces.

TECHNICAL ARTICLE

CLK

Figure 5: D_TYPE EDGE TRIGGERED CIRCUIT

drive the output from LOW to HIGH. Moments later, the NOT gate output changes state and the AND gate reacts to the new stimulus. However, the chain reaction is still in place and what we see at the output or the AND gate is a HIGH equal to the time it took the NOT gate to switch. This may look great, but its not a defined period of timeother gates may not even react quickly enough to it and we are relying on the analog side effects of the gates. So what we need is a nice stable version of the glitch generator. We could, for example, have a much higher speed clock running somewhere that could help us process the signals, but then that would need higher speed clocks too The answer, however, is in our original SR flip-flops. These react to the change of input only once when the input change is applied. With both inputs at LOW, a HIGH signal on one of the inputs generates a fast reaction and latches in a new output if one is required. The interesting effect is the DO NOTHING condition where setting both inputs HIGH will not change the output. Changing an input as LOW will then either Set or Reset the SR latch. However, driving the signal up and down as much as we want will not affect the output. If we were to connect a clock input to this circuit, then Setting or Resetting the latch would happen only on the falling edge of the clock. We are now getting close, but still not quite there. We have a circuit that responds to the edge of the clockthe wrong edgebut we can only connect this circuit so that it Sets or Resets. We need both.

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

14

Transform Your iPhone, iPad or iPod into an Oscilloscope with the iMSO-104
Begin Your Experience Now

Experience the iMSO-104 as Joe Wolin, co-founder of EEWeb, gives you an in-depth look into the future of oscilloscopes.
UBM ELECTRONICS

WI NNER

2012

TECHNICAL ARTICLE
TECHNICAL ARTICLE

Embedded Software Specialist

Robert Berger

for mere m0rtals - PART 4


Disclaimer The views, opinions, positions or strategies expressed by the author and those providing comments are theirs alone, and do not necessarily reflect the views, opinions, positions or strategies of anybody else. Das Blinkenlights [1] Well have a closer look at the blinking LED Arduino sketch we saw last time (Figure 1). ACHTUNG! ALLES TURISTEN UND NONTEKNISCHEN LOOKENPEEPERS! DAS KOMPUTERMASCHINE IST NICHT FUR DER GEFINGERPOKEN UND MITTENGRABEN! ODERWISE IST EASY TO SCHNAPPEN DER SPRINGENWERK, BLOWENFUSEN UND POPPENCORKEN MIT SPITZENSPARKSEN. IST NICHT FUR GEWERKEN BEI DUMMKOPFEN. DER RUBBERNECKEN SIGHTSEEREN KEEPEN DAS COTTONPICKEN HANDER IN DAS POCKETS MUSS. ZO RELAXEN UND WATSCHEN DER. BLINKENLICHTEN. Dissection of BlinkWithoutDelay [3] Sketch Programs written for the Processing [4] programming language are called sketches. These sketches are typically written using the text editor that comes with Processing. It has features for cutting/pasting and for searching/replacing text. Sketches written for Processing should have a .pde file extension, which stands for Processing Development Environment. Arduino borrowed this concept from Processing and programs that are being uploaded to and run on an Arduino board are called sketches as well. To distinguish Arduino from Processing sketches, .ino should be used as a file extension, which stands for Arduino (Figure 2). Comments Everything between the /* (line 1) and */ (line 22) is ignored by the Arduino when it runs the sketch (the * (lines 8, 9) at the start of each line is only there to make the comment look pretty, and isnt required). Comments are for people who read your code and for you and try

Arduino

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

16

TECHNICAL ARTICLE
to understand what you wrote a long time ago. They (hopefully) explain what the program does, how it works, or why its written the way it is. Its good practice to comment on your sketches and to keep the comments up-to-date when you modify the code. Remember, as a good open-source citizen, to share your code so others can learn from or modify/improve your code. Theres another style for short, single-line comments. These start with // (e.g on line 26) and continue to the end of the line. To delay() or not to delay()? [5] The delay() function mentioned on line 4 and the hint not to use it so other code can run already looks weird to someone who used a RTOS or Unix/Linux before. Lets have a closer look at it. From the FreeRTOS call vTaskDelay(500/portTICK RATE MS) [6], you would expect to delay a task for 500 msec. The fact that this API call delays/blocks a task for 500 msec means that it allows tasks with a lower priority to run until the time expires. In Linux usleep(500) [7], it would block the calling process for 500 msec and allow processes with a lower priority to run until the time expires kind of. Description The delay() function pauses the program for the amount of time (in milliseconds) specified as parameter. (Remember: there are 1000 milliseconds in a second.) Syntax delay(ms) Parameters ms: the number of milliseconds to pause (unsigned long) Returns nothing (Figure 3) Caveat While it is easy to create a blinking LED with the delay() function, and many sketches use short delays for such tasks as switch debouncing, the use of delay() in a sketch has significant drawbacks. No other reading of sensors, mathematical calculations, or pin manipulation

TECHNICAL ARTICLE

Figure 1: Try telnet towels.blinkenlights.nl [2]


Listing 1: BlinkWithoutDelay.ino
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

/* Blink without Delay Turns on and off a light emitting diode (LED) connected to a digital pin, without using the delay() function. This means that other code can run at the same time without being interrupted by the LED code. The circuit: * LED attached from pin 13 to ground * Note: on most Arduinos, there is already an LED on the board thats attached to pin 13, so no hardware is needed for this example. created 2005 by David A. Mellis modified 8 Feb 2010 by Paul Stoffregen This example code is in the public domain http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay */

Figure 2

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

17

TECHNICAL ARTICLE
can go on during the delay function, so in effect, it brings most other activity to a halt. For alternative approaches to controlling timing, see the millis() function [8] used on line 49 in the sketch below. Arduino veterans usually avoid the use of delay() for timing of events longer than 10s of milliseconds unless the Arduino sketch is very simple. However, certain things do go on while the delay() function is controlling the Atmega chip because the delay function does not disable interrupts. Serial communication that appears at the RX pin is recorded, PWM (analogWrite) values and pin states are maintained, and interrupts will work as they should. Authors Comment From what we have seen above, the delay() implementation behaves like a busy loop with interrupts enabled. Variables A variable is a place for storing a piece of data. It has a name, a type, and a value. For example, the line 26 from the sketch above declares a variable with the name ledPin, the type int, and an initial value of 13. Its being used to indicate which Arduino pin the LED is connected to and since it never changes, its declared as const, which could give the linker a hint to place it in a section other then precious RAM. Every time the name ledPin appears in the code, its value will be retrieved. In this case, the person writing the program could have chosen not to bother creating the ledPin variable and could have simply written 13 everywhere they needed to specify a pin number instead. The advantage of using a variable is that its easier to move the LED to a different pinyou only need to edit the one line that assigns the initial value to the variable. Often, however, the value of a variable will change while the sketch runs (lines 29, 34, 49). Due to the lack of insightful comments, its not quite obvious to me why the variable in line 30 is not defined as const as well since it does not change. Functions A function (otherwise known as a procedure or subroutine) is a named piece of code that can be used from elsewhere in a sketch. The setup() function [9] as seen in
Listing 2: delay-example.ino
1 2 3 4 5 6 7 8 9 10 11 12 13 14

TECHNICAL ARTICLE

int ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); } void loop() { digitalWrite(ledPin, HIGH); delay(500); digitalWrite(ledPin, LOW); delay(500); }

// LED connected to digital pin 13

// sets the digital pin as output

// // // //

sets the LED on waits 500 msec sets the LED off waits 500 msec

Figure 3
Listing 3: BlinkWithoutDelay.ino continued
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

// constants wont change. Used here to // set pin numbers: const int ledPin = 13; // the number of the LED pin // Variables will change: int ledState = LOW; long previousMillis = 0; // ledState used to set the LED // will store last time LED was updated

// the following variable is a long because the time, measured in milliseconds, // will quickly become a bigger number than can be stored in an int. long interval = 1000; // interval at which to blink (milliseconds) void setup() { // set the digital pin as output; pinMode(ledPin, OUTPUT) }

Figure 4
Listing 4: BlinkWithoutDelay.ino continued
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

void loop() { // here is where youd put code that needs to be running all the time. // check to see if its time to blink the LED; that is, if the // difference between the current time and last time you blinked // the LED is bigger than the interval at which you want to // blink the LED. unsigned long currentMillis = millis(); if(currentMillis previousMillis > interval) { // save the last time you blinked the LED previousMillis = currentMillis; // if the LED is off turn it on and vice-versa: if (ledState = LOW) ledState = HIGH; else ledState = LOW; // set the LED with the ledState of the variable: digitalWrite(ledPin, ledState);

Figure 5

line 36 is called once, when the sketch starts. Its a good place to configure pin modes and to initialize libraries. The pinMode() function [10] line 38 configures a digital pin as either an input or an output. To use it, you pass the number of the pin to configure and the constant INPUT or OUTPUT. When configured as an input, a pin can detect the state of a sensor like a Push button. As an output, it can drive an actuator like an LED, which, in our case, utilizes the digitalWrite() function [11] line 62 to

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

18

TECHNICAL ARTICLE
change state (Figure 5). The loop() function [12] line 41 is called over and over and is the heart of most sketches. Both setup() and loop() need to be included in your sketch, even if you dont need them for anything. Authors Comment From what we have seen so far, it looks like an Arduino sketch behaves like a cyclic executive with interrupts. Stay tuned for more hands-on stuff in the next part of this series of articles where well investigate Processing! References [1] Das Blinkenlights http://en.wikipedia.org/wiki/ Blinkenlights [2] www.blinkenlights.nl http://www.blinkenlights.nl [3] First Sketch http://arduino.cc/en/Tutorial/Sketch [4] Processing http://processing.org [5] delay() http://arduino.cc/en/Reference/Delay [6] vTaskDelay() http://www.freertos.org/a00127.html [7] usleep() http://pubs.opengroup.org/onlinepubs/009695399/functions/usleep.html [8] millis() http://arduino.cc/en/Reference/millis [9] setup() http://arduino.cc/hu/Reference/Setup [10] pinMode() http://arduino.cc/en/Reference/pinMode [11] digitalWrite() http://arduino.cc/en/Reference/digitalWrite [12] loop() http://arduino.cc/en/Reference/loop About the Author Robert Berger is a highly respected and experienced embedded real-time expert and CEO of Reliable Embedded Systems, a leading embedded training consultancy. Robert consults and trains people all over the globe on a mission to help them create better embedded software. He specializes in training and consulting for embedded systems, from small real-time systems to multi-core embedded Linux.

TECHNICAL ARTICLE

ACOUSTICS & SENSORS


PRODUCTS
Speakers Buzzers Piezo Elements Back-up Alarms Horns Sirens/Bells Beacons Microphones Sensors

BeStar
INDUSTRIES
Automotive Durables Medical Industrial Mobile Fire / Safety Security Consumer Leisure

Teamwork Technology Invention Listen Hear

Preferred acoustic component supplier to OEMs worldwide

bestartech.com | sales@bestartech.com | 520.439.9204


EEWeb | Electrical Engineering Community Visit www.eeweb.com QS9000 TS/ISO16949 IS O 14001 IS O 13485 IS O 9001

19

RETURN TO ZERO
RETURN TO ZERO

EEWeb
Electrical Engineering Community

Join Today
EEWeb | Electrical Engineering Community

www.eeweb.com/register

Visit www.eeweb.com

20

You might also like