Sign in
Explore Guest Blogging Opportunities at Voude Blog: Your Online Diary Platform
Explore Guest Blogging Opportunities at Voude Blog: Your Online Diary Platform
Your Position: Home - Commonly Used Accessories & Parts - A 'C' Test: The 0x10 Best Questions for Would-be ...
Guest Posts

A 'C' Test: The 0x10 Best Questions for Would-be ...

Jan. 13, 2025

A 'C' Test: The 0x10 Best Questions for Would-be ...

An obligatory and significant part of the recruitment process for embedded systems programmers seems to be the 'C Test'. Over the years, I have had to both take and prepare such tests and in doing so have realized that these tests can be very informative for both the interviewer and interviewee. Furthermore, when given outside the pressure of an interview situation, they can also be quite entertaining (hence this article).

Please visit our website for more information on this topic.

From the interviewee's perspective, you can learn a lot about the person that has written or administered the test. Is the test designed to show off the writer's knowledge of the minutiae of the ANSI standard rather than to test practical know-how? Does it test ludicrous knowledge, such as the ASCII values of certain characters? Are the questions heavily slanted towards your knowledge of system calls and memory allocation strategies, indicating that the writer may spend his time programming computers instead of embedded systems? If any of these are true, then I know I would seriously doubt whether I want the job in question.

From the interviewer's perspective, a test can reveal several things about the candidate. Primarily, one can determine the level of the candidate's knowledge of C. However, it is also very interesting to see how the person responds to questions to which they do not know the answers. Do they make intelligent choices, backed up with some good intuition, or do they just guess? Are they defensive when they are stumped, or do they exhibit a real curiosity about the problem, and see it as an opportunity to learn something? I find this information as useful as their raw performance on the test.

With these ideas in mind, I have attempted to construct a test that is heavily slanted towards the requirements of embedded systems. This is a lousy test to give to someone seeking a job writing compilers! The questions are almost all drawn from situations I have encountered over the years. Some of them are very tough; however, they should all be informative.

This test may be given to a wide range of candidates. Most entry-level applicants will do poorly on this test, while seasoned veterans should do very well. Points are not assigned to each question, as this tends to arbitrarily weight certain questions. However, if you choose to adapt this test for your own uses, feel free to assign scores.

Preprocessor

1. Using the #define statement, how would you declare a manifest constant that returns the number of seconds in a year? Disregard leap years in your answer.

#define SECONDS_PER_YEAR (60UL * 60UL * 24UL * 365UL)

I'm looking for several things here:

(a) Basic knowledge of the #define syntax (i.e. no semi-colon at the end, the need to parenthesize etc.).

(b) A good choice of name, with capitalization and underscores.

(c) An understanding that the pre-processor will evaluate constant expressions for you. Thus, it is clearer, and penalty free to spell out how you are calculating the number of seconds in a year, rather than actually doing the calculation yourself.

(d) A realization that the expression will overflow an integer argument on a 16 bit machine ' hence the need for the L, telling the compiler to treat the expression as a Long.

(e) As a bonus, if you modified the expression with a UL (indicating unsigned long), then you are off to a great start because you are showing that you are mindful of the perils of signed and unsigned types ' and remember, first impressions count!

2. Write the 'standard' MIN macro. That is, a macro that takes two arguments and returns the smaller of the two arguments.

#define MIN(A,B) ((A) <= (B) ? (A) : (B))

The purpose of this question is to test the following:

(a) Basic knowledge of the #define directive as used in macros. This is important, because until the inline operator becomes part of standard C, macros are the only portable way of generating inline code. Inline code is often necessary in embedded systems in order to achieve the required performance level.

(b) Knowledge of the ternary conditional operator. This exists in C because it allows the compiler to potentially produce more optimal code than an if-then-else sequence. Given that performance is normally an issue in embedded systems, knowledge and use of this construct is important.

(c) Understanding of the need to very carefully parenthesize arguments to macros.

(d) I also use this question to start a discussion on the side effects of macros, e.g. what happens when you write code such as :

least = MIN(*p++, b);

3. What is the purpose of the preprocessor directive #error?

