EEWeb Pulse - Volume 51

Page 1

EEWeb

PULSE

EEWeb.com

Issue 51 June 19, 2012

Tamara Schmitz Intersil

Electrical Engineering Community


EEWeb Electrical Engineering Community

Contact Us For Advertising Opportunities

1.800.574.2791

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


TA B L E O F C O N T E N T S TABLE OF CONTENTS

4

Tamara Schmitz INTERSIL Interview with Tamara Schmitz - Applications Manager for Optical Sensors

10

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

12

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

16

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

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

RTZ - Return to Zero Comic

EEWeb | Electrical Engineering Community

20

Visit www.eeweb.com

3


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

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

FEATURED INTERVIEW

Tamara Schmitz Intersil 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

Tamara Schmitz - Applications Manager for Optical Sensors

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

4


INTERVIEW

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.

EEWeb | Electrical Engineering Community

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

Visit www.eeweb.com

5

FEATURED INTERVIEW

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


INTERVIEW

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.

EEWeb | Electrical Engineering Community

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 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 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

Visit www.eeweb.com

6

FEATURED INTERVIEW

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.


INTERVIEW

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?

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

7

FEATURED INTERVIEW

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.


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

EEWeb Electrical Engineering Community

Join Today www.eeweb.com/register

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

8

FEATURED 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 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


Avago Technologies LED Lighting Solutions

One LED. Infinite colors. World’s 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 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 • Indoor and outdoor full color display • LED advertisement panels • Decorative lighting

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:

www.avagoresponsecenter.com/led


F E AT U R E D P R O D U C T S New 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 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. 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 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

FEATURED PRODUCTS

Switch Family for 24V Battery Systems


Get the Datasheet and Order Samples http://www.intersil.com

4-Channel LED Driver with Independent Channel Control for Dynamic Dimming ISL97686

Features

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.

• 4 x 160mA, 75V Rated Channels with Integrated Channel Regulation FETs

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.

• 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

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

• Current Matching of ±1%

Related Literature

• General/Industrial/Automotive Lighting

• 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

• See Application note for “ISL97686IBZ_EVALZ” for SOIC Application

VIN: 9V~32V

Fuse D1

160mA MAX PER STRING

VIN SLEW

VLOGIC

GD

EN

CS

CLK SDI SDO

PGND

Q1

110

COMP

/CS EN_VSYNC

OVP

CSEL ISET1 ISET2 OSC PWM_SET/PLL

I_CH2

100

RSENSE

CHANNEL CURRENT (mA)

VDC

CH1 CH2 CH3 CH4

I_CH3

90 80

I_CH1

70

I_CH4

60 50 40 30 20 10 0

0

20

40

60

80

100

DIMMING DUTY CYCLE (%)

FIGURE 1. ISL97686 APPLICATION DIAGRAM

April 23, 2012 FN7953.0

FIGURE 2. PWM DIMMING LINEARITY

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.


TECHNICAL ARTICLE

Part 3 - D-Type Flip-Flops Paul Clarke Electronics Design Engineer

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

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

12

TECHNICAL ARTICLE

Illogical Logic


TECHNICAL ARTICLE Q

H

L

Q

Reset

H

H

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).

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

R

Q

0

0

!

0

1

1

1

0

0

1

1

X

Figure 2: SR TRUTH TABLE

L

D

Q

L

CLK Figure 3: D-TYPE FLIP-FLOP

H

L

Figure 4: GLITCH CIRCUIT

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

EEWeb | Electrical Engineering Community

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

Visit www.eeweb.com

13

TECHNICAL ARTICLE

Set

by adding a NOT gate between the S and R inputs and renaming the S input as D (Figure 3).


TECHNICAL ARTICLE

H

CLK

H

D

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

EEWeb | Electrical Engineering Community

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

Visit www.eeweb.com

14

TECHNICAL ARTICLE

Q

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).


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

2012

WI NNER


TECHNICAL ARTICLE

Arduino

for mere m0rtals - PART 4 Disclaimer

Dissection of BlinkWithoutDelay [3]

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.

