Embedded systems interview questions
20 questions with answers. 1,548 open jobs in India ask for Embedded systems.
What's the difference between a microcontroller and a microprocessor?
A microprocessor generally does not have RAM, ROM and IO pins. It usually uses its pins as a bus to interface to peripherals such as RAM, ROM, Serial ports, Digital and Analog IO. It is expandable at the board level due to this.
A microcontroller is 'all in one', the processor, ram, IO all on the one chip, as such you cannot (say) increase the amount of RAM available or the number of IO ports. The controlling bus is internal and not available to the board designer.
This means that a microprocessor is generally capable of being built into bigger general purpose applications than a microcontroller. The microcontroller is usually used for more dedicated applications.
All of these are very general statements. There are chips available that blur the boundaries.
From Electrical Engineering Stack Exchange: asked by endolith, answered by JohnC (CC BY-SA 3.0)
Is C++ suitable for embedded systems?
Yes, C++ is still useful in embedded systems. As everyone else has said, it still depends on the system itself, like an 8-bit uC would probably be a no-no in my book even though there is a compiler out there and some people do it (shudder). There's still an advantage to using C++ even when you scale it down to something like "C+" even in a 8-bit micro world. What do I mean by "C+"? I mean don't use new/delete, avoid exceptions, avoid virtual classes with inheritance, possibly avoid inheritance all together, be very careful with templates, use inline functions instead of macros, and use
constvariables instead of#defines.I've been working both in C and C++ in embedded systems for well over a decade now, and some of my youthful enthusiasm for C++ has definitely worn off due to some real world problems that shake one's naivete. I have seen the worst of C++ in an embedded systems which I would like to refer to as "CS programmers gone wild in an EE world." In fact, that is something I'm working on with my client to improve this one codebase they have among others.
The danger of C++ is because it's a very very powerful tool much like a two-edged sword that can cut both your arm and leg off if not educated and disciplined properly in it's language and general programming itself. C is more like a single-edged sword, but still just as sharp. With C++ it's too easy to get very high-levels of abstraction and create obfuscated interfaces that become meaningless in the long-term, and that's partly due to C++ flexibility in solving the same problem with many different language features(templates, OOP, procedural, RTTI, OOP+templates, overloading, inlining).
I finished a two 4-hour seminars on Embedded Software in C++ by the C++ guru, Scott Meyers. He pointed out some things about templates that I never considered before and how much more they can help creating safety-critical code. The jist of it is, you can't have dead code in software that has to meet stringent safety-critical code requirements. Templates can help you accomplish this, since the compiler only creates the code it needs when instantiating templates. However, one must become more thoroughly educated in their use to design correctly for this feature which is harder to accomplish in C because linkers don't always optimize dead code. He also demonstrated a feature of templates that could only be accomplished in C++ and would have kept the Mars Climate Observer from crashing had NASA implemented a similar system to protect units of measurement in the calculations.
Scott Meyers is a very big proponent on templates and judicious use of inlining, and I must say I'm still skeptical on being gung ho about templates. I tend to shy away from them, even though he says they should only be applied where they become the best tool. He also makes the point that C++ gives you the tools to make really good interfaces that are easy to use right and make it hard to use wrong. Again, that's the hard part. One must come to a level of mastery in C++ before you can know how to apply these features in most efficient way to be the best design solution.
The same goes for OOP. In the embedded world, you must familiarize yourself with what kind of code the compiler is going to spit out to know if you can handle the run-time costs of run-time polymorphism. You need to be willing to make measurements as well to prove your design is going to meet your deadline requirements. Is that new InterruptManager class going to make my interrupt latency too long? There are other forms of polymorphism that may fit your problem better such as link-time polymorphism which C can do as well, but C++ can do through the Pimpl design pattern (Opaque pointer).
I say that all to say, that C++ has its place in the embedded world. You can hate it all you want, but it's not going away. It can be written in a very efficient manner, but it's harder to learn how to do it correctly than with C. It can sometimes work better than C at solving a problem and sometimes expressing a better interface, but again, you've got to educate yourself and not be afraid to learn how.
From Electrical Engineering Stack Exchange: asked by Toby Jaffey, answered by Jay Atkinson (CC BY-SA 4.0)
Can microcontrollers be run at arbitrarily low clock frequencies?
Yes. If the datasheet says "fully static operation", then you can clock it at any speed, even 0 Hz. A "dynamic" chip needs to have a clock at a specific rate or it loses its state.
From Electrical Engineering Stack Exchange: asked by endolith, answered by todbot (CC BY-SA 2.5)
When is a MOSFET more appropriate as a switch than a BJT?
When is a MOSFET more appropriate as a switch than a BJT?
Answer: 1) a MOSFET is better than a BJT when:
Read the rest at the sourceFrom Electrical Engineering Stack Exchange: asked by Mark, answered by Gabriel Staples (CC BY-SA 4.0)
Why are there no 256-bit or 512-bit microprocessors?
Think about it. What exactly do you envision a "256 bit" processor being? What makes the bit-ness of a processor in the first place?
I think if no further qualifications are made, the bit-ness of a processor refers to its ALU width. This is the width of the binary number that it can handle natively in a single operation. A "32 bit" processor can therefore operate directly on values up to 32 bits wide in single instructions. Your 256 bit processor would therefore contain a very large ALU capable of adding, subtracting, ORing, ANDing, etc, 256 bit numbers in single operations. Why do you want that? What problem makes the large and expensive ALU worth having and paying for, even for those cases where the processor is only counting 100 iterations of a loop and the like?
The point is, you have to pay for the wide ALU whether you then use it a lot or only a small fraction of its capabilities. To justify a 256 bit ALU, you'd have to find an important enough problem that can really benefit from manipulating 256 bit words in single instructions. While you can probably contrive a few examples, there aren't enough of such problems that make the manufacturers feel they will ever get a return on the significant investment required to produce such a chip. If it there are niche but important (well-funded) problems that can really benefit from a wide ALU, then we would see very expensive highly targeted processors for that application. Their price, however, would prevent wide usage outside the narrow application that it was designed for. For example, if 256 bits made certain cryptography applications possible for the military, specialized 256 bit processors costing 100s to 1000s of dollars each would probably emerge. You wouldn't put one of these in a toaster, a power supply, or even a car though.
I should also be clear that the wide ALU doesn't just make the ALU more expensive, but other parts of the chip too. A 256 bit wide ALU also means there have to be 256 bit wide data paths. That alone would take a lot of silicon area. That data has to come from somewhere and go somewhere, so there would need to be registers, cache, other memory, etc, for the wide ALU to be used effectively.
Another point is that you can do any width arithmetic on any width processor. You can add a 32 bit memory word into another 32 bit memory word on a PIC 18 in 8 instructions, whereas you could do it on the same architecture scaled to 32 bits in only 2 instructions. The point is that a narrow ALU doesn't keep you from performing wide computations, only that the wide computations will take longer. It is therefore a question of speed, not capability. If you look at the spectrum of applications that need to use particular width numbers, you will see very very few require 256 bit words. The expense of accelerating just those few applications with hardware that won't help the others just isn't worth it and doesn't make a good investment for product development.
From Electrical Engineering Stack Exchange: asked by Michael harris, answered by Olin Lathrop (CC BY-SA 3.0)
What is the difference between a DSP and a standard microcontroller?
To be honest the line between the two is almost gone nowadays and there are processors that can be classified as both (AD Blackfin for instance).
Generally speaking:
Microcontrollers are integer math processors with an interrupt sub system. Some may have hardware multiplication units, some don't, etc. Point is they are designed for simple math, and mostly to control other devices.
DSPs are processors optimized for streaming signal processing. They often have special instructions that speed common tasks such as multiply-accumulate in a single instruction. They also often have other vector or SIMD instructions. Historically they weren't interrupt based systems and operated with non-standard memory systems optimized for their purpose making them more difficult to program. They were usually designed to operate in one big loop processing a data stream. DSP's can be designed as integer, fixed point or floating point processors.
Historically if you wanted to process audio streams, video streams, do fast motor control, anything that required processing a stream of data at high speed you would look to a DSP.
If you wanted to control some buttons, measure a temperature, run a character LCD, control other ICs which are processing things, you'd use a microcontroller.
Today, you mostly find general purpose microcontroller type processors with either built in DSP-like instructions or with on chip co-processors to deal with streaming data or other DSP operations. You don't see pure DSP's used much anymore except in specific industries.
The processor market is much broader and more blurry than it used to be. For instance i hardly consider a ARM cortex-A8 SoC a micro-controller but it probably fits the standard definition, especially in a PoP package.
EDIT: Figured i'd add a bit to explain when/where i've used DSPs even in the days of application processors.
A recent product i designed was doing audio processing with X channels of input and X channels of output per 'zone'. The intended use for the product meant that it would often times sit there doing its thing, processing the audio channels for years without anyone touching it. The audio processing consisted of various acoustical filters and functions. The system also was "hot plugable" with the ability to add some number of independent 'zones' all in one box. It was a total of 3 PCB designs (mainboard, a backplane and a plug in module) and the backplane supported 4 plug in modules. Quite a fun project as i was doing it solo, i got to do the system design, schematic, PCB layout and firmware.
Now i could have done the entire thing with an single bulky ARM core, i only needed about 50MIPS of DSP work on 24bit fixed point numbers per zone. But because i knew this system would operate for an extremely long time and knew it was critical that it never click or pop or anything like that. I chose to implement it with a low power DSP per zone and a single PIC microcontroller that played the system management role. This way even if one of the uC functions crashed, maybe a DDOS attack on its Ethernet port, the DSP would happily just keep chugging away and its likely no one would ever know.
So the microcontroller played the role of running the 2 line character LCD, some buttons, temperature monitoring and fan control (there were also some fairly high power audio amplifiers on each board) and even served an AJAX style web page via ethernet. It also managed the DSPs via a serial connection.
So thats a situation where even in the days where i could have used a single ARM core to do everything, the design dictated a dedicated signal processing IC.
Other areas where i've run into DSPs:
*High End audio - Very high end receivers and concert quality mixing and processing gear
*Radar Processing - I've also used ARM cores for this in low end apps.
*Sonar Processing
*Real time computer vision
For the most part, the low and mid ends of the audio/video/similar space have been taken over by application processors which combine a general purpose CPU with co-proc offload engines for various applications.
From Electrical Engineering Stack Exchange: asked by Kevin Vermeer, answered by Mark (CC BY-SA 2.5)
What's the cheapest way to link a few microcontrollers wirelessly at low speeds over short distances?
Infrared emitters and receivers can be used to transmit/receive data. However, interference with other devices like remote controls might be a problem. If the connection needs to be really reliable, this probably wouldn't be that great of an option. However, you might be able to find a really uncommon wavelength emitter and receiver to limit the amount of interference.
These are pretty common, and very cheap. Packs of 20 emitters for $1 and packs of 100 receivers for $13 can be found on eBay (not including shipping). Lots of electronics stores have them as well.
From Electrical Engineering Stack Exchange: asked by Toby Jaffey, answered by Ponkadoodle (CC BY-SA 3.0)
Push-pull/open drain; pull-up/pull-down
This answer is general to processors and peripherals, and has an SRAM specific comment at the end, which is probably pertinent to your specific RAM and CPU.
Output pins can be driven in three different modes:
- open drain - a transistor connects to low and nothing else
- open drain, with pull-up - a transistor connects to low, and a resistor connects to high
- push-pull - a transistor connects to high, and a transistor connects to low (only one is operated at a time)
Input pins can be a gate input with a:
- pull-up - a resistor connected to high
- pull-down - a resistor connected to low
- pull-up and pull-down - both a resistor connected to high and a resistor connected to low (only useful in rare cases).
There is also a Schmitt triggered input mode where the input pin is pulled with a weak pull-up to an initial state. When left alone it persists in its state, but may be pulled to a new state with minimal effort.
Open drain is useful when multiple gates or pins are connected together with an (external or internal) pull-up. If all the pin are high, they are all open circuits and the pull-up drives the pins high. If any pin is low they all go low as they tied together. This configuration effectively forms an
ANDgate._____________________________
Note added November 2019 - 7+ years on: The configuration of combining multiple open collector/drain outputs has traditionally been referred to as a "Wired OR" configuration. CALLING it an OR (even traditionally) does not make it one. If you use negative logic (which traditionally may have been the case) things will be different, but in the following I'll stick to positive logic convention which is what is used as of right unless specifically stated.
The above comment about forming an 'AND' gate has been queried a number of times over the years - and it has been suggested that the result is 'really' an 'OR' gate. It's complex.
The simple picture' is that if several open collector outputs are connected together then if any one of the open collector transistors is turned on then the common output will be low. For the common output to be high all outputs must be off.
If you consider combining 3 outputs - for the result to be high all 3 would need to have been high individually. 111 -> 1. That's an 'AND'.
If you consider each of the output stages as an inverter then for each one to have a high output it's input must be low. So to get a combined high output you need three 000 -> 1 . That's a 'NOR'.
Some have suggested that this is an OR - Any of XYZ with at least 1 of these is a 1 -> 1.
I can't really "force" that idea onto the situation._________________________________
When driving an SRAM you probably want to drive either the data lines or the address lines high or low as solidly and rapidly as possible so that active up and down drive is needed, so push-pull is indicated. In some cases with multiple RAMs you may want to do something clever and combine lines, where another mode may be more suitable.
With SRAM with data inputs from the SRAM if the RAM IC is always asserting data then a pin with no pull-up is probably OK as the RAM always sets the level and this minimises load. If the RAM data lines are sometimes open circuit or tristate you will need the input pins to be able to set their own valid state. In very high speed communications you may want to use a pull-up and a pull-down so the parallel effective resistance is the terminating resistance, and the bus idle voltage is set by the two resistors, but this is somewhat specialist.
From Electrical Engineering Stack Exchange: asked by Randomblue, answered by Russell McMahon (CC BY-SA 4.0)
How can anyone use a microcontroller which has only 384 bytes of program memory?
You kids, get off my lawn!
384 bytes is plenty of space to create something quite complex in assembler.
If you dig back through history to when computers were the size of a room, you'll find some truly amazing feats of artistry executed in <1k.
For instance, read the classic Story of Mel - A Real Programmer. Admittedly, those guys had 4096 words of memory to play with, the decadent infidels.
Also look at some of the old demoscene competitions where the challenge was to fit an "intro" into the bootblock of a floppy, typical targets being 4k or 40k and usually managing to include music and animation.
Edit to add: Turns out you can implement the world's first $100 scientific calculator in 320 words.
Edit for the young 'uns:
- Floppy = floppy disk.
- Bootblock = 1st sector of the floppy read at bootup.
- Demoscene = programming competitions amongst hacker groups.
- Assembler = fancy way of programming a device if you're too soft to use 8 toggle switches and a "store" button.
From Electrical Engineering Stack Exchange: asked by coder543, answered by John U (CC BY-SA 3.0)
Why aren't FPGAs ubiquitous?
You are ignoring a lot of factors that go into making design choices:
- Cost. FPGAs are more expensive than micros for the same complexity of logic.
- Logic complexity. Executable code can implement far more complicated logic than the same number of gates in the micro used directly.
- Ease of development. It's easier to write executable code than to define logic for all but small problems. Even modest microcontroller projects have thousands of lines of code. Developing the equivalent logic definitions would take much longer and be much more difficult to debug and verify.
- Power consumption. Since FPGAs are intended for high speed operations that micros can't handle (else you'd use a micro), they are not optimized for low power. This makes them unsuitable for some low power applications. Some micros have sleep currents under 1 µA, and can operate on just a few µA at slow clock rates. Try finding a FPGA that can do this.
The main advantages of FPGAs versus micros is that they are faster and can do more things in parallel. Other than that, you'd rather use a micro. Therefore in the design process, you usually start out with a micro, then grudgingly go to a FPGA when you really need the speed and/or concurrent high speed operation. Even then, you implement only the speed-critical parts in a FPGA, and leave the lower speed control functions and the like in the micro.
From Electrical Engineering Stack Exchange: asked by Utku, answered by Olin Lathrop (CC BY-SA 3.0)
What is a boot loader, and how would I develop one?
A bootloader is a program that runs in the microcontroller to be programmed. It receives new program information externally via some communication means and writes that information to the program memory of the processor.
This is in contrast with the normal way of getting the program into the microcontroller, which is via special hardware built into the micro for that purpose. On PICs, this is a SPI-like interface. If I remember right, AVRs use Jtag, or at least some of them do. Either way, this requires some external hardware that wiggles the programming pins just right to write the information into the program memory. The HEX file describing the program memory contents originates on a general purpose computer, so this hardware connects to the computer on one side and the special programming pins of the micro on the other. My company makes PIC programmers among other things as a sideline, so I am quite familiar with this process on PICs.
The important point of external programming via specialized hardware is that it works regardless of the existing contents of program memory. Microcontrollers start out with program memory erased or in a unknown state, so external programming is the only means to get the first program into a micro.
If you are sure about the program you want to load into your product and your volumes are high enough, you can have the manufacturer or a distributor program chips for you. The chip gets soldered to the board like any other chip, and the unit is ready to go. This can be appropriate for something like a toy, for example. Once the firmware is done, it's pretty much done, and it will be produced in large volumes.
If your volumes are lower, or more importantly, you expect ongoing firmware development and bug fixes, you don't want to buy pre-programmed chips. In this case blank chips are mounted on the board and the firmware has to get loaded onto the chip as part of the production process. In that case the hardware programming lines have to be made available somehow. This can be via a explicit connector, or pogo pin pads if you're willing to create a production test fixture. Often such products have to be tested and maybe calibrated anyway, so the additional cost of writing the program to the processor is usually minimal. Sometimes when small processors are used a special production test firmware is first loaded into the processor. This is used to facilitate testing and calibrating the unit, then the real firmware is loaded after the hardware is known to be good. In this case there are some circuit design considerations to allow access to the programming lines sufficiently for the programming process to work but to also not inconvenience the circuit too much. For more details on this, see my in-circuit programming writeup.
So far so good, and no bootloader is needed. However, consider a product with relatively complex firmware that you want field upgradable or even allow the end customer to upgrade. You can't expect the end customer to have a programmer gadget, or know how to use one properly even if you provided one. Actually one of my customers does this. If you buy their special field customizing option, you get one of my programmers with the product.
However, in most cases you just want the customer to run a program on a PC and have the firmware magically updated. This is where a bootloader comes in, especially if your product already has a communications port that can easily interface with a PC, like USB, RS-232, or ethernet. The customer runs a PC program which talks to the bootloader already in the micro. This sends the new binary to the bootloader, which writes it to program memory and then causes the new code to be run.
Sounds simple, but it's not, at least not if you want this process to be robust. What if a communication error happens and the new firmware is corrupt by the time it arrives at the bootloader? What if power gets interrupted during the boot process? What if the bootloader has a bug and craps on itself?
Read the rest at the sourceFrom Electrical Engineering Stack Exchange: asked by mina_g, answered by Olin Lathrop (CC BY-SA 3.0)
What exactly fries the chip when you invert power supply?
Most commercial IC circuits are isolated from the substrate material by a reverse-biased P-N junction (including CMOS parts). The substrate is usually tied to the voltage expected to be most negative.
If it isn't, then that junction becomes forward biased and can conduct a great deal of current, melting metal or heating the junction to the point where it no longer acts as a diode. That is typically at a voltage of about 0.6V, but the IC makers play it safe usually by telling you not to go lower than -0.3V.
(referring to the below diagram, but not shown, the substrate would be tied to pin 5)
Most CMOS parts have another twist that if part of the chip has a normal Vdd and another part sees a big negative current it will trigger a big parasitic SCR that is a side effect of the structure, then the device's power supply draws a large current which causes overheating, melting etc. if the current is not externally limited. That is called latch-up.
From Electrical Engineering Stack Exchange: asked by triplebig, answered by Spehro 'speff' Pefhany (CC BY-SA 3.0)
RTOS for Embedded Systems
I haven't had much personal experience with RTOS's other than QNX (which is great on the whole but it's not cheap and I have had a really bad experience with a particular board vendor and QNX's we-don't-care attitude for systems other than their most common) which is too large for PICs and MSP430's.
Where you will benefit from an RTOS is in areas such as
- thread management/scheduling
- inter-thread communications + synchronization
- I/O on systems with stdin/stdout/stderr or serial ports or ethernet support or a filesystem (not an MSP430 or PIC for the most part, except for the serial ports)
For peripherals of a PIC or MSP430: for serial ports I'd use a ring buffer + interrupts... something I write once per system and just reuse; other peripherals I don't think you'd find much support from an RTOS, as they are so vendor-specific.
If you need timing that is rock-solid to the microsecond, an RTOS probably won't help -- RTOS's have bounded timing, but typically do have timing jitter in their scheduling due to context switching delays... QNX running on a PXA270 had jitter in the tens of microseconds typical, 100-200us maximum, so I wouldn't use it for stuff that has to run faster than about 100Hz or which needs timing much more accurate than about 500us. For that kind of stuff you probably will have to implement your own interrupt handling. Some RTOS's will play nicely with that, and others will make it a royal pain: your timing and their timing may not be able to coexist well.
If the timing/scheduling is not too complex, you may be better off using a well-designed state machine. I would highly recommend reading Practical Statecharts in C/C++ if you haven't already. We've used this approach in some of our projects where I work, and it's got some real advantages over traditional state machines for managing complexity.... which is really the only reason you need an RTOS.
From Electrical Engineering Stack Exchange: asked by Kortuk, answered by Jason S (CC BY-SA 2.5)
When to use pull-down vs. pull-up resistors?
The answer depends on what you want the "default" configuration to be. For example, say you have a down-stream N-channel MOSFET, and you want it default off. Then you would use a pull-down resistor to ensure this behavior if the input becomes high impedance.
simulate this circuit – Schematic created using CircuitLab
On the other hand, suppose you have an upstream P-channel MOSFET, and want it default off. This time a pull up resistor is required to create this behavior.
There's also the alternative case where you want a device to be default-on, in which case the above two cases would be reversed (pull-up for the N-channel MOSFET, pull-down for the P-channel MOSFET).
A few other considerations:
I2C lines specify pull-up resistors because devices are "expected" to have an open-drain to ground, and thus need some way to raise the line potential.
Analog comparators are usually configured as open-drain devices, and thus also need pull up resistors to get a high potential output.
You may draw more current using pullup/pulldown resistors, depending on what's hooked to the input/output.
Either configuration could works equally well in your application (i.e. there's no significant advantage one way or the other).
... And any number of very application-specific reasons why one configuration may be preferred.
From Electrical Engineering Stack Exchange: asked by osvein, answered by helloworld922 (CC BY-SA 3.0)
Can I cut an IC?
How do you intend to do this butchery?
Unless you have very specialized tools, a Dremel cutting disk or something like that could generate a lot of static charges. Well enough to kill the chip!
Moreover, mechanical stresses could damage the internal bond wires, or even the die. Let alone you would have the bond wires to the cut-off pins protruding flush from the cut side (8 of them), maybe shorted together due to harsh mechanical stresses during the butchering action.
People needing to reverse-engineer a chip do this kind of things, but they use much more "delicate" measures. Moreover, they want to expose the die, so they "cut" off the upper part of the package.
In particular see this video showing LASER decapsulation.
Google for "chip decapsulation" and you'll find tons of references and you'll understand why it is a costly process if you want your die to survive! People pay big bucks to reverse engineer chips (both for legitimate and criminal purposes). Legitimate purposes comprise failure analysis ("Why our top notch IC failed unexpectedly?!? Let's crack it open and see what happened!") or retrieving lost designs ("OK, we acquired this little IC design house with these excellent parts. But, wait! Where are the design sheets of the groundbreaking HQC954888PXQ processor?!? Who fired the design engineers who knew?!?" - Yes these things happen!).
BTW, Did I mention all these methods are delicate?!? Side cutters are not what I could call delicate. When I was a boy I remember cutting a (dead) IC to see the die using a big side cutter: it splintered wildly!
YMMV!
From Electrical Engineering Stack Exchange: asked by v.m., answered by LorenzoDonati4Ukraine-OnStrike (CC BY-SA 4.0)
Using volatile in embedded C development
A definition of
volatilevolatiletells the compiler that the variable's value may change without the compiler knowing. Hence the compiler cannot assume the value did not change just because the C program seems not to have changed it.On the other hand, it means that the variable's value may be required (read) somewhere else the compiler does not know about, hence it must make sure that every assignment to the variable is actually carried out as a write operation.
Use cases
volatileis required when- representing hardware registers (or memory-mapped I/O) as variables - even if the register will never be read, the compiler must not just skip the write operation thinking "Stupid programmer. Tries to store a value in a variable which he/she will never ever read back. He/she won't even notice if we omit the write." Conversly, even if the program never writes a value to the variable, its value may still be changed by hardware.
- sharing variables between execution contexts (e.g. ISRs/main program) (see kkramo's answer)
Effects of
volatileWhen a variable is declared
volatilethe compiler must make sure that every assignment to it in program code is reflected in an actual write operation, and that every read in program code reads the value from (mmapped) memory.For non-volatile variables, the compiler assumes it knows if/when the variable's value changes and can optimize code in different ways.
For one, the compiler can reduce the number of reads/writes to memory, by keeping the value in CPU registers.
Example:
void uint8_t compute(uint8_t input) { uint8_t result = input + 2; result = result * 2; if ( result > 100 ) { result -= 100; } return result; }Here, the compiler will probably not even allocate RAM for the
resultvariable, and will never store the intermediate values anywhere but in a CPU register.If
resultwas volatile, every occurrence ofresultin the C code would require the compiler to perform an access to RAM (or an I/O port), leading to a lower performance.Secondly, the compiler may re-order operations on non-volatile variables for performance and/or code size. Simple example:
int a = 99; int b = 1; int c = 99;could be re-ordered to
int a = 99; int c = 99; int b = 1;which may save an assembler instruction because the value
99won't have to be loaded twice.If
a,bandcwere volatile the compiler would have to emit instructions which assign the values in the exact order as they are given in the program.The other classic example is like this:
volatile uint8_t signal; void waitForSignal() { while ( signal == 0 ) { // Do nothing. } }If, in this case,
signalwere notvolatile, the compiler would 'think' thatwhile( signal == 0 )may be an infinite loop (becausesignalwill never be changed by code inside the loop) and might generate the equivalent ofvoid waitForSignal() { if ( signal != 0 ) { return; } else { while(true) { // <-- Endless loop! // do nothing. } } }Considerate handling of
volatilevaluesAs stated above, a
volatilevariable can introduce a performance penalty when it is accessed more often than actually required. To mitigate this issue, you can "un-volatile" the value by assignment to a non-volatile variable, likevolatile uint32_t sysTickCount; void doSysTick() { uint32_t ticks = sysTickCount; // A single read access to sysTickCount ticks = ticks + 1; setLEDState( ticks < 500000L ); if ( ticks >= 1000000L ) { ticks = 0; } sysTickCount = ticks; // A single write access to volatile sysTickCount }Read the rest at the sourceFrom Electrical Engineering Stack Exchange: asked by Pryda, answered by JimmyB (CC BY-SA 4.0)
Why use PLC instead of microcontroller?
I'd think a major factor is people. The engineers that can design a microcontroller to run a factory are busy making batches of small devices. Engineers that work on brand name PLCs use standard software packages, they don't have to deal with lower level programming, most problems they encounter someone else has already solved with that hardware (comms to strange devices, IO issues, PIDs). Also the engineers are interchangeable, with a good spec or code commenting you don't need the engineer that built a system there when you need to change the code.
It's also a bit like asking why would someone buy a PC when they could build their own.
From Electrical Engineering Stack Exchange: asked by Saneesh A T, answered by daniel (CC BY-SA 3.0)
Programming microcontrollers: JTAG, SPI, USB oh my!?
ATMEGA microcontrollers like the one in the arduino that are coming straight from the factory can only be programmed using the SPI or JTAG interface.
SPI stands for Serial Peripheral Interface and is a way for microcontrollers to communicate with each other or with the outside world. It's also called 3-wire sometimes because it uses three wires to communicate. To program a chip, you will need a special programmer which reads commands from USB to drive the SPI lines to program the chip. A popular one seems to be the USBTinyISP from Adafruit. A very good introduction into SPI programming is at SparkFun. The most popular applications for programming Atmel AVR chips are avrdude (cmd line), ponyprog (doesn't work with newer programmers) and in some cases AVR Studio (if your programmer supports it). The advantage of SPI programming is that you can program any Atmel chip straight from the factory so you wouldn't always need an Arduino in your projects.
Where SPI is "just another" serial protocol, JTAG is a protocol which is especially designed to program and debug microcontrollers. Not all Atmel micro's support JTAG but the ones that are used in the Arduino do. The JTAG protocol can be used for cool things like "in circuit emulation" and debugging which means that it enables you to see the state of the program in your microcontroller while it's actually running. To do this you'll need a special programmer. Seen my answer for another question.
To program a chip using USB, you'll have to program it first with a "bootloader" using SPI or JTAG. Once loaded with the bootloader, the system will be programmable from any PC using a USB-Serial converter. The downside is that the bootloader takes up some memory space and this method does not allow you to see the state of the chip while it's running.
From Electrical Engineering Stack Exchange: asked by jdiaz, answered by bpijls (CC BY-SA 3.0)
How do I measure a negative voltage with a ADC?
An inverting amplifier does not need a negative rail to invert the voltage.
Try to think of your power rails as what supply your output. If you look at the circuit, all op-amp pins are tied to a voltage of 0V or higher. When your range of -1 to -3 comes in, it will show up as the exact opposite of 1 to 3 on the output. This also gives you some advantages as a buffer, as the input impedance of your pin will not affect this circuit very much (so long as Rin||Rf is large).
I agree that a simple resistor divider does the job -- just letting you know that this also works.
From Electrical Engineering Stack Exchange: asked by Kevin Boyd, answered by Kortuk (CC BY-SA 3.0)
Why does TI have so many microcontrollers?
I am a TI employee who works in an MCU development group, but this is not an official statement from TI. In particular, this is not an official statement about roadmaps or priorities. Also, I'm not in marketing, so if I contradict any of our marketing material, they're right and I'm wrong. :-)
M D's answer is correct, but I thought some more detail would be helpful. TI targets different applications with different requirements. When you're competing for an MCU socket (and there is a lot of competition in this industry), both features and price matter. A ten cent cost difference can win or lose the socket. One of the main drivers of cost is die size -- how much stuff is on the chip. Thus, it makes sense to have different product lines, and different families within those product lines. Product lines differ mainly in peripheral types and architecture, while families within a line products differ mainly in terms of cost and feature set.
Here are some details on the product lines:
- Hercules is a continuation of the TMS470/TMS570 line. It's focused on safety and performance. One of the key features of Hercules is dual CPUs running the same code in parallel ("lock-step"). This lets you immediately detect faults in the CPU itself. Check out this datasheet for some performance info on a newer product. The Cortex-R5F CPU runs at >300 MHz, and there's a large number of peripherals with higher-end features -- the CAN modules have 64 mailboxes, for example. Obviously, this stuff isn't cheap. But look at the applications -- defibrillators, ventilators, elevators, insulin pumps... these are places where customers are willing to pay for safety. Hercules also goes into automotive products that have a wider temperature range and longer operating life.
- C2000's focus is on supporting control algorithms. The C28x "CPU" is really a DSP, and its instruction set has been extended to handle things like trigonometry and complex numbers. There's also a separate task-based processor called the Control Law Accelerator (CLA) that can run control algorithms independently of the CPU. The ADCs and PWMs support a lot of timing options, too. Performance varies from midrange (Piccolo) to high-end (dual-core Delfino). The big applications here are power converters, power line communication, industrial drives, and motor control.
- MSP430 is all about low power. They have some products that use FRAM (ferroelectric nonvolatile memory), which uses less power than flash, and even one that runs off of 0.9V (one battery). They have some less-common peripherals to support things like LCDs and capacitive touch sensing. Look through their datasheets and you'll see applications like remote sensors, smoke alarms, and smart meters.
- I don't know much about the Wireless MCU group, but obviously wireless connectivity has its own special requirements. They seem to have Cortex-M and MSP430 CPUs, with applications in consumer electronics and the Internet of Things. IoT has been a big buzzword for a while now, so I'd imagine that's one of their main targets. Their newest (?) product is described as an "Internet-on-a-chip™ solution". UPDATE: Fellow TIer justinrjy commented with more info about Wireless/Connectivity MCUs: "'Wireless MCU' products are distinguished by having a processor core that runs the drivers/stack of the wireless protocol. For instance, the CC26xx runs the entire BLE stack on the uC itself, making it really easy to develop for. Same with the CC3200, except that processor runs the WiFi drivers all on the Cortex-M4. The integrated core and drivers are really what make these a 'Wireless MCU', instead of a transceiver."
Read the rest at the sourceFrom Electrical Engineering Stack Exchange: asked by Andy_A̷n̷d̷y̷, answered by Adam Haun (CC BY-SA 3.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Electrical Engineering Stack Exchangeby its contributors, named on each answerCC BY-SA20 questions