Either you know the answer to this, or you don't. If you don't, then see reference 1. This question is very useful for differentiating between normal folks and the nerds. It's only the nerds that actually read the appendices of C textbooks that find out about such things. Of course, if you aren't looking for a nerd, the candidate better hope she doesn't know the answer.

Infinite Loops

4. Infinite loops often arise in embedded systems. How does one code an infinite loop in C?

There are several solutions to this question. My preferred solution is:

Another common construct is:

Personally, I dislike this construct because the syntax doesn't exactly spell out what is going on. Thus, if a candidate gives this as a solution, I'll use it as an opportunity to explore their rationale for doing so. If their answer is basically ' 'I was taught to do it this way and I have never thought about it since' ' then it tells me something (bad) about them. Conversely, if they state that it's the K&R preferred method and the only way to get an infinite loop passed Lint, then they score bonus points.

A third solution is to use a goto:

Candidates that propose this are either assembly language programmers (which is probably good), or else they are closet BASIC / FORTRAN programmers looking to get into a new field.

Data declarations

5. Using the variable a, write down definitions for the following:

(a) An integer

(b) A pointer to an integer

(c) A pointer to a pointer to an integer

(d) An array of ten integers

(e) An array of ten pointers to integers

(f) A pointer to an array of ten integers

(g) A pointer to a function that takes an integer as an argument and returns an integer

(h) An array of ten pointers to functions that take an integer argument and return an integer.

The answers are:

People often claim that a couple of these are the sorts of thing that one looks up in textbooks ' and I agree. While writing this article, I consulted textbooks to ensure the syntax was correct. However, I expect to be asked this question (or something close to it) when in an interview situation. Consequently, I make sure I know the answers ' at least for the few hours of the interview. Candidates that don't know the answers (or at least most of them) are simply unprepared for the interview. If they can't be prepared for the interview, what will they be prepared for?

Static

6. What are the uses of the keyword static?

This simple question is rarely answered completely. Static has three distinct uses in C:

(a) A variable declared static within the body of a function maintains its value between function invocations.

(b) A variable declared static within a module [1], (but outside the body of a function) is accessible by all functions within that module. It is not accessible by functions within any other module. That is, it is a localized global.

(c) Functions declared static within a module may only be called by other functions within that module. That is, the scope of the function is localized to the module within which it is declared.

Most candidates get the first part correct. A reasonable number get the second part correct, while a pitiful number understand answer (c). This is a serious weakness in a candidate, since they obviously do not understand the importance and benefits of localizing the scope of both data and code.

Const

7. What does the keyword const mean?

As soon as the interviewee says 'const means constant', I know I'm dealing with an amateur. Dan Saks has exhaustively covered const in the last year, such that every reader of ESP should be extremely familiar with what const can and cannot do for you. If you haven't been reading that column, suffice it to say that const means 'read-only'. Although this answer doesn't really do the subject justice, I'd accept it as a correct answer. (If you want the detailed answer, then read Saks' columns ' carefully!).

If the candidate gets the answer correct, then I'll ask him these supplemental questions:

What do the following incomplete [2] declarations mean?

The first two mean the same thing, namely a is a const (read-only) integer. The third means a is a pointer to a const integer (i.e., the integer isn't modifiable, but the pointer is). The fourth declares a to be a const pointer to an integer (i.e., the integer pointed to by a is modifiable, but the pointer is not). The final declaration declares a to be a const pointer to a const integer (i.e., neither the integer pointed to by a, nor the pointer itself may be modified).

If the candidate correctly answers these questions, I'll be impressed.

Incidentally, one might wonder why I put so much emphasis on const, since it is very easy to write a correctly functioning program without ever using it. There are several reasons:

(a) The use of const conveys some very useful information to someone reading your code. In effect, declaring a parameter const tells the user about its intended usage. If you spend a lot of time cleaning up the mess left by other people, then you'll quickly learn to appreciate this extra piece of information. (Of course, programmers that use const, rarely leave a mess for others to clean up')

(b) const has the potential for generating tighter code by giving the optimizer some additional information.

(c) Code that uses const liberally is inherently protected by the compiler against inadvertent coding constructs that result in parameters being changed that should not be. In short, they tend to have fewer bugs.