Sketch

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 LOOKENPEEPERS! DAS KOMPUTERMASCHINE IST NICHT F¨UR DER GEFINGERPOKEN UND MITTENGRABEN! ODERWISE IST EASY TO SCHNAPPEN DER SPRINGENWERK, BLOWENFUSEN UND POPPENCORKEN MIT SPITZENSPARKSEN. IST NICHT F¨UR GEWERKEN BEI DUMMKOPFEN. DER RUBBERNECKEN SIGHTSEEREN KEEPEN DAS COTTONPICKEN H¨ANDER IN DAS POCKETS MUSS. ZO RELAXEN UND WATSCHEN DER. BLINKENLICHTEN.

EEWeb | Electrical Engineering Community

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

Visit www.eeweb.com

16

TECHNICAL ARTICLE

Robert Berger

Embedded Software Specialist


TECHNICAL ARTICLE

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

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

4 5

delay(ms)

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.

Parameters

The circuit: * LED attached from pin 13 to ground * Note: on most Arduinos, there is already an LED on the board that’s attached to pin 13, so no hardware is needed for this example.

Returns

6 7 8 9 10 11 12 13 14 15 16

created 2005 by David A. Mellis modified 8 Feb 2010 by Paul Stoffregen

17 18

This example code is in the public domain

19 20 21 22

Syntax

/* Blink without Delay

2 3

The delay() function pauses the program for the amount of time (in milliseconds) specified as parameter. (Remember: there are 1000 milliseconds in a second.)

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

Figure 2

EEWeb | Electrical Engineering Community

ms: the number of milliseconds to pause (unsigned long) 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

Visit www.eeweb.com

17

TECHNICAL 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.


TECHNICAL ARTICLE Listing 2: delay-example.ino 1

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 subroutine) is a named piece of code that can be used from elsewhere in a sketch. The setup() function [9] as seen in

EEWeb | Electrical Engineering Community

// LED connected to digital pin 13

2 3 4 5 6

void setup() { pinMode(ledPin, OUTPUT); }

// sets the digital pin as output

7 8 9 10 11

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.

int ledPin = 13;

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 10’s of milliseconds unless the Arduino sketch is very simple.

12 13 14

void loop() { digitalWrite(ledPin, HIGH); delay(500); digitalWrite(ledPin, LOW); delay(500); }

// // // //

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

Figure 3 Listing 3: BlinkWithoutDelay.ino continued 24 25 26

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

27 28 29 30

// Variables will change: int ledState = LOW; long previousMillis = 0;

// ledState used to set the LED // will store last time LED was updated

31 32 33 34

// 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)

35 36 37 38 39

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

Figure 4 Listing 4: BlinkWithoutDelay.ino continued 41 42 43

void loop() { // here is where you’d put code that needs to be running all the time.

44

// 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();

45 46 47 48 49 50

if(currentMillis – previousMillis > interval) { // save the last time you blinked the LED previousMillis = currentMillis;

51 52 53 54

// if the LED is off turn it on and vice-versa: if (ledState = LOW) ledState = HIGH; else ledState = LOW;

55 56 57 58 59 60 61 62 63 64

}

}

// set the LED with the ledState of the variable: digitalWrite(ledPin, ledState);

Figure 5

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

Visit www.eeweb.com

18


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

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.

[7] ”usleep()” http://pubs.opengroup.org/onlinepubs/009695399/functions/usleep.html

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

®

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

Teamwork • Technology • Invention • Listen • Hear

ACOUSTICS & SENSORS PRODUCTS

INDUSTRIES

Speakers

Automotive

Buzzers

Durables

Piezo Elements

Medical

Back-up Alarms

Industrial

Horns

Mobile

Sirens/Bells

Fire / Safety

Beacons

Security

Microphones

Consumer

Sensors

Leisure

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

TECHNICAL ARTICLE

change state (Figure 5).


RETURN TO ZERO RETURN TO ZERO

EEWeb Electrical Engineering Community

Join Today www.eeweb.com/register

EEWeb | Electrical Engineering Community

Visit www.eeweb.com

20


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.