EEWeb Pulse - Volume 51

20
PULSE EEWeb.com Issue 51 June 19, 2012 Tamara Schmitz Intersil Electrical Engineering Community EEWeb

description

Interview with Tamara Schmitz – Applications Manager for Optical Sensors; Illogical Logic – Part 3: D-Type Flip Flops; Arduino for Mere M0rtals: Part 4; RTZ – Return to Zero Comic

Transcript of EEWeb Pulse - Volume 51

Page 1: EEWeb Pulse - Volume 51

PULSE EEWeb.comIssue 51

June 19, 2012

Tamara Schmitz

Intersil

Electrical Engineering Community

EEWeb

Page 2: EEWeb Pulse - Volume 51

Contact Us For Advertising Opportunities

[email protected]

www.eeweb.com/advertising

Electrical Engineering CommunityEEWeb

Page 3: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 3

TABLE O

F CO

NTEN

TSTABLE OF CONTENTS

Tamara Schmitz 4INTERSIL

Featured Products 10

Illogical Logic - Part 3: D-Type Flip FlopsBY PAUL CLARKE WITH EBM-PAPST

Arduino for Mere M0rtals: Part 4 16 BY ROBERT BERGER WITH RELIABLE EMBEDDED SYSTEMS

RTZ - Return to Zero Comic 20

Interview with Tamara Schmitz - Applications Manager for Optical Sensors

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

Understanding the most common logic blocks in today’s computers and digital electronics - the edge-triggered D-Type flip-flop.

12

Page 4: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 4

INTERVIEWFEA

TURED IN

TERVIEW

IntersilHow 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

Tamara Schmitz - Applications Manager for Optical Sensors

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 don’t 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

Page 5: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 5

INTERVIEWFEA

TURED IN

TERVIEW

love solving problems, so becoming an engineer was the right fit. Most people just don’t start by wanting to drive a train.

As for electrical engineering, that’s 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?I’m 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 incredible—and improving constantly. Since I’m in an optical sensors group now, I’m 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 don’t recommend that unless you are stranded on an

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 don’t usually record in their lab notebooks.

What is the hardest/trickiest bug you have ever fixed?Whichever one I’m working on right now. Bugs aren’t usually so complicated that it takes a team of geniuses to find them. It’s like finding Waldo. If he’s half an inch tall, he’s easy to spot on a baseball card. However, if he’s half an inch tall and he’s somewhere on a wall mural, it’s 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, I’d start there.

What is on your bookshelf?Some old databooks that I haven’t 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? It’s all about the basics. Start

Page 6: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 6

INTERVIEWFEA

TURED IN

TERVIEW

simple. Power and ground. Check the voltage on every node/pin. Don’t 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 University’s 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? I’m 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 work—this 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. Let’s just

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 it’s fun to walk around Best Buy and see all of the products that use an IC from Intersil—especially one of the light sensors.

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. It’s 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. It’s 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 don’t 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 itty-bitty 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 don’t 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

Page 7: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 7

INTERVIEWFEA

TURED IN

TERVIEW

new platforms. People use money to say what they like and don’t 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 isn’t just an electrical system. It’s 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 don’t 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 haven’t seem much that is new. The platform seems to be moving from hardware to software. It’s 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?

Page 8: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 8

INTERVIEWFEA

TURED IN

TERVIEW

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 I’m 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. It’s 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 don’t love what I do, I’d be exhausted and miserable a lot. I might be exhausted at times, but I’m 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. ■

Join Today

www.eeweb.com/register

Electrical Engineering CommunityEEWeb

Page 9: EEWeb Pulse - Volume 51

Tri-color High Brightness SMT LEDs from Avago Technologies

Avago’s 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.

Applications

• Indoorandoutdoorfullcolordisplay

• LEDadvertisementpanels

•Decorativelighting

Features

•Water-resistance(IPX6*)perIEC60529:2001

•VerysmallPLCC6packagedimensions–3.4x2.8x1.8mm

• In-lineRGBdiesconfiguration

•AvailableinWhiteSurface,Black-SurfaceandFullBlack-Body