Volatile

8. What does the keyword volatile mean? Give three different examples of its use.

A volatile variable is one that can change unexpectedly. Consequently, the compiler can make no assumptions about the value of the variable. In particular, the optimizer must be careful to reload the variable every time it is used instead of holding a copy in a register. Examples of volatile variables are:

(a) Hardware registers in peripherals (e.g., status registers)

(b) Non-stack variables referenced within an interrupt service routine.

(c) Variables shared by multiple tasks in a multi-threaded application.

If a candidate does not know the answer to this question, they aren't hired. I consider this the most fundamental question that distinguishes between a 'C programmer' and an 'embedded systems programmer'. Embedded folks deal with hardware, interrupts, RTOSes, and the like. All of these require volatile variables. Failure to understand the concept of volatile will lead to disaster.

On the (dubious) assumption that the interviewee gets this question correct, I like to probe a little deeper, to see if they really understand the full significance of volatile. In particular, I'll ask them the following:

(a) Can a parameter be both const and volatile? Explain your answer.

(b) Can a pointer be volatile? Explain your answer.

(c) What is wrong with the following function?:

The answers are as follows:

(a) Yes. An example is a read only status register. It is volatile because it can change unexpectedly. It is const because the program should not attempt to modify it.

(b) Yes. Although this is not very common. An example is when an interrupt service routine modifies a pointer to a buffer.

(c) This one is wicked. The intent of the code is to return the square of the value pointed to by *ptr. However, since *ptr points to a volatile parameter, the compiler will generate code that looks something like this:

Since it is possible for the value of *ptr to change unexpectedly, it is possible for a and b to be different. Consequently, this code could return a number that is not a square! The correct way to code this is:

Bit Manipulation

9. Embedded systems always require the user to manipulate bits in registers or variables. Given an integer variable a, write two code fragments. The first should set bit 3 of a. The second should clear bit 3 of a. In both cases, the remaining bits should be unmodified.

These are the three basic responses to this question:

(a) No idea. The interviewee cannot have done any embedded systems work.

(b) Use bit fields. Bit fields are right up there with trigraphs as the most brain-dead portion of C. Bit fields are inherently non-portable across compilers, and as such guarantee that your code is not reusable. I recently had the misfortune to look at a driver written by Infineon for one of their more complex communications chip. It used bit fields, and was completely useless because my compiler implemented the bit fields the other way around. The moral ' never let a non-embedded person anywhere near a real piece of hardware! [3]

(c) Use #defines and bit masks. This is a highly portable method, and is the one that should be used. My optimal solution to this problem would be:

Some people prefer to define a mask, together with manifest constants for the set & clear values. This is also acceptable. The important elements that I'm looking for are the use of manifest constants, together with the |= and &= ~ constructs.

Additional reading:
Unlock Efficiency: 8-Port UHF RFID Module for All Industries

RoyalRay Product Page

Accessing fixed memory locations

10. Embedded systems are often characterized by requiring the programmer to access a specific memory location. On a certain project it is required to set an integer variable at the absolute address 0x67a9 to the value 0xaa55. The compiler is a pure ANSI compiler. Write code to accomplish this task.

This problem tests whether you know that it is legal to typecast an integer to a pointer in order to access an absolute location. The exact syntax varies depending upon one's style. However, I would typically be looking for something like this:

A more obfuscated approach is:

*(int * const)(0x67a9) = 0xaa55;

Even if your taste runs more to the second solution, I suggest the first solution when you are in an interview situation.

Interrupts

11. Interrupts are an important part of embedded systems. Consequently, many compiler vendors offer an extension to standard C to support interrupts. Typically, this new key word is __interrupt. The following code uses __interrupt to define an interrupt service routine. Comment on the code.

This function has so much wrong with it, it's almost tough to know where to start.

(a) Interrupt service routines cannot return a value. If you don't understand this, then you aren't hired.

(b) ISR's cannot be passed parameters. See item (a) for your employment prospects if you missed this.

