3. SINA PROG. INTERFACING. 1. LCD,KEYPAD. 2. ADC,I2C,SERIAL,PWM. ATMEGA DEVELOPMENT BOARD. Programming With AVR. Microcontroller. programming book or an electronics text (or just look it up on the Net). But when .. If your PDF reader supports indexing, enable the in-. I highly recommend that you get the book, 'The C Programming Language – based on the AVR microcontroller, and the examples are as microcontroller.
|Language:||English, Spanish, Japanese|
|Genre:||Politics & Laws|
|PDF File Size:||17.55 MB|
|Distribution:||Free* [*Regsitration Required]|
The AVR1 family of MCUs from Atmel Corporation has become one of the most Since this is not primarily a book about programming, we will only be going on Unix or the AVRDude user manual (supplied with AVRDude as a PDF file on. This book is not a C language Programming Book or a Book to learn AVR Studio provides a project management tool, source file editor and chip simulator. Atmel AVR Microcontroller Primer: Programming and Interfacing. Pages · · MB · 1, The AVR Microcontroller and Embedded System by Muhammad Ali Mazidi Pdfdrive:hope Give books away. Get books you want.
At the receiving end, it is difficult to discern a logic high from a logic low. The RS standard has been around for some time.
Chips are commonly available e. The RS standard also specifies other features for this communication protocol. Parity is an additional bit or bits that may be transmitted with the data byte. The ATmega16 uses a single parity bit.
With a single parity bit, a single-bit error may be detected. Parity may be even or odd. At the receiver, the number of bits within a data byte including the parity bit are counted to ensure that parity has not changed, indicating an error, during transmission. It has been in use for many decades, so some of the characters and actions listed in the ASCII table are not in common use today.
It provides standardized bit encoding format for the written languages of the world. The interested reader is referred to the Unicode home page website at www. This is accomplished by equipping the ATmega16 with independent hardware for the transmitter and receiver.
It has the capability to be set to a variety of data transmission or baud bits per second rates. Because of space limitations, we cover only the most basic capability of this flexible and powerful serial communication system. The block diagram may appear a bit overwhelming, but realize there are four basic pieces to the diagram: We discuss each in turn. L] and several additional dividers to set the baud rate.
Solving for UBRR yields. The start and stop framing bits are automatically appended to the data within the Transmit Shift Register. The parity is automatically calculated and appended to the Transmit Shift Register.
Data are then shifted out of the Transmit Shift Register via the TxD pin a single bit at a time at the established baud rate. The UDRE flag sets when the transmit buffer is empty, indicating it is ready to receive new data. The TXC flag bit is set to logic 1 when the entire frame in the Transmit Shift Register has been shifted out and there are no new data currently present in the transmit buffer. The TXC bit may be reset by writing a logic 1 to it.
Data are received a single bit at a time via the RxD pin at the established baud rate. The RXC flag is logic 1 when unread data exist in the receive buffer. The function of these bits has already been discussed. This allows the user to customize the data features to the application at hand.
It should be emphasized that both the transmitter and receiver be configured with the same data features for proper data transmission. These activities are summarized in Figure 2.
Both the transmitter and receiver must be initialized with the same communication parameters for proper data transmission. The transmission and reception activities are similar except for the direction of data flow. In transmission, we monitor for the UDRE flag to set, indicating the data register is empty. We then load the data for transmission into the UDR register. We then retrieve the data from the UDR register. USART activities. In the sample code provided, we assume the ATmega16 is operating at 10 MHz and we desire a baud rate of , asynchronous operation, no parity, one stop bit, and eight data bits.
To achieve baud with an operating frequency of 10 MHz requires that we set the UBRR registers to 64, which is 0x The SPI system allows for fast and efficient data exchange between microcontrollers or peripheral devices.
There are many SPI-compatible external systems available to extend the features of the microcontroller. The SPI may be viewed as a synchronous bit shift register with an 8-bit half residing in the transmitter and the other 8-bit half residing in the receiver as shown in Figure 2. A slave is chosen for reception by taking its slave select SS line low. Master Device Slave Device. SCK pulse. The data are received at the MOSI pin of the slave designated device.
After eight master SCK clock pulses, a byte of data has been exchanged between the master and slave designated SPI devices. At that time, another data byte may be transmitted. The registers for the SPI system are provided in Figure 2. We will discuss each one in turn. SPI Control Register. It also provides the flexibility for the SPI to be connected to a wide variety of devices with different data formats.
It is important that both the SPI master and slave devices be configured for compatible data formats for proper data transmission. The SPCR contains the following bits:. A logic 1 turns the system on and logic 0 turns it off.
SPI Status Register. This contains the SPIF. The flag sets when eight data bits have been transferred from the master to the slave. SPI Data Register. To program the SPI system, the system must first be initialized with the desired data format.
Data transmission may then commence. Functions for initialization, transmission, and reception are provided below. In this specific example, we divide the clock oscillator frequency by to set the SCK clock frequency. Space does not permit a detailed discussion of this advanced serial communication system.
Summarize the differences between parallel and serial conversion. Draw the schematic of a system consisting of two ATmega16 that will exchange data via the SPI system. The system should include RS level shifting.
Write the code to implement the system described in the question above. A microcontroller is used to process information from the natural world, decide on a course of action based on the information collected, and then issue control signals to implement the decision. Because much of the information from the natural world is analog or continuous in nature and the microcontroller is a digital or discrete-based processor, a method to convert an analog signal to digital is required .
We will discuss both types of converters in this chapter. In the first section, we present the fundamental concepts associated with the ADC process. In the following section, we discuss the conversion process itself, followed by a presentation of different hardware implementations of the process.
Much of these early sections contain the same material you will find in our text, Microcontroller Fundamentals for Engineers and Scientists. We conclude our discussion of the ADC with several illustrative code examples. We conclude the chapter with a discussion of the DAC process. We start with some definitions on analog and digital signals.
The collection can be as small as only one value or can have as many values as you wish. In engineering, we usually arrange the values in order, for example, over time or over a spatial axis, to display the information. The time and spatial variables are called independent variables, because they are not affected by the physical variables of interests.
For example, we measure the temperature change over time. The temperature measured is dependent on the time, not the other way around. Figure 3. The signal shows how the altitude of the bird changes continuously. The image captured the light intensities of the scene using a charge-coupled device camera. If we move from the left to the right on the image and observe the intensity changes, we can find vertical edges by detecting signal.
Altitude trajectory generated by a flying bird.
The same analysis can be performed as we move from the top to the bottom of the image. Analog signals are those whose physical variable values change continuously over their independent variable.
Most physical variables, your speech, movement of stars, and the music you hear at a concert are analog signals, signals that we find all around us. Digital signals, on the other hand, have their physical variables defined only for discrete instances over their independent variables. Although it may look continuous to human eyes, the photo example shown in Figure 3. The image is only a finite composition of intensity values seen by a discrete number of pixels.
Digital signals are important because all signals represented in digital systems, computers, and microcontrollers are in digital forms. For example, human voices must be converted to corresponding digital signals before they can be routed by digital switching circuits in telephone communication systems. Similarly, voice commands to robots must be converted to a digital form before robots can understand the command.
As shown in the examples above, we live in an analog world; that is, physical variables are analog signals. It is precisely this reason why the ADC is so very important in any digital systems that interact with an analog environment. We first start with the subject of sampling. Imagine yourself as a photographer in an Olympic diving stadium.
Your job is taking a sequence of pictures of divers jumping off from a diving board 10 meters above the surface of the diving pool. Your goal is to put the sequence of pictures together to reconstruct the motion of each diver. If a diver tries a complex motion and you want to faithfully reconstruct his motion, you must take enough pictures from the start to the end of the dive. If a diver makes a simple routine dive, you only need to take a few pictures over the period of the dive.
Two very different cases of motions generated by a diver is shown in Figure 3. The same time sequence is used to capture samples for both motions. As can be seen from figure, frame a motion cannot be regenerated from the samples, whereas the motion shown in frame b can clearly be reconstructed from the same number of samples used to capture both motions. Naturally, when we sample a signal, we want to sample it in an optimal fashion such that we can capture the essence of the signal while minimizing the use of resources.
In essence, we want to minimize the number of samples while faithfully reconstructing the original signal from the samples. As can be deduced from our discussion above, the rate of change in a signal determines the number of samples required to faithfully reconstruct the signal, provided that all adjacent samples are captured with the same sample timing intervals.
Harry Nyquist from Bell Laboratory studied the sampling process and derived a criterion that determines the minimum sampling rate for any continuous analog signals. His, now famous, minimum sampling rate is known as the Nyquist sampling rate, which states that one must sample a signal at least twice as fast as the highest frequency content of the signal of interest. Engineers who work for telephone companies must deal with such issues.
Sampling is important because when we want to represent an analog signal in a digital system, such as a computer, we must use the appropriate sampling rate to capture the analog signal for a faithful representation in digital systems. Now that we understand the sampling process, let us move on to the second process of the ADC, quantization. Each digital system has a number of bits, which it uses as the basic units to represent data.
A bit is the most basic unit where single binary information, 1 or 0, is represented. A nibble is made up of 4 bits put together. A byte is 8 bits. In the previous section, we tacitly avoided the discussion of the form of captured signal samples.
The quantization of a sampled signal is how the signal is represented as one of quantization level. Suppose you have a single bit to represent an incoming signal.
You only have two different numbers, 0 and 1. You may say that you can distinguish only low from high. Suppose you have 2 bits. You can represent four different levels, 00, 01, 10, and What if you have 3 bits? You now can represent eight different levels: Think of it as follows. When you had 2 bits, you were able to represent four different levels. If we add one more bit, that bit can be 1 or 0, making the total possibilities 8.
Similar discussion can lead us to conclude that given n bits, we have 2n different numbers or levels one can represent. In many digital systems, the incoming signals are voltage signals.
The voltage signals are first obtained from physical signals with the help of transducers, such as microphones, angle sensors, and infrared sensors. The voltage signals are then conditioned to map their range with the input range of a digital system, typically 0 to 5 V. In Figure 3. As can be seen from the figure, higher quantization levels means better mapping of an incoming signal to its true value.
If we only had a single bit, we can only represent levels 0 and 1. Any analog signal value in between the range had to be mapped either as level 0 or level 1, not many choices. Now imagine what happens as we increase the number of bits available for the quantization levels. What happens when the available number of bits is 8? How many different quantization levels are available now? Yes, How about 10, 12, or 14? Finally, the encoding process involves converting a quantized signal into a digital binary number.
Suppose again we are using 8 bits to quantize a sampled analog signal. The quantization levels are determined by the 8 bits, and each sampled signal is quantized as one of quantization levels. Consider the two sampled signals shown in Figure 3. The first sample is mapped to quantization level 2 and the second one is mapped to quantization level Note the amount. Quantization with fewer bits.
Now consider Figure 3. The same signal is sampled at the same time but quantized using a less number of bits. Note that the quantization error is inversely proportional to the number of bits used to quantize the signal. Once a sampled signal is quantized, the encoding process involves representing the quanti- zation level with the available bits. Thus, for the first sample, the encoded sampled value is , whereas the encoded sampled value for the second sample is As a result of the encoding process, sampled analog signals are now represented as a set of binary numbers.
Thus, the encoding is the last necessary step to represent a sampled analog signal into its corresponding digital form, shown in Figure 3. Suppose again we have. The resolution in this case is 2. You can imagine how your TV screen will look if you only had only two levels to represent each pixel, black and white.
The maximum error, called the resolution error, is 2. Suppose you now have 4 bits to represent quantization levels. The resolution now becomes 1. Suppose you have 20 bits for quantization levels. The resolution now becomes 4.
The discussion we presented simply illustrates that as we increase the available number of quantization levels within a range, the distance between adjacent levels decreases, reducing the quantization error of a sampled signal. As the number grows, the error decreases, making the representation of a sampled analog signal more accurate in the corresponding digital form.
The number of bits used for the quantization is directly proportional to the resolution of a system. You now should understand the technical background when you watch high-definition television broadcasting. Now let us move onto the discussion of the data rate. The definition of the data rate is the amount of data generated by a system per some time unit. Typically, the number of bits or the number of bytes per second is used as the data rate of a system. We just saw that the more bits we use for the quantization levels, the more accurate we can represent a sampled analog signal.
Why not use the maximum number of bits current technologies can offer for all digital systems, when we convert analog signals to digital counterparts? It has to do with the cost involved. In particular, suppose you are working for a telephone company and your switching system must accommodate , customers.
For each individual phone conversation, suppose the company uses an 8-kHz sampling rate and you are using 10 bits for the quantization levels for each sampled signal.
You will need some major computing power to meet the requirement. For such reasons, when designers make decisions on the number of bits used for the quantization levels, they must consider the computational burden the selection will produce on the computational capabilities of a digital system versus the required system resolution.
You will also encounter the term dynamic range when you consider finding appropriate ADCs. The dynamic range is a measure used to describe the signal to noise ratio. The unit used for the measurement is decibel, which is the strength of a signal with respect to a reference signal. The greater the decibel number, the stronger the signal is compared with a noise signal.
The definition of the dynamic range is 20 log 2b , where b is the number of bits used to convert analog signals. Typically, you will find 8 to 12 bits used in commercial ADCs, translating the dynamic range from 20 log 28 dB to 20 log dB Oppenheim and Schafer .
Toward this end, three signal processing procedures, sampling, quantization, and encoding, described in the previous section must be combined together. Before the ADC process takes place, we first need to convert a physical signal into an electrical signal with the help of a transducer. Depending on the purpose, we categorize a transducer as an input transducer or an output transducer. If the conversion is from physical to electrical, we call it an input transducer.
The mouse, the keyboard, and the microphone for your PC all fall under this category. A camera, an infrared sensor, and a temperature sensor are also input transducers. The output transducer converts electrical signals to physical signals. The computer screen and the printer for your computer are output transducers. Speakers and electrical motors are also output transducers.
Therefore, transducers play the central part for digital systems to operate in our physical world by transforming physical signals to and from electrical signals. In addition to transducers, we also need signal conditioning circuitry before we apply the ADC process or its opposite process of DAC process. The signal conditioning circuitry is called the transducer interface. The objective of the transducer interface circuit is to scale and shift the electrical signal range to map the output of the input transducer to the input of the ADC.
The output of the input transducer is first scaled by constant K. The box with constant K maps the output range of the input transducer to the input range of the converter. Once the range has been mapped, the signal now needs to be shifted. The second portion of the circuit shifts the range by 2. Actual implementation of the circuit components is accomplished using amplifiers with some feedback loops.
In general, the scaling and bias process may be described by two equations:. A block diagram of the signal conditioning for an ADC.
The range of the sensor voltage output is mapped to the ADC input voltage range. The scalar multiplier maps the magnitudes of the two ranges, and the bias voltage is used to align two limits. The variable V1 max represents the maximum output voltage from the input transducer. This voltage occurs when the maximum physical variable Xmax is presented to the input transducer. This voltage must be scaled by the scalar multiplier K and then have a DC offset bias voltage B added to provide the voltage V2 max to the input of the ADC converter.
Similarly, The variable V1 min represents the minimum output voltage from the input transducer. This voltage occurs when the minimum physical variable Xmin is presented to the input transducer. This voltage must be scaled by the scalar multiplier K and then have a DC offset bias voltage B added to produce voltage V2 min to the input of the ADC converter.
Usually, the values of V1 max and V1 min are provided with the documentation for the transducer. Also, the values of V2 max and V2 min are known. We thus have two equations and two unknowns to solve for K and B.
The circuits to scale by K and add the offset B are usually implemented with operational amplifiers. We refer interested readers to Thomas and Rosa  listed in the References section. Once a physical signal has been converted to its corresponding electrical signal with the help of an input transducer and the output of the transducer mapped correctly to the input of the ADC, the ADC process can start.
The first step of the ADC process is the sampling of the analog signal. When selecting a converter, one must consider the type of physical signal that is being converted to properly ensure the sampling rate. What this means for the reader is to select an ADC that can handle a required conversion rate.
Because most microcontrollers now come with a built-in ADC, one must study the user manual portion discussing the conversion rate and make sure that the required sampling rate for the application falls under the advertised conversion rate. On the other hand, if you are dealing with human voice, you need at least an 8-kHz sampling rate capacity see Enderle et al. Once the analog signal has been sampled, the quantization process takes place. For this process, again one must decide how much quantization error can be allowed.
At one extreme where you are only concerned with finding out only two states, say on and off, quantization error of 1 V is not important. We can operate safely with 2 bits with maximum quantization error of 1. On the other hand, if we can only operate with maximum quantization error of 0. To determine the number of bits and its corresponding maximum quantization error, we use the following equation. Once the quantization level has been determined, we can now encode it using the available bits.
As seen in the previous section, the process is a simple conversion of a decimal number quantization level to a binary number. Note that the binary number should use all available bits. For example, quantization level 4 using 8 bits is converted as , not In summary, the ADC process has three steps for completion: In the next section, we delve into four different technologies used to implement the ADC process. Example 3. The photodiode is used with a transimpedance amplifier to convert the output current to an output voltage.
In this section, we will discuss this type of conversion process as well as other techniques. In certain applications, you are required to use converter technologies external to the microcontroller. We begin by briefly discussing four different types of technologies used in ADCs: For a detailed discussion, we refer the interested readers to Barrett and Pack . For the following discussion of different ADC technologies, see Figure 3.
One can group all existing technologies into two different categories: The successive approximation conversion, counter-based conversion, and parallel conversion use techniques to directly convert analog input signals into their digital counterparts.
They are all considered to fall under the direct conversion category. The integration method uses conversion time as the means to indirectly measure the magnitude of the incoming analog signals, an indirect approach.
Starting from the MSB down to the LSB, the controller turns on each bit at a time and generates an analog signal, with the help of the DAC, to be compared with the original input analog signal. Based on the result of the comparison, the controller changes or leaves the current bit and turns on the next MSB.
The process continues until decisions are made for all available bits. One can consider the process similar to a game children play often. One child thinks of a number in the range of 0 to 10 and asks another child to guess the number within n turns. The first child will tell the second child whether a guessed number is higher or lower than the answer at the end of each turn.
The optimal strategy in such a situation is to guess the middle number in the range, say 5. If the answer is higher than 5, the second guess should be 8. If the answer is lower than 5, the second guess should be 3. The strategy is to narrow down to the answer by partitioning the available range into two equal parts at every turn.
Four different technologies used to convert analog signals to digital signals: The advantage of this technique is that the conversion time is uniform for any input, but the disadvantage of the technology is the use of complex hardware for implementation. A sampled analog signal is integrated over a fixed period, say n clock cycles of the digital system.
Another fixed reference signal is integrated over time and compared with the input analog signal integrated. Although the value of the reference signal integrated is smaller than the input analog signal integrated, the reference signal is continuously integrated, and the time for the integration is measured.
When the two integrated values equal, the measured time is converted to a digital encoded value. One disadvantage of this technique is the varying time for the conversion process. A small analog value will take less time to convert compared with a large value. This conversion is performed with the help of a counter, a DAC, and a comparator. The counter starts at 0 and counts up. As the counter counts up, the corresponding value is converted to an analog value and compared with an input analog signal.
As long as the input analog signal is greater than the signal generated by the DAC, the counter counts up and the process continues. When the comparator detects that the signal from the DAC is greater than the input analog signal, the counter value is then converted to a digital value representing the sampled analog signal.
Similar to the converter based on the integration principle, the disadvantage of this type of converter is the varying conversion time. A parallel converter uses a large number of comparators and circuitry to simultaneously measure the input signal and convert it to a digital value. The obvious disadvantage of this technique is the cost involved in building the circuitry. It has the following features:. Let us discuss each feature in turn.
It requires 13 analog-to-digital clock cycles to perform an ADC conversion. The ADC system may be run at a slower clock frequency than the main microcontroller clock source. The ADC is equipped with a single successive approximation converter. Only a single ADC channel may be converted at a given time. The input of the ADC is equipped with an eight-input analog multiplexer.
The analog input for conversion is selected using the MUX[4: These two registers provide 16 bits for the bit result. Right justification is provided by clearing this bit.
The analog input voltage for conversion must be between 0 and Vcc V. If this is not the case, external circuitry must be used to ensure the analog input voltage is within these prescribed bounds as discussed earlier in the chapter.
The left edge of the diagram provides the external microcontroller pins to gain access to the ADC. The eight analog input channels are provided at ADC[7: The key features and registers of the ADC system previously discussed are included in the diagram.
It must be emphasized that the ADC system has many advanced capabilities that we do not discuss here. Our goal is to review the basic ADC conversion features of this powerful system.
We have already discussed many of the register settings already. We will discuss each register in turn. To select a specific input for conversion is accomplished when a binary equivalent value is loaded into the MUX[4: This may be accomplished using the following C instruction:. ADC registers. These bits may be set to the following values:. The ADC is turned on by setting this bit to a logic 1.
Setting this bit to logic 1 initiates an ADC. This bit sets to logic 1 when the ADC is complete. The ADIF bit is reset by writing a logic 1 to this bit. The ADPS[2: The ADC clock is derived from dividing down the main microcontroller clock. The function then enters a while loop waiting for the ADIF bit to set, indicating the conversion is complete. After conversion, the ADIF bit is reset by writing a logic 1 to it.
The desired channel for conversion is passed in as an unsigned character variable. The result is returned as a left-justified, bit binary result. In the final chapter of the book, we show how to convert an unsigned integer into a floating point voltage that may be displayed on a LCD. A simple example of such a conversion occurs in digital audio processing.
Human voice is converted to a digital signal, modified, processed, and converted back to an analog signal for people to hear. The process to convert digital signals to analog signals is completed by a DAC. The most commonly used technique to convert digital signals to analog signals is the summation method shown in Figure 3. For each bit, a comparator checks its logic state, high or low, to produce a clean digital bit, represented by a voltage level.
Typically, in a microcontroller. Scalar Multipliers. Comparators 2. A summation method to convert a digital signal into a quantized analog signal. Comparators are used to clean up incoming signals, and the resulting values are multiplied by a scalar multiplier, and the results are added to generate the output signal.
For the final analog signal, the quantized analog signal should be connected to a low pass filter followed by a transducer interface circuit. The voltage is then multiplied by a scalar value based on its significant position of the digital signal as shown in Figure 3. Once all bits for the signal have been processed, the resulting voltage levels are summed to produce the final analog voltage value. We also presented the quantization errors and the data rate associated with the ADC process.
The dynamic range of an ADC, one of the measures to describe a conversion process, was also presented. Two different categories exist to represent technologies used to convert analog signals to their corresponding digital signals: For the direct approach, we presented the successive approximation, counter-based, and parallel conversion techniques.
For the indirect approach, the integration-based conversion technique was discussed. We then reviewed the operation, registers, and actions required to program the ADC system aboard the ATmega We concluded the chapter with a brief presentation of DACs. Given a sinusoid with Hz frequency, what should be the minimum sampling frequency for an ADC if we want to faithfully reconstruct the analog signal after the conversion?
If 12 bits are used to quantize a sampled signal, what is the number of available quantized levels? What will be the resolution of such a system if the input range of the ADC is 10 V?
Given the V input range of an ADC and the desired resolution of 0. Perform a trade-off study on the four technologies used for the ADC. Use cost, conversion time, and accuracy as the list of criteria. Investigate the ADCs in your audio system.
Find the sampling rate, the quantization bits, and the technique used for the conversion. Design a circuit to convert the resistance change to a voltage change hint: Then design a transducer interface circuit to convert the output from the flex sensor circuit to voltages suitable for the ATmega16 ADC system.
If an analog signal is converted by an ADC to a binary representation and then back to an analog voltage using a DAC, will the original analog input voltage be the same as the resulting analog output voltage?
However, the microcontroller must be equipped to handle unscheduled, higher-priority events that might occur inside or outside the microcontroller. To process such events, a microcontroller requires an interrupt system . The interrupt system onboard a microcontroller allows it to respond to higher-priority events. These events may be planned, but we do not know when they will occur. When an interrupt event occurs, the microcontroller will normally complete the instruction it is currently executing and then transition program control to interrupt event specific tasks.
These tasks, which resolve the interrupt event, are organized into a function called an interrupt service routine ISR. Each interrupt will normally have its own interrupt specific ISR.
Once the ISR is complete, the microcontroller will resume processing where it left off before the interrupt event occurred. Three of the interrupts originate from external interrupt sources, whereas the remaining 18 interrupts support the efficient operation of peripheral subsystems aboard the microcontroller.
The ATmega16 interrupt sources are shown in Figure 4. The interrupts are listed in descending order of priority. The remaining interrupt sources are internal to the ATmega Interrupt Fetch Service Routine. When an interrupt occurs, the microcontroller completes the current instruction, stores the address of the next instruction on the stack, and starts executing instructions in the designated ISR corresponding to the particular interrupt source.
It also turns off the interrupt system to prevent further interrupts while one is in progress. The execution of the ISR is performed by loading the beginning address of the ISR specific for that interrupt into the program counter. The ISR will then commence.
Execution of the ISR continues until the return from interrupt instruction reti is encountered. Program control then reverts back to the main program. This is accomplished with the assembly language instruction SEI. In the next two examples that follow, we illustrate how to accomplish these steps.
Other compilers have similar features. We provide both an externally generated interrupt event and also one generated from within the microcontroller. As you can see, the pragma with the reserved word interrupt handler is used to communicate to the compiler that the routine name that follows is an ISR.
The number that follows the ISR name corresponds to the interrupt vector number in Figure 4. The ISR is then written like any other function. The specific settings for each interrupt is provided in Figure 4. Provided below is the code snapshot to configure an interrupt for INT0.
In this specific example, an interrupt will occur when a positive edge transition occurs on the ATmega16 INT0 external interrupt pin. We can use this overflow interrupt as a method of keeping track of real clock time hours, minutes, and seconds within a program. In this specific example, we use the overflow to provide precision program delays. In this example, the ATmega16 is being externally clocked by a MHz ceramic resonator.
The resonator frequency is further divided by using the CS[2: When CS[2: To create a precision delay, we write a function called delay.
The function requires an unsigned integer parameter value indicating how many 6. The function stays within a while loop until the desired number of interrupts has occurred. We also discussed how to program an interrupt for proper operation and provided two representative samples: What is the purpose of an interrupt? Describe the flow of events when an interrupt occurs.
Describe the interrupt features available with the ATmega What is interrupt priority? How is it determined? What steps are required by the system designer to properly configure an interrupt? A MHz ceramic resonator is not available. What is the maximum delay that may be generated with the delay function provided in the text without modification? How could the function be modified for longer delays?
Develop a hour timer hh: What is the accuracy of your timer? How can it be improved? In a simple application, one can program a microcontroller system to turn on or turn off an external device at a programmed time.
In a more involved application, we can use a microcontroller to generate complex digital waveforms with varying pulse widths to control the speed of a DC motor . In this chapter, we review the capabilities of the Atmel ATmega16  microcontroller to perform time-related functions.
We begin with a review of timing-related terminology. We then provide an overview of the general operation of a timing system followed by the timing system features aboard the ATmega Next, we present a detailed discussion of each of its timing channels, Timer 0, Timer 1, and Timer 2, and their different modes of operation. We call this signal periodic with period T if it satisfies. To measure the frequency of a periodic signal, we count the number of times a particular event repeats within a 1-s period.
The unit of frequency is Hertz, or cycles per second. For example, a sinusoidal signal with a Hz frequency means that a full cycle of a sinusoid signal repeats itself 60 times each second, or every If an event occurs with a rate of 1 Hz, the period of that event is 1 s.
Both periods and frequencies of signals are often used to specify timing constraints of embedded systems [3,4]. For example, when your car is on a wintery road and slipping, the engineers who designed your car configured the antislippage unit to react within some millisecond period, say 20 ms.
The constraint then forces the design team that monitors the slippage to program their monitoring system to check a slippage at a rate of 50 Hz. A good example is the use of a periodic pulse to control a servo motor. To control the direction and sometimes the speed of a motor, a periodic pulse signal with a changing duty cycle over time is used. The periodic pulse signal shown in Figure 5. The pulse shown in Figure 5. The duty cycle is defined as the percentage of one period a signal is on.
Therefore, we call the signal in Figure 5. For a timer system, the system clock is used to update the contents of a special register called a free-running counter. The job of a free-running counter is to count increment each time it sees a rising edge or a falling edge of a clock signal. Thus, if a clock is running at the rate of 2 MHz, the free-running counter will count each 0.
Two signals with the same period but different duty cycles: For input time-related activities, all microcontrollers typically have timer hardware com- ponents that detect signal logic changes on one or more input pins. Such components rely on a free-running counter to capture external event times. We can use such ability to measure the period of an incoming signal, the width of a pulse, and the time of a signal logic change.
For output timer functions, a microcontroller uses a comparator, a free-running counter, logic switches, and special-purpose registers to generate time-related signals on one or more output pins. A comparator checks the value of the free-running counter for a match with the contents of another special-purpose register where a programmer stores a specified time in terms of the free-running counter value.
Using such capability, one can generate a simple logic change at a designated time incident, a pulse with a desired time width, or a PWM signal to control servo or DC motors.
You can also use the timer input system to measure the pulse width of an aperiodic signal. For example, suppose that the times for the rising edge and the falling edge of an incoming signal are 1. We can use these values to easily compute the pulse width of 0. The second overall goal of the timer system is to generate signals to control external devices. Again, an event simply means a change of logic states on an output pin of a microcontroller at a specified time.
Now consider Figure 5. Suppose an external device connected to the microcontroller requires a pulse signal to turn itself on. Suppose the particular pulse the external device needs is 2-ms wide. In such situations, we can use the free-running counter value to synchronize the time of desired logic state changes. Naturally, extending the same capability, we can also generate a periodic pulse with a fixed duty cycle or a varying duty cycle.
From the examples we discussed above, you may have wondered how a microcontroller can be used to compute absolute times from the relative free-running counter values, say 1. The simple answer is that we cannot do so directly. A programmer must use the relative system clock values and derive the absolute time values.
Suppose your microcontroller is clocked by a 2-MHz signal, and the system clock uses a bit free-running counter. For such a system, each clock period represents 0. The timer input system then uses the clock values to compute frequencies, periods, and pulse widths. For example, suppose you want to measure a pulse width of an incoming aperiodic signal. Let us first convert the two values into their corresponding decimal values, and The pulse width of the signal in the number of counter value is Our calculations do not take into account time increments lasting longer than the rollover time of the counter.
When a counter rolls over from its maximum value back to 0, a flag is set to notify the processor of this event. The rollover events may be counted to correctly determine the overall elapsed time of an event. We first start with a case of measuring the time duration of an incoming signal. Using the hardware and functional units discussed in the previous sections, we now present a procedure to accomplish the task of computing the frequency of an incoming periodic signal.
The first necessary step for the current task is to turn on the timer system. To reduce power consumption, a microcontroller usually does not turn on all of its functional systems after reset until they are needed. In addition to a separate timer module, many microcontroller manufacturers allow a programmer to choose the rate of a separate timer clock that governs the overall functions of a timer module.
Once the timer is turned on and the clock rate is selected, a programmer must configure the physical port to which the incoming signal arrives. This step is done using a special input timer port configuration register. The next step is to program the input event to capture.
External Timer Output Port Device. The signal on top is fed into a timer input port. The captured signal is subsequently used to compute the input signal frequency. The signal on the bottom is generated using the timer output system.
The signal is used to control an external device. Again, the programming portion is done by storing an appropriate setup value to a special register. Now that the input timer system is configured appropriately, you now have two options to accomplish the task.
The first one is the use of a polling technique; the microcontroller continuously polls a flag, which holds a logic high signal when a programmed event occurs on the physical pin.
Once the microcontroller detects the flag, it needs to clear the flag and record the time when the flag was set using another special register that captures the time of the associated free-running counter value. The program needs to continue to wait for the next flag, which indicates the end of one period of the incoming signal.
A programmer then needs to record the newly acquired captured time represented in the form of a free-running counter value again. The period of the signal can now be computed by computing the time difference between the two captured event times, and based on the clock speed of the microcontroller, the programmer can compute the actual time changes and consequently the frequency of the signal.
In many cases, a microcontroller cannot afford the time to poll for one event. Such situation introduces the second method: Most microcontroller manufacturers have developed built-in interrupt systems with their timer input modules. Instead of continuously polling for a flag, a microcontroller performs other tasks and relies on its interrupt system to detect the programmed event.
The task of computing the period and the frequency is the same as the first method, except that the microcontroller will not be tied down constantly checking the flag, increasing the efficient use of the microcontroller resources.
Typically, additional registers must be configured, and a special program called an ISR must be written. Note that these values are not absolute times but the representations of times reflected as the values of the free-running counter.
If we assume that the timer clock runs at 10 MHz, the period of the signal is 1. Suppose we want to count the number of logic state changes of an incoming signal for a given period. Again, we can use the polling technique or the interrupt technique to accomplish the task. For both techniques, the initial steps of turning on a timer and configuring a physical input port pin are the same. In this application, however, the programmed event should be any logic state changes instead of looking for a rising or a falling edge as we have done in the previous section.
If the polling technique is used, at each event detection, the corresponding flag must be cleared and a counter must be updated. If the interrupt technique is used, one must write an ISR within which the flag is cleared and a counter is updated. In this subsection and the next one, we consider how a microcontroller can generate time critical signals for external devices. Suppose in this application, we want to send a signal shown in Figure 5. The timing signal is arbitrary, but the application will show that a timer output system can generate any desired time-related signals permitted under the timer clock speed limit of the microcontroller.
Similar to the use of the timer input system, one must first turn on the timer system and configure a physical pin as a timer output pin using special registers. In addition, one also needs to program the desired external event using another special register associated with the timer output system. To generate the signal shown in Figure 5. Suppose that the external device requires a pulse that is 2 ms wide to be activated.
To generate the desired pulse, one must first program the logic state for the particular pin to be low and set the time value using a special register with respect to the contents of the free-running counter. As was mentioned in Section 5. Once the rising edge is generated, the program then must reconfigure the event to be a falling edge logic state low and change the contents of the special register to be compared with the free-running counter.
For the particular example in Figure 5. As was the case with the input timer system module, we can use output timer system interrupts to generate the desired signals as well. The underlying concept is as follows. If we turn on a DC motor and provide the required voltage, the motor will run at its maximum speed.
Suppose we turn the motor on and off rapidly by applying a periodic signal. The motor at some point cannot react fast enough to the changes of the voltage values and will run at the speed proportional to the average time the motor was turned on. By changing the duty cycle, we can control the speed of a DC motor as we desire. Suppose again we want to generate a speed profile shown in Figure 5.
As shown in the figure, we want to accelerate the speed, maintain the speed, and decelerate the speed for a fixed amount of time. The first task necessary is again to turn on the timer system, configure a physical port, and program the event to be a rising edge.
Once the rising edge is generated, the program then needs to modify the event to a falling edge and change the contents of the output timer register to a value proportional to a desired duty cycle. Constant Speed Period Motor Velocity. Acceleration Deceleration Period Period. Time Pulse Width Modulated Signal. Standard IO and Preprocessor Functions. Project Development. Library Functions Reference. Answers to Selected Exercises.
Leave a Reply Cancel Reply Your email address will not be published. Recent Posts. Project Categories. Richard H. Barnett , Larry D. Cox , Sarah Alison Cox. Internet - Ethernet - LAN. Metering - Instrument. Sensor - Transducer - Detector. Motor Project. Phone Project. Robotics - Automation Projects. Video - Camera - Imaging. Game - Entertainment Project. Home Automation Project. Memory - Storage. RFID Projects. Security - Safety Project.
Sound - Audio Projects.