•Wideoperatingtemperaturerange:-40°to+110°

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

www.avagoresponsecenter.com/led

AvagoTechnologiesLEDLightingSolutions

One LED. Infinite colors. World’s first waterproof package.

For more information or to request a sample please go to:

Page 10: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 10

FEATURED

PROD

UCTS

FEATURED PRODUCTS

Switch Family for 24V Battery SystemsNew 24V eXtreme switches designed for applications such as lamps, LEDs, solenoids and motors used in trucks, buses and special engines. Freescale’s intelligent, dual high-side eXtreme switches for 24V systems feature current capability ranging from 1 to 12A DC and are fully footprint- and 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. Freescale’s 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.

Automotive-Qualified Power MOSFETsInternational 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 CablesDesigned 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.

Page 11: EEWeb Pulse - Volume 51

4-Channel LED Driver with Independent Channel Control for Dynamic DimmingISL97686The 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 ISL97686’s 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

Related Literature• See Application note for “ISL97686IBZ_EVALZ” for SOIC

Application

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

FIGURE 1. ISL97686 APPLICATION DIAGRAM FIGURE 2. PWM DIMMING LINEARITY

SDO

CLK

OSC

GD

PWM_SET/PLL

EN

OVP

VIN

VLOGIC

VDC

D1

CS

CH1CH2CH3CH4

CSEL

ISET2

COMP

Fuse

SDIPGND

SLEW

VIN: 9V~32V

160mA MAX PER STRING

Q1

RSENSE

ISET1

/CS

EN_VSYNC

010

20

30

40

50

60

70

80

90

100

110

0 20 40 60 80 100

DIMMING DUTY CYCLE (%)

I_CH2

CH

AN

NEL

CU

RR

ENT

(mA

)

I_CH1

I_CH3

I_CH4

April 23, 2012FN7953.0

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

Get the Datasheet and Order Samples

http://www.intersil.com

Page 12: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 12

TECHN

ICA

L ARTIC

LETECHNICAL ARTICLE

Part 3 - D-Type Flip-FlopsIllogical Logic

Paul ClarkeElectronics DesignEngineer

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 today’s computers and digital electronics. It’s a bit like saying the transistor is the most common component in modern electronics—but 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 that’s 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

Page 13: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 13

TECHN

ICA

L ARTIC

LETECHNICAL ARTICLE

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.

This circuit uses the idea that it takes time for the gates to switch. Let’s 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

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 state—so 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, it’s gated so the output only happens at certain times, when the clock input is high. This is all very good, however, it’s possible for the circuit to change its output multiple times during a clock high, which is not what we want at all. It’s also not a D-type yet. However, this is easy to fix

Figure 3: D-TYPE FLIP-FLOP

Figure 4: GLITCH CIRCUIT

Figure 1: SR FLIP-FLOP

SetQ

QReset

H

H

L

H

S R Q

0 0 !

0 1 1

1 0 0

1 1 X

CLK

QD

LL

LH

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 it’s 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, let’s think about the ability to generate race conditions—or 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).

Page 14: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 14

TECHN

ICA

L ARTIC

LETECHNICAL ARTICLE

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 it’s not a defined period of time—other 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 clock—the wrong edge—but we can only connect this circuit so that it Sets or Resets. We need both.

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, it’s 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 flip-flops 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.

It’s 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 ebm-papst I’m 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. ■

CLK

Q

D

H

H

Figure 5: D_TYPE EDGE TRIGGERED CIRCUIT

Page 15: EEWeb Pulse - Volume 51

Transform Your iPhone, iPad or iPod into an Oscilloscope

with the iMSO-104

Experience the iMSO-104 as Joe Wolin, co-founder of EEWeb,

gives you an in-depth look into the future of oscilloscopes.

2012

UBM ELECTRONICSUBM ELECTRONICS

WINNER

Begin Your Experience NowBegin Your Experience Now

Page 16: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 16

TECHN

ICA

L ARTIC

LETECHNICAL ARTICLE

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]

We’ll have a closer look at the blinking LED Arduino sketch we saw last time (Figure 1).