(c) On many processors / compilers, floating point operations are not necessarily re-entrant. In some cases one needs to stack additional registers, in other cases, one simply cannot do floating point in an ISR. Furthermore, given that a general rule of thumb is that ISRs should be short and sweet, one wonders about the wisdom of doing floating point math here.

(d) In a similar vein to point (c), printf() often has problems with reentrancy and performance. If you missed points (c) & (d) then I wouldn't be too hard on you. Needless to say, if you got these two points, then your employment prospects are looking better and better.

Code Examples

12. What does the following code output and why?

This question tests whether you understand the integer promotion rules in C ' an area that I find is very poorly understood by many developers. Anyway, the answer is that this outputs '> 6'. The reason for this is that expressions involving signed and unsigned types have all operands promoted to unsigned types. Thus '20 becomes a very large positive integer and the expression evaluates to greater than 6. This is a very important point in embedded systems where unsigned data types should be used frequently (see reference 2). If you get this one wrong, then you are perilously close to not being hired.

13. Comment on the following code fragment?

On machines where an int is not 16 bits, this will be incorrect. It should be coded:

unsigned int compzero = ~0;

This question really gets to whether the candidate understands the importance of word length on a computer. In my experience, good embedded programmers are critically aware of the underlying hardware and its limitations, whereas computer programmers tend to dismiss the hardware as a necessary annoyance.

By this stage, candidates are either completely demoralized ' or they are on a roll and having a good time. If it is obvious that the candidate isn't very good, then the test is terminated at this point. However, if the candidate is doing well, then I throw in these supplemental questions. These questions are hard, and I expect that only the very best candidates will do well on them. In posing these questions, I'm looking more at the way the candidate tackles the problems, rather than the answers. Anyway, have fun'

Dynamic Memory Allocation

14. Although not as common as in non-embedded computers, embedded systems still do dynamically allocate memory from the heap. What are the problems with dynamic memory allocation in embedded systems?

Here, I expect the user to mention memory fragmentation, problems with garbage collection, variable execution time, etc. This topic has been covered extensively in ESP, mainly by Plauger. His explanations are far more insightful than anything I could offer here, so go and read those back issues! Having lulled the candidate into a sense of false security, I then offer up this tidbit:

What does the following code fragment output and why?

This is a fun question. I stumbled across this only recently, when a colleague of mine inadvertently passed a value of 0 to malloc, and got back a valid pointer! After doing some digging, I discovered that the result of malloc(0) is implementation defined, so that the correct answer is 'it depends'. I use this to start a discussion on what the interviewee thinks is the correct thing for malloc to do. Getting the right answer here is nowhere near as important as the way you approach the problem and the rationale for your decision.

Typedef

15. Typedef is frequently used in C to declare synonyms for pre-existing data types. It is also possible to use the preprocessor to do something similar. For instance, consider the following code fragment:

The intent in both cases is to define dPS and tPS to be pointers to structure s. Which method (if any) is preferred and why?

This is a very subtle question, and anyone that gets it right (for the right reason) is to be congratulated or condemned ('get a life' springs to mind). The answer is the typedef is preferred. Consider the declarations:

The first expands to

struct s * p1, p2;

which defines p1 to be a pointer to the structure and p2 to be an actual structure, which is probably not what you wanted. The second example correctly defines p3 & p4 to be pointers.

Obfuscated syntax

16. C allows some appalling constructs. Is this construct legal, and if so what does this code do?

This question is intended to be a lighthearted end to the quiz, as, believe it or not, this is perfectly legal syntax. The question is how does the compiler treat it? Those poor compiler writers actually debated this issue, and came up with the 'maximum munch' rule, which stipulates that the compiler should bite off as big a (legal) chunk as it can. Hence, this code is treated as:

c = a++ + b;

Thus, after this code is executed, a = 6, b = 7 & c = 12;

If you knew the answer, or guessed correctly ' then well done. If you didn't know the answer then I would not consider this to be a problem. I find the biggest benefit of this question is that it is very good for stimulating questions on coding styles, the value of code reviews and the benefits of using lint.

Well folks, there you have it. That was my version of the C test. I hope you had as much fun doing it as I had writing it. If you think the test is a good test, then by all means use it in your recruitment. Who knows, I may get lucky in a year or two and end up being on the receiving end of my own work.

References:

  1. In Praise of the #error directive. ESP September .
  2. Efficient C Code for Eight-Bit MCUs. ESP November .

[1] Translation unit for the pedagogues out there.

[2] I've had complaints that these code fragments are incorrect syntax. This is correct. However, writing down syntactically correct code pretty much gives the game away.

[3] I've recently softened my stance on bit fields. At least one compiler vendor (IAR) now offers a compiler switch for specifying the bit field ordering. Furthermore the compiler generates optimal code with bit field defined registers ' and as such I now do use bit fields in IAR applications.

Frequently Asked Questions - Embedded Systems Design

Created by Scott Schmit, last modified by Robert Nelson on Feb 05,

The purpose of this page is to address some commonly asked questions regarding embedded systems design. Some of the presented questions are broad or conceptual in nature. Others are more narrow in focus and may pertain to a single peripheral within a microcontroller. After you have browsed through the various topics, please take a moment to visit the various spaces within the eewiki. You will find some hands-on examples incorporating the topics discussed below.

What is an Embedded System?

An embedded system is comprised of hardware and software with a dedicated function and is part of a larger system. Normally it includes one or more microprocessors or microcontrollers which supervise system functions. An embedded system incorporates some sort of software that automatically boots on power-up. Many times, the software will run autonomously. However, it is not uncommon for an embedded system to include some sort of user interface for external control and monitoring (buttons, switches, LEDs, LCDs, etc).

What is a Microprocessor?

A microprocessor performs all functions of a Central Processing Unit and is manufactured into a small integrated circuit. It interprets and executes program instructions and can be thought of as 'the brain' of an embedded system. It includes digital logic that executes instructions in a specific order. A master clock is used to continue executing instructions in sequential order. It's not uncommon for the master clock to be divided internally into individual clock signals that trigger specialized hardware sections.

What is a Microcontroller?

A microcontroller integrates a CPU with memory and hardware peripheral circuitry that serve specific purposes.

For memory, a microcontroller includes some sort of non-volatile programmable memory that becomes Read-Only at run-time. This memory is where the user would program application code which executes instructions in a specific order to achieve the system's overall purpose. A microcontroller usually has volatile Random Access Memory that can be used at run-time for manipulating variables and storing results. Sometimes a microcontroller will include extra non-volatile memory for storing information while powered-down.

The dedicated hardware peripherals will vary depending on the microcontroller. Some common hardware peripherals include timers, serial communication blocks, analog to digital converters, digital to analog converters, analog comparators, and general purpose input and output pins.

What is the difference between parallel and serial communication?

When two devices communicate with each other, it means they are exchanging data. The system architecture will define the number of bits each data word is made up of, but 8, 16, and 32-bit data words are probably the most common. Parallel communication uses a dedicated wire for each bit in the data word. Serial communication on the other hand, shifts all bits onto a single data line in some predefined order. Typically, serial communication will use a single data line and shift each bit in sequential order, either most significant bit (msb) or least significant bit (lsb) first. However, some serial protocols will rearrange the bits in non-sequential order to mitigate electrical effects (DC offset, EMI, etc.) on the rest of the board.

The major benefit of using Parallel communication is that it takes less clock cycles to transmit the same amount of data as serial communication would. For example, if 8 individual lines were used to transmit an 8-bit data word, the entire data word would be transmitted in a single clock cycle. Compare that to a serial communication protocol that uses a single data line. It would take 8 clock cycles to transmit the same data word.

The major benefit of using Serial communication is that it takes far less pins on a device and less board space for running trace wires. This allows the pins to be used for other purposes, and generally reduces the required board space and/or cable size.

Hybrid communication protocols also exist which make use of the advantages of each. For example, dual and quad I/O SPI protocols use more than one serial data pin to increase overall bandwidth. Ultimately, it's up to the designer to understand the tradeoffs and determine what is required/acceptable for a specific application.

What is the difference between synchronous and asynchronous communication?