ACHTUNG!

ALLES TURISTEN UND NONTEKNISCHEN LOOKEN-PEEPERS! DAS KOMPUTERMASCHINE IST NICHT F¨UR DER GEFINGERPOKEN UND MITTENGRA-BEN! ODERWISE IST EASY TO SCHNAPPEN DER SPRINGENWERK, BLOWENFUSEN UND POPPEN-CORKEN MIT SPITZENSPARKSEN. IST NICHT F¨UR GEWERKEN BEI DUMMKOPFEN. DER RUBBER-NECKEN SIGHTSEEREN KEEPEN DAS COTTON-PICKEN H¨ANDER IN DAS POCKETS MUSS. ZO RE-LAXEN 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 isn’t required). Comments are for people who read your code and for you and try

ArduinoRobert Berger

Embedded Software Specialist

for mere m0rtals - PART 4

Page 17: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 17

TECHN

ICA

L ARTIC

LETECHNICAL ARTICLE

to understand what you wrote a long time ago. They (hopefully) explain what the program does, how it works, or why it’s written the way it is. It’s 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.

There’s 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. Let’s 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

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

Figure 2

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 digitalpin, without using the delay() function. This means that other codecan 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 boardthat’s attached to pin 13, so no hardware is needed for this example.

created 2005by David A. Mellismodified 8 Feb 2010by Paul Stoffregen

This example code is in the public domain

http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay*/

Listing 1: BlinkWithoutDelay.ino

Page 18: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 18

TECHN

ICA

L ARTIC

LETECHNICAL 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 10’s 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.

Author’s 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. It’s being used to indicate which Arduino pin the LED is connected to and since it never changes, it’s 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 it’s easier to move the LED to a different pin—you 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, it’s 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 sub-routine) is a named piece of code that can be used from elsewhere in a sketch. The setup() function [9] as seen in

line 36 is called once, when the sketch starts. It’s 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

Figure 3

Figure 4

Figure 5

1

2

3

4

5

6

7

8

9

10

11

12

13

14

int ledPin = 13; // LED connected to digital pin 13

void setup(){ pinMode(ledPin, OUTPUT); // sets the digital pin as output}

void loop(){ digitalWrite(ledPin, HIGH); // sets the LED on delay(500); // waits 500 msec digitalWrite(ledPin, LOW); // sets the LED off delay(500); // waits 500 msec}

Listing 2: delay-example.ino

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

// constants won’t change. Used here to// set pin numbers:const int ledPin = 13; // the number of the LED pin

// Variables will change:int ledState = LOW; // ledState used to set the LEDlong previousMillis = 0; // 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)}

Listing 3: 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 you’d put code that needs to be running all the time.

// check to see if it’s 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); }}

Listing 4: BlinkWithoutDelay.ino continued

Page 19: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 19

TECHN

ICA

L ARTIC

LETECHNICAL 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 don’t need them for anything.

Author’s 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 we’ll 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

BeStar®

ACOUSTICS & SENSORS

Teamwork • Technology • Invention • Listen • Hear

PRODUCTSSpeakers

Buzzers

Piezo Elements

Back-up Alarms

Horns

Sirens/Bells

Beacons

Microphones

Sensors

INDUSTRIESAutomotive

Durables

Medical

Industrial

Mobile

Fire / Safety

Security

Consumer

Leisure

QS9000 • TS/ ISO16949 • ISO14001 • ISO13485 • ISO9001

bestartech.com | [email protected] | 520.439.9204

Preferred acoustic componentsupplier to OEMs worldwide

[6] ”vTaskDelay()” http://www.freertos.org/a00127.html

[7] ”usleep()” http://pubs.opengroup.org/online-pubs/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/pin-Mode

[11] ”digitalWrite()” http://arduino.cc/en/Reference/digi-talWrite

[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. ■

Page 20: EEWeb Pulse - Volume 51

EEWeb | Electrical Engineering Community Visit www.eeweb.com 20

RETURN TO

ZERORETURN TO ZERO

EEWebElectrical Engineering Community

Join Todaywww.eeweb.com/register