Synchronous communication means that the two (or more) devices exchanging data share a common clock line. One device (typically referred to as the Master) will drive the clock signal as an output, while the other device (typically referred to as the Slave) will read the clock signal as an input. As the name suggests, this keeps the devices synchronized and ensures data is setup and sampled at the correct times. The major benefit of synchronous communication is that it is reliable. You don't need to worry about setting up accurate reference clocks on each device to achieve the appropriate baud rate and temperature has little or no effect on data reliability. The down side is that it takes an extra pin, and generally increases the required board space/cable size. Running a clock signal on a board can also increase EMI effects.

Asynchronous communication means that the two devices do not share a dedicated clock signal'a unique clock exists on each device. Each device must setup ahead of time a matching bit rate and how many bits to expect in a given transaction. Asynchronous communication is nice because it takes one less pin, which saves board space/cable size, and allows the designer to use that pin for other purposes. Removing a clock line from a board also helps reduce EMI. The downside to using asynchronous communication is that it is more difficult to achieve reliable communication. The reference clocks used for generating the bit rate must be fairly accurate and stable over temperature or timing could get thrown off. Integer drop-off can also introduce error in the baud rate. This occurs when you try and achieve a baud rate that is not an exact integer multiple of the reference clock. In other words, even with a perfect reference clock, the desired baud rate may not be achievable without a certain amount of error. The amount of error may or may not be acceptable.

What is I2C?

The Inter-Integrated Circuit (I2C) protocol is a very popular synchronous serial communication protocol in embedded designs due to the low number of pins required and the large number of devices that can be connected to a single bus. A single data line (SDA) and a single clock line (SCL) plus common ground are the only required connections between an I2C master and slave. The following figure (taken from the I2C wikipedia page) shows a simplified timing diagram for I2C transactions. The first yellow box indicates a START signal. A START condition is the only time the SDA line will transition low while the clock line is high. During the transcaction, SDA transitions are made while SCL is low (blue) and SDA is sampled while SCL is high (green). The second yellow box indicates a STOP signal. A STOP condition is the only time the SDA line will transition high while the clock line is high. Open-drain outputs with external pull-up resistors are used for the data and clock lines. Once a device stops actively driving the bus lines, the external resistors pull each line high.


I2C Timing Example

I2C is an address-based protocol, meaning each slave device has a unique I2C address. I2C supports multiple masters and multiple slaves on a single bus. A device's datasheet will specify its I2C slave address. Typically, a device will use a 7-bit I2C slave address, although some variations to the I2C protocol also support 10 and 16-bit addressing modes. A typical I2C transaction would begin with a master issuing a START signal, followed by a single byte consisting of the slave's 7-bit address and a single read/write bit. After the slave address byte, the message format varies a bit from device to device. There is no limit to the number of bytes that can be transmitted in a single transaction. However, each byte must be acknowledged by the receiving device before the next byte is sent. After the last byte and acknowledge is received, the master will end the transaction by issuing a STOP signal. For devices that support larger addressing schemes, the initial byte format may also change. The specific device's datasheet will describe the required I2C message format. 100kbps is the standard I2C data rate while more recent I2C variations support 400kbps fast mode , 1Mbps fast mode plus , and 3.4Mbps high speed mode .

What is SPI?

The Serial Peripheral Interface (SPI) protocol is another popular synchronous serial communication protocol in embedded designs. SPI communication involves one or more master devices and one or more slave devices using a shared bus. Full duplex or 4-wire SPI uses two data lines, a shared clock line, and a slave select line. Half duplex or 3-wire SPI uses a shared data line.

Pin Descriptions

  • MISO: Master In, Slave Out - Data is shifted out from the slave and into the master on this line.
  • MOSI: Master Out, Slave In - Data is shifted out from the master and into the slave on this line.
  • SCLK: Clock - The clock is always driven by the master. The clock starts as soon as data is loaded into the master's transmitter and stops when the last bit is shifted out.
  • SS: Slave Select - A dedicated slave select (or chip select) line is used to address different slave devices. A slave will only receive data if its SS pin is asserted (active low).

SPI Timing

The following figure was taken from an Atmel Xmega-A3U manual. It illustrates the 4 SPI modes of operation. The 4 modes are similar for all SPI devices.

  • Mode 0: SCLK idles low. Data is setup on falling edge of SCLK. Data is sampled on rising edge of SCLK.
  • Mode 1: SCLK idles low. Data is setup on rising edge of SCLK. Data is sampled on falling edge of SCLK.
  • Mode 2: SCLK idles high. Data is setup on rising edge of SCLK. Data is sampled on falling edge of SCLK.
  • Mode 3: SCLK idles high. Data is setup on falling edge of SCLK. Data is sampled on rising edge of SCLK.

General Operation

The master always initiates transmission. The slave simply has to wait for its SS line to be asserted and the SCLK to appear, or prompt the master using other I/O. When SCLK activates, data will simultaneously start shifting out on the MOSI line and in on the MISO line. Data gets shifted in/out one bit at a time until every bit has been shifted. Usually a microcontroller will have a built in SPI register that sets a flag when all data bits have been shifted out.

Pros:

  • Low overhead - SPI protocol uses dedicated slave select lines for each slave device. This eliminates the need for sending addresses over the data lines and decreases overhead.
  • Reliable - The dedicated clock line eliminates baud mismatches that are common in asynchronous protocols (like UART).
  • Fast - Dual data lines increase the overall throughput and the low overhead increases overall bps.
  • Shared bus - The dedicated slave select lines allow multiple devices to share the same data/clock lines. If the device's SS line is not enabled, the device will simply ignore data.

Cons:

  • High pin count - Compared to other common serial communication protocols, SPI uses quite a few pins. An extra pin (SS) is required for every slave device and master device for multi-master setups.
  • Error checking - No default CRC checking or bus contention indication
  • Transmission Initiation - The master must initiate all transmissions. If a slave has data to send to the master, it must wait for the master to start transmission, or use external signals to interrupt the master.

What is a UART?

A Universal Asynchronous Receiver/Transmitter (UART) is a very simple method of serial communication in embedded designs. UART communication in full-duplex mode uses one pin for Transmit (TX) and one pin for Receive (RX). Half-duplex uses a shared pin for TX and RX (commonly referred to as single-wire UART or 1-wire Comm). Both versions require a common ground to operate properly since TX and RX are single-ended signals.

Since there is no shared clock line, the data rate and frame format need to be setup on both ends of the communication link ahead of time. 7, 8, and 9-bit data frames are common lengths with 8-bit being the most prevalent. The data lines will idle high between transmissions. There is no master-slave relationship in the UART protocol, therefore either device can initiate transmission. This is accomplished by driving the transmit pin low for one bit-period (considered a START signal). The specified number of data bits will follow, typically transmitted least-significant-bit first. An optional parity bit can be used for basic error checking. The parity bit is used to make the 'sum' of the data bits even or odd and gets transmitted along with the data. The receiver will recalculate the sum of the data bits and parity bit and compare to the expected parity as a simple check for data integrity. The frame is ended by driving the line high for the specified number of bit periods (STOP bits). The receiver on each end uses oversampling to read each bit of incoming data. The oversampling rate is dependent on the desired baud rate being used.

The following image was taken from an Atmel ATmega256RFR2 datasheet (Sec 23.4). It shows the frame format for UART communication.

Separate flow control signals Clear-To-Send (CTS) and Request-To-Send (RTS) are sometimes utilized to provide more efficient transactions between devices that operate at different speeds. This is especially common when mixing electrical systems with mechanical systems (for example a desktop printer). The electrical signal takes very little time to complete. However, the mechanical motion of a motor or solenoid will take much longer to complete a process. The two devices would most likely use CTS and RTS signals in a handshaking method to make sure data is transmitted at the proper times.

What is a USART?

A Universal Synchronous/Asynchronous Receiver/Transmitter (USART) is a dedicated hardware peripheral found in some microcontrollers. The USART peripheral gives the user the option of using synchronous or asynchronous communication. It can be used as a UART as described above utilizing only data lines, or it can be used in synchronous mode which will add the clock line. Synchronous mode will generally allow for burst transactions (sending multiple bytes in a single transaction) whereas asynchronous mode generally sends a single byte at a time. Most microcontrollers that contain a USART will allow the user to implement the SPI protocol on it (in synchronous mode). However, it should be noted that most microcontrollers that support USART SPI mode typically don't support SPI slave mode on the USART, only SPI master mode. Basically, a USART gives you the ability to implement UART or SPI without restricting you to one or the other.

What is an ADC?

An Analog to Digital Converter (ADC) is one of the most common peripherals found in microcontrollers. An ADC converts a continuous analog voltage, at a single point in time, to a digital value that can be interpreted by a digital device, such as a microcontroller. The designer decides how frequently to sample the analog signal. However, every ADC has a maximum sampling rate that cannot be exceeded.

The resolution is another important ADC spec. The resolution defines the number of bits used to describe the analog signal at a given point in time. 8, 10, and 12-bit are typical ADC resolutions available in inexpensive microcontrollers. Some special purpose ADC's even go as high as 32-bits of resolution. The more resolution you have, the finer you can define an analog signal. For example, an ADC with 10-bits of resolution will allow for 2^10 or possible digital values that can be used to describe the analog signal. A 16-bit ADC on the other hand will allow for 2^16 or 65,536 individual digital values that can be used to represent the analog signal.

The analog input range of the ADC is another important thing to consider. For single-ended measurements (measurements taken with reference to ground), the analog input range is generally from 0V up to the defined reference voltage. Normally, the designer has options when it comes to selecting a reference voltage. Differential measurements sample two different analog signals and take the difference between the two. This is useful in eliminating external noise that is present on both signals, known as common-mode noise.

What is a DAC?

A Digital to Analog Converter (DAC) converts a digital signal to a continuous analog signal. DAC's are typically used in audio applications to drive a speaker or amplifier. Similar to an ADC, a DAC will have a maximum operating speed that cannot be exceeded. A DAC will also have a fixed resolution as an ADC does. A higher resolution will allow for finer control over the analog output.

A DAC will take a digital input and create a single pulse up to the specified analog value. As you input a stream of digital values to the DAC, you will get subsequent pulses of analog output. The spaces between the output pulses will be interpolated by a filter to achieve a continuous signal. As previously stated, DACs are typically used in audio applications. Therefore, the digital inputs are usually applied at constant time intervals and the analog output is updated accordingly.

What is Pulse Width Modulation?

Pulse-Width-Modulation (PWM) is a method of controlling a voltage or current by varying the signal between fully ON and fully OFF and precisely controlling the amount of time spent in each state. The pulse train is switched at a constant frequency and the average value of the signal is directly proportional to the ratio of ON/OFF time. This ON/OFF time ratio is known as duty cycle. Duty cycle allows us to think in terms of percentage rather than individual units of time. Let's take a look at a simple example.

The following image shows a PWM signal with 50% duty cycle, meaning the signal is ON 50% of the time and OFF 50% of the time. If the signal is being switched between 0 and 5V for example, the average value of the following PWM signal would be 2.5V.

In this next image, the duty cycle is increased to 75%, meaning the signal is ON 75% of the time and OFF 25% of the time. This increases the voltage from 2.5V to 3.75V (75% of 5V).

It should be noted that the period (frequency) of the PWM signal remains constant. You can see in both images that the black lines are evenly spaced and that the falling edge of the signal always occurs at a defined time. The rising edge, and hence the pulse width, is what we are adjusting to precisely control the average value. The required switching frequency will be application specific.

PWM is used extensively in embedded designs. Motor control, LED intensity control, and DC/DC power conversion are all typical applications for Pulse Width Modulation.

What is DMA?

Direct Memory Access (DMA) allows a device, such as a microcontroller to perform certain tasks without using the CPU. The DMA controller can supervise tasks and transfer data between different areas of memory. This allows the CPU to perform other tasks while waiting for slower functions to complete. This increases throughput and overall program execution efficiency.

Are you interested in learning more about embedded module? Contact us today to secure an expert consultation!

Questions/Comments

Comments

0 of 2000 characters used

All Comments (0)
Get in Touch

  |   Transportation   |   Toys & Hobbies   |   Tools   |   Timepieces, Jewelry, Eyewear   |   Textiles & Leather Products   |   Telecommunications   |   Sports & Entertainment   |   Shoes & Accessories   |   Service Equipment