Customized Electronic Dictionary
Customized Electronic Dictionary
by Ashish Kumar Gupta (0509131071) Pulkit Maheshwari (0509131026) Shubham Sinha (0509131097) Submitted to the Department of Electronics & Communication in partial fulfillment of the requirements for the degree of Bachelor of Technology in Electronics & Communication Engg. Under the guidance of Mrs Monica Malik
J.S.S. Academy of Technical Education, Noida U.P. Technical University May, 2009
DECLARATION
We hereby declare that this submission is our own work and that, to the best of our knowledge and belief, it contains no material previously published or written by another person nor material which to a substantial extent has been accepted for the award of any other degree or diploma of the university or other institute of higher learning, except where due acknowledgement has been made in the text.
CERTIFICATE
This is to certify that Project Report entitled Electronic Dictionary submitted by Pulkit Maheshwari, Ashish Kumar Gupta and Shubham Sinha in partial fulfillment of the requirement for the award of degree Bachelor of Technology in Department of Electronics & Communication of JSSATE (U.P. Technical University,Lucknow), is a record of the candidates own work carried out by him under my supervision. The matter embodied in this thesis is original and has not been submitted for the award of any other degree.
ACKNOWLEDGEMENT
We owe special debt of gratitude to our Project Guide, Mrs. Monica Malik for providing her valuable support, guidance and worthy suggestions during various stages of our project Mrs. Chhaya Grover and Mrs. KHNV Laxmi for their extreme cooperation and generous help. Without their help and support this project would not have reached to its completion. We are also thankful to Mr. Uday (Project Coordinator, Department of EC) for her kind help and guidance in completion of the project. We are also grateful to all the staff of our EC Department & the institute and our friends whose contribution in this effort was appreciable. They have been very helpful for the entire period and have been a great source of inspiration for us.
ABSTRACT
An embedded system is a special-purpose computer system designed to perform one or a few dedicated functions often with real-time computing constraints. It is usually embedded as part of a complete device including hardware and mechanical parts. Since the embedded system is dedicated to specific tasks, design engineers can optimize it, reducing the size and cost of the product, or increasing the reliability and performance. Some embedded systems are mass-produced, benefiting from economies of scale. Embedded systems can also be used to meet the daily requirements. The inspiration of this project is the need of a specific dictionary for candidates preparing for competitive exams like GRE, GMAT, CAT etc These exams require candidates to learn a specific list of words to enhance their vocabulary skills. Further, a customised dictionary can also be used to store general words in different foreign languages for tourists. The electronic dictionary can be scaled down to a very compact size that can fit into a pocket and can be customized for any purpose. By changing the program it can be filled with any list of words the user desires. The electronic dictionary has a compact keyboard interface and a programmable LCD (graphical LCD will be used to display foreign languages). Further to accommodate a large number of words an external memory or a microcontroller with large memory is used. The searching algorithm used here is a modified version of binary string search, where first a pointer takes the control to the list of words starting with the first letter of the input word. Then the ASCII code of the second letter of the middle word in the list is matched with the second letter of the input word. Based on the comparison, the search then shortens down to the upper half or lower half of the list. This process continues until the desired word is found. The electronic dictionary finds any word stored in its database in 100 milliseconds. This delay is set to constant in all the words to obtain uniformity. There are no cases of incorrect item matching or failure to find a word. It is completely efficient.
TABLE OF CONTENTS
DECLARATION.................................................................................................................2 CERTIFICATE....................................................................................................................3 ACKNOWLEDGEMENT...................................................................................................4 ABSTRACT.........................................................................................................................5 LIST OF FIGURES.8 LIST OF TABLES.. ....9 CHAPTER 1 INTRODUCTION....11
1.1 INTRODUCTION TO MICROCONTROLLERS...11 1.2 FEATURES AND FUNCTIONS OF ATMEGA 32L.....15 1.3 PIN CONFIGURATION..18
CHAPTER 2 LCD AND ITS INTERFACING..19 2.1 LCD AND ITS WORKING PRINCIPLE....19 2.2 LIQUID CRYSTAL MATERIAL....21 2.3 FEATURES AND SPECIFICATIONS OF 16X2 LCD......23 2.4 INTERFACING OF LCD WITH MICROCONTROLLER.26 CHAPTER 3 MATRIX KEYPAD AND INTERFACING...27 3.1 THE MATRIX CIRCUIT..27 3.2 SCANNING TO DETECT KEY PRESSES.28 3.3 INTERFACING OF 4X4 KEYPAD MATRIX WITH ATMEGA 32L..33
CHAPTER 4 COMPLETE CIRCUIT INTERFACING36 4.1 INTERFACING OF TWO ATMEGA 32L..36 4.2 COMPLETE CIRCUIT DIAGRAM38
CHAPTER 5 ALGORITHM...39 5.1 BINARY SEARCH...39 5.2 APPLICATIONS TO COMPLEXITY THEORY....40 5.3 THE METHOD.....40
5.4 COMPARISON OF BINARY SEARCH AND LINEAR SEARCH.43 CHAPTER 6 CONCLUSION.....46 6.1 FINAL SEARCH TIME AND EFFICIENCY.....46 6.2 APPLICATION OF ELECTRONIC DICTIONARY...46
APPENDIX A: LIST OF WORDS INCLUDED IN THE DICTIONARY. 47 APPENDIX B: PROGRAMMING CODES..55 APPENDIX C: SOFTWARES USED77 REFERENCES78
LIST OF FIGURES
1. FIGURE 1.1
1.
Pin Configuration Of Atmega32L Cross Section Of a Simple LC Display X,Y,Z Direction in LCD Circuit for interfacing of LCD with ATMEGA 32L Conceptual Matrix Circuit Open Switch Key Scanning Column 1 The A key is Pressed The A Switch is Closed Row 1 is Activated Neither row is Activated The Key A and D are pressed Row 1 is Activated Self The Key A,B and D are Pressed Interface between Atmega32L and keyboard matrix Circuit diagram Interfacing of two Atmega32L Circuit Diagram Of Electronic Dictionary
1. FIGURE 3.3 1. FIGURE 3.4 1. FIGURE 3.5 1. FIGURE 3.6 1. FIGURE 3.7 1. FIGURE 3.8 1. FIGURE 3.9 1. FIGURE 3.10 1. FIGURE 3.11 1. FIGURE 4.1
LIST OF TABLES
1. TABLE 2.1
MECHANICAL SPECIFICATION OF LCD ELECTRICAL SPECIFICATION OF LCD PIN FUNCTIONS OF 16X2 LCD
1. TABLE 2.2
1. TABLE 2.3
10
1.
CHAPTER 1 INTRODUCTION
11
A microcontroller is a small computer on a single integrated circuit consisting of a relatively simple CPU combined with support functions such as a crystal oscillator, timers, watchdog, serial and analog I/O etc. Program memory in the form of flash or ROM is also often included on chip, as well as a, typically small, read/write memory. Microcontrollers are designed for small applications. Thus, in contrast to the microprocessors used in personal computers and other high-performance applications, simplicity is emphasized. Some microcontrollers may operate at clock frequencies as low as 32KHz, as this is adequate for many typical applications, enabling low power consumption (milliwatts or microwatts). They will generally have the ability to retain functionality while waiting for an event such as a button press or other interrupt; power consumption while sleeping (CPU clock and most peripherals off) may be just nanowatts, making many of them well suited for long lasting battery applications. Microcontrollers are used in automatically controlled products and devices, such as automobile engine control systems, remote controls, office machines, appliances, power tools, and toys. By reducing the size and cost compared to a design that uses a separate microprocessor, memory, and input/output devices, microcontrollers make it economical to digitally control even more devices and processes. The majority of computer systems in use today are embedded in other machinery, such as automobiles, telephones, appliances, and peripherals for computer systems. These are called embedded systems. While some embedded systems are very sophisticated, many have minimal requirements for memory and program length, with no operating system, and low software complexity. Typical input and output devices include switches, relays, solenoids, LEDs, small or custom LCD displays, radio frequency devices, and sensors for data such as temperature, humidity, light level etc. Embedded systems usually have no keyboard, screen, disks, printers, or other recognizable I/O devices of a personal computer, and may lack human interaction devices of any kind. Since embedded processors are usually used to control devices, they sometimes need to accept input from the device they are controlling. This is the purpose of the analog to digital converter. Since processors are built to interpret and process digital data, i.e. 1s and 0s, they won't be able to do anything with the analog signals that may be being sent to it by a device. So the analog to digital converter is used to convert the incoming data into a
12
form that the processor can recognize. There is also a digital to analog converter that allows the processor to send data to the device it is controlling. In addition to the converters, many embedded microprocessors include a variety of timers as well. One of the most common types of timers is the Programmable Interval Timer, or PIT for short. A PIT just counts down from some value to zero. Once it reaches zero, it sends an interrupt to the processor indicating that it has finished counting. This is useful for devices such as thermostats, which periodically test the temperature around them to see if they need to turn the air conditioner on, the heater on, etc. Time Processing Unit or TPU for short is a sophisticated timer. In addition to counting down, the TPU can detect input events, generate output events, and perform other useful operations. Dedicated Pulse Width Modulation (PWM) block makes it possible for the CPU to control power converters, resistive loads, motors, etc., without using lots of CPU resources in tight timer loops. Universal Asynchronous Receiver/Transmitter (UART) block makes it possible to receive and transmit data over a serial line with very little load on the CPU. In contrast to general-purpose CPUs, microcontrollers may not implement an external address or data bus as they integrate RAM and non-volatile memory on the same chip as the CPU. Using fewer pins, the chip can be placed in a much smaller, cheaper package. Integrating the memory and other peripherals on a single chip and testing them as a unit increases the cost of that chip, but often results in decreased net cost of the embedded system as a whole. Even if the cost of a CPU that has integrated peripherals is slightly more than the cost of a CPU + external peripherals, having fewer chips typically allows a smaller and cheaper circuit board, and reduces the labor required to assemble and test the circuit board. A microcontroller is a single integrated circuit, commonly with the following features:
central processing unit - ranging from small and simple 4-bit processors to complex 32- or 64-bit processors
discrete input and output bits, allowing control or detection of the logic state of an individual package pin
13
other serial communications interfaces like IC, Serial Peripheral Interface and Controller Area Network for system interconnect
peripherals such as timers, event counters, PWM generators, and watchdog volatile memory (RAM) for data storage ROM, EPROM, EEPROM or Flash memory for program and operating parameter storage
clock generator - often an oscillator for a quartz timing crystal, resonator or RC circuit
This integration drastically reduces the number of chips and the amount of wiring and circuit board space that would be needed to produce equivalent systems using separate chips. Furthermore, and on low pin count devices in particular, each pin may interface to several internal peripherals, with the pin function selected by software. This allows a part to be used in a wider variety of applications than if pins had dedicated functions. Microcontrollers have proved to be highly popular in embedded systems since their introduction in the 1970s. Some microcontrollers use a Harvard architecture: separate memory buses for instructions and data, allowing accesses to take place concurrently. Where a Harvard architecture is used, instruction words for the processor may be a different bit size than the length of internal memory and registers; for example: 12-bit instructions used with 8-bit data registers. The decision of which peripheral to integrate is often difficult. The microcontroller vendors often trade operating frequencies and system design flexibility against time-tomarket requirements from their customers and overall lower system cost. Manufacturers have to balance the need to minimize the chip size against additional functionality. Microcontroller architectures vary widely. Some designs include general-purpose microprocessor cores, with one or more ROM, RAM, or I/O functions integrated onto the package. Other designs are purpose built for control applications. A microcontroller instruction set usually has many instructions intended for bit-wise operations to make control programs more compact.[2] For example, a general purpose processor might require several instructions to test a bit in a register and branch if the bit is set, where a
14
microcontroller could have a single instruction to provide that commonly-required function. Microcontrollers typically do not have a math coprocessor, so fixed point or floating point arithmetic are performed by program code. Microcontrollers were originally programmed only in assembly language, but various high-level programming languages are now also in common use to target microcontrollers. These languages are either designed specially for the purpose, or versions of general purpose languages such as the C programming language. Compilers for general purpose languages will typically have some restrictions as well as enhancements to better support the unique characteristics of microcontrollers. Some microcontrollers have environments to aid developing certain types of applications. Microcontroller vendors often make tools freely available to make it easier to adopt their hardware.
Features Advanced RISC Architecture 131 Powerful Instructions Most Single-clock Cycle Execution 32 x 8 General Purpose Working Registers Fully Static Operation Up to 16 MIPS Throughput at 16 MHz On-chip 2-cycle Multiplier High Endurance Non-volatile Memory segments 32K Bytes of In-System Self-programmable Flash program memory 1024 Bytes EEPROM 2K Byte Internal SRAM Write/Erase Cycles: 10,000 Flash/100,000 EEPROM Data retention: 20 years at 85C/100 years at 25C Optional Boot Code Section with Independent Lock Bits In-System Programming by On-chip Boot Program True Read-While-Write Operation Programming Lock for Software Security JTAG (IEEE std. 1149.1 Compliant) Interface
15
Boundary-scan Capabilities According to the JTAG Standard Extensive On-chip Debug Support Programming of Flash, EEPROM, Fuses, and Lock Bits through the JTAG Interface Peripheral Features Two 8-bit Timer/Counters with Separate Prescalers and Compare Modes One 16-bit Timer/Counter with Separate Prescaler, Compare Mode, and Capture Mode Real Time Counter with Separate Oscillator Four PWM Channels 8-channel, 10-bit ADC 8 Single-ended Channels 7 Differential Channels in TQFP Package Only 2 Differential Channels with Programmable Gain at 1x, 10x, or 200x Byte-oriented Two-wire Serial Interface Programmable Serial USART Master/Slave SPI Serial Interface Programmable Watchdog Timer with Separate On-chip Oscillator On-chip Analog Comparator Special Microcontroller Features Power-on Reset and Programmable Brown-out Detection Internal Calibrated RC Oscillator External and Internal Interrupt Sources Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby and Extended Standby I/O and Packages 32 Programmable I/O Lines 40-pin PDIP, 44-lead TQFP, and 44-pad QFN/MLF Operating Voltages 2.7 - 5.5V for ATmega32L 4.5 - 5.5V for ATmega32 Speed Grades 0 - 8 MHz for ATmega32L 0 - 16 MHz for ATmega32 Power Consumption at 1 MHz, 3V, 25C for ATmega32L
16
Active: 1.1 mA Idle Mode: 0.35 mA Power-down Mode: < 1 A Memory The AVR architecture has two main memory spaces, the Data Memory and the Program Memory space. In addition, the ATmega32 features an EEPROM Memory for data storage. All three memory spaces are linear and regular. The ATmega32 contains 32K bytes On-chip In-System Reprogrammable Flash memory for program storage. Since all AVR instructions are 16 or 32 bits wide, the Flash is organized as 16K x 16. For software security, the Flash Program memory space is divided into two sections, Boot Program section and Application Program section. The Flash memory has an endurance of at least 10,000 write/erase cycles. The ATmega32 Program Counter (PC) is 14 bits wide, thus addressing the 16K program memory locations.
The lower 2144 Data Memory locations address the Register File, the I/O Memory, and the internal data SRAM. The first 96 locations address the Register File and I/O Memory, and the next 2048 locations address the internal data SRAM. The five different addressing modes for the data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment. In the Register File, registers R26 to R31 feature the indirect Addressing Pointer Registers. The direct addressing reaches the entire data space. The Indirect with Displacement mode reaches 63 address locations from the base address given by the Y- or Z-register. When using register indirect addressing modes with automatic pre-decrement and postincrement, the address registers X, Y, and Z are decremented or incremented.
17
The 32 general purpose working registers, 64 I/O Registers, and the 2048 bytes of internal data SRAM in the ATmega32 are all accessible through all these addressing modes.
The ATMEGA 32L has total forty pins. four ports named A,B,C and D having eight pins each. Some of these pins are used for multiple purpose such as Analog to Digital convertor, Interrupt handling and serial communication. These ports can have unidirectional or bidirectional or both types of data transfers. Atmega 32L comes in two types of packaging-DIP and TQFP. The packaging used for electronic dictionary is DIP.
18
19
of 16 characters. These can be easily interfaced to MCU's, thanks to the API( Functions used to easily access the modules) we provide.
2.1.1 General Characteristics and LCD Modes Liquid Crystal Displays (LCDs) are categorized as non- emissive display devices, in that respect, they do not produce any form of light like a Cathode Ray Tube (CRT). LCDs either pass or block light that is reflected from an external light source or provided by a back/side lighting system. There are two modes of operation for LCDs during the absence of an electric field (applied Power); a mode describes the transmittance state of the liquid crystal elements. Normal White mode: the display is white or clear and allows light to pass through and Normal Black Mode: the display is dark and all light is diffused. Virtually all displays in production for PC/Workstation use are normal white mode to optimize contrast and speed. 2.1.2 LCD Cell Switching and Fundamentals A simplified description of how a dot matrix LCD display works is as follows: A twisted nematic (TN) LC display consists of two polarizers, two pieces of glass, some form of switching element or electrode to define pixels, and driver Integrated Circuits (ICs) to address the rows and columns of pixels. To define a pixel (or subpixel element for a color display), a rectangle is constructed out of Indium Tin Oxide -- a semi-transparent metal oxide (ITO) and charge is applied to this area in order to change the orientation of the LC material ( change from a white pixel to a dark pixel). The method utilized to form a pixel in passive and active matrix displays differs and will be described in later sections. Figure 1 illustrates a cross sectional view of a simple TN LC display. Figure 2 depicts a dot matrix display as viewed without its metal module/case exposing the IC drivers. Looking directly at the display the gate or row drivers are located either on the left or the right side of the display while the data or column drivers are located on the top (and or bottom) of the display. New thin display module technology mounts the ICs on conductive tape that allows them to be folded behind the display further reducing the size of the finished module. An IC will address a number of rows or columns, not just 1 as pictured in figure 2.1
20
Polarizers are an integral part of a LCD display, possessing the unique property of only passing light if it is oriented in a specific (oriented) direction. To utilize this phenomena in TN LC displays, the bottom polarizer orients incoming light in one direction. The oriented light passes through the LC material and is either unaltered or "bent" 90 degrees. Depending on the orientation of the top polarizer, this light will either pass through or be diffused. If the light is diffused, it will appear as a dark area. Figure 3 is a simple illustration of the sequence of events that occur when light passes through a simple twisted nematic LC display.
Liquid crystals encompass a broad group of materials that posses the properties of both a solid and a liquid. More specifically, they are a liquid with molecules oriented in one common direction (having a long range and repeating pattern-- definition of a crystal), but
21
have no long range order in the other two directions. For example, in figure 4 all the lines are oriented in the Y direction (up and down), but they posses no common ordering in the x direction (disorder is assumed in the Z direction). To more easily visualize this, think of figure 4 as one thin slice (one layer of molecules to be exact) of a block of material. If you examined another slice, the molecules would still be oriented in the Y direction, but they would be in different positions along the X-axis. By stacking millions of these thin slices, the Z direction is built up and as a result of the change in relative position on the x-axis, the Z direction has no long range order.
Figure 2.2 : X,Y,Z-Direction in LCD. The liquid crystals used for display technology are thermotropic liquid crystals; they exhibit desired characteristics over a specific temperature range. This is the primary reason why LCDs do not operate properly when they are too cold or too warm. If liquid crystals are too cold, they will not twist and the display will not form an image. If the display is too warm, the resistance of the liquid crystal material changes and this alters the properties of the display and performance suffers. Liquid crystal material for display use is normally referred to as TN (STN, DSTN, MSTN, and etc.) or Twisted Nematic--sometimes known as TNFE or Twisted Nematic Field Effect. It is called TWISTED since the crystals are twisted 90 degrees (or more for STN) from the top piece of glass to the bottom piece of glass. (TN usually refers only to a 90 degree twist.) Field Effect (a direct correlation is the semiconductor MOSFET), refers to the LC material's ability to align parallel or perpendicular to an applied electric field. As a result, using twisted or untwisted liquid crystal and two polarizers; an applied electric field can force the LC material into a particular alignment effectively diffusing or passing light through the top polarizer.
22
As a note of interest, polarizers are also one of the major reasons that LC displays require bright back lighting. The polarizers and liquid crystal materials absorb more than 50% of the incident light. As a result, even though the actual display is a very low power device, the power hungry back lighting makes a LCD module one of the primary causes of short battery life in notebook computers. Due to the fact that the LC material has optical properties and effectively bends light, the problem of viewing angle effects occur. When the user is not directly in front of the display the image can disappear or seem to invert (dark images become light and light images become dark). However, LC material and polarizer technology is rapidly improving and that improvement is showing up in brighter displays with greater viewing angles. 2.2.1 Liquid Crystal Alignment Liquid crystals must be aligned to the top and bottom pieces of glass in order to obtain the desired twist. In other words, the 90 degree twist is formed by anchoring the liquid crystal on one glass plate and forcing it to twist across the cell gap (the distance between the two glass plates) when contacting the second plate. Furthermore, The actual image quality of the display will be dependent on the surface alignment of the LC material. The method currently used for aligning liquid crystals was developed by the Dai-Nippon Screening (English= Big Japan Screening) Company. The process consists of coating the top and bottom sheets of glass with a Polyimide based film. The top piece of glass is coated and rubbed in a particular orientation; the bottom panel/polyimide is rubbed perpendicular (90 degrees for TN displays) with respect to the top panel. It was discovered that by rubbing the polyimide with a cloth, nanometer (1 X 10 - 9 meters) size grooves are formed and the liquid crystals align with the direction of the grooves. It is common that when assembling a TN LC cell, it will be necessary to eliminate patches of non- uniform areas. The two parameters required to eliminate the nonuniformities and complete the TN LC display are pretilt angle and cholesteric impurities. TN LC cells commonly have two problems that affect uniformity following assembly: reverse tilt and reverse twist. Reverse tilt is a function of the applied electrical field and reverse twist is common when no electrical field is applied. Reverse twist is eliminated by the introduction of cholesteric additives and reverse tilt is eliminated by introducing a pre-tilt angle to the LC material. The pre-tilt angle also determines what direction the LC molecules will rotate when an electrical field is applied. Pre-tilt angle can be visualized by considering the normal position of the LC molecule to be flat against the glass plate, by anchoring one edge and forcing the other upward by a specific number of degrees, a pretilt angle is established.
23
2.3.1 FEATURES 5 x 8 dots with cursor Built-in controller (KS 0066 or Equivalent) + 5V power supply (Also available for + 3V) 1/16 duty cycle B/L to be driven by pin 1, pin 2 or pin 15, pin 16 or A.K (LED) N.V. optional for + 3V power supply
24
25
26
For electronic dictionary, four pins of the LCD are used for data transfer and display which are connected to PORT C of the microcontroller. Two pins are used for Vcc and GND and one pin is connected to a 10K ohm potentiometer for contrast adjustment. The code for sending data to the LCD data bus is given in Appendix 2.
CHAPTER 3
27
Figure 3.1 : Conceptual Matrix Circuit This keyboard only has 4 keys: A, B, C, and D. Each key has a unique grid location, much like points on a graph. Key A is at node C1R1, key B is at node C2R1, key C is at node C1R2, and key D is at node C2R2. In reality this is pretty useless which is why real keyboards use many more rows and columns. The electronic circuit for this matrix looks something (not exactly) like this:
28
Neither key A nor C are pressed, so neither row R1 nor R2 is activated. The controller now knows that both nodes C1R1 and C1R2 are deactivated.
29
Then it activates column C2 and checks rows R1 and R2 again: Neither key B nor D are pressed so neither row R1 nor R2 is activated. The controller now knows that both nodes C2R2 and C2R2 are deactivated. 3.2.1 Single Key Presses Now, let's say the the A key is pressed. The matrix will look like this:
Figure 3.4 The A Key is Pressed Key A corresponds to node C1R1. By going back to the circuit, we can see how C1R1 is detected. First, here is the circuit with switch A closed:
Walking through the scanning procedure again, the controller activates column C1 and detects which rows are activated:
30
Figure 3.6 Row 1 is Activated This time, row R1 is activated. So the controller now knows that node C1R1 is pressed. Since C1R1 corresponds to the A key, the controller knows that the A key is pressed. When the controller activates column C2, neither row R1 nor R2 are activated. Both switches B and D are open:
When the A key is released, the circuit goes back to the original, and the controller detects the node C1R1 is no longer activated.
3.2.2 Multiple Key Presses Now we will cover multiple key presses. Let's say that both keys A and D are pressed at the same time. The matrix will look like this:
31
Figure 3.8 The A and D Keys are Pressed Both nodes C1R1 and C2R2 should be detected. Here is the circuit with both switches A and D closed: Scanning column C1 then column C2 produces an outcome like this:
When column C1 is activated, row R1 is active, hence node C1R1 is activated. When column C2 is activated, row R2 is activated, hence node C2R2 is activated.
3.2.3 Three Simultaneous Key Presses and Ghosting When three keys are pressed at the same time, ghosting may occur. In this example, keys A, B, and D are pressed. The matrix looks like this:
32
Figure 3.10 The A, B, and D Keys are Pressed If everything goes well, nodes C1R1, C2R1, and C2R2 will be detected. Let's look at the circuit If you get the feeling something is not right, you are correct! This is where the ghosting problem comes to play. Row R1 is activated as well as row R2, so both nodes C1R1 and C1R2 are activated. Node C1R1 is expected as it corresponds to the A key that is pressed. However, node C1R2 corresponds to the C key. Switch C is open, so the key is not really pressed. The keyboard controller does not know this and incorrectly generates a C key press. What happens is that closing switch B and switch D at the same time creates an electrical path from C1 to R2, bypassing the open switch C. The keyboard does not know that switch C is open and generates a "ghost" key press. Ghosting will show up when any 3 corners of a rectangle in the matrix are pressed at once. In my simple example, any 3 keys causes ghosting, but in a bigger matrix only 3 corners of a rectangle cause it. Just for completion, here is the circuit when activating column C2: As expected, nodes C2R1 and C2R2 are activated corresponding to the B and D keys
33
The four input pin has a 10k pull-up to Vcc. We make the upper four bits of PortD function as output with a logic high. The lower four bits are made to funtion as input with a logic low. Now, if a key is pressed, a connection is made between a column (output, logic low) and a row (input, logic high). This row line will be pulled low. Also, the OR output goes low, and Int0 fires an interrupt. In the interrupt routine we quickly read the state of the row lines to see on which row the pressed key is. Then, the upper four bits of PortD are made input with logic level high, and the lower four bits are made output with logic level low. Now, we read the state of the
34
upper four bits to determine on which column the pressed key is. We then wait a certain 'debounce' time. From the state of the row and column lines read, the key pressed is determined. Lastly, the state of the row and column bits of Port D is restored to the starting point.Which key has been pressed is then determined from the state of the row and column bits.The first 13 keys are dual function keys representing two consecutive alphabets with the use of a shift key. Suppose we have to enter alphabet B. For that we will press alphabet A along with shift key. The last three keys in the matrix are not dual functions. They are used for BACKSPACE, SEARCH and RESET instructions. Following is the table for assigning a specific code to an alphabet or an instruction: Code generated 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Alphabet Assigned A B C D E F G H I J K L M N O P Q R S T
35
21 22 23 24 25 26 27 28 29
36
Figure 4.1 Circuit Diagram Interfacing of two Atmega32L 4.1.1 USART Initialization The USART has to be initialized before any communication can take place. The initialization process normally consists of setting the baud rate, setting frame format and enabling the Transmitter or the Receiver depending on the usage. For interrupt driven USART operation, the Global Interrupt Flag should be cleared (and interrupts globally disabled) when doing the initialization.
37
Before doing a re-initialization with changed baud rate or frame format, be sure that there are no ongoing transmissions during the period the registers are changed. The TXC Flag can be used to check that the Transmitter has completed all transfers, and the RXC Flag can be used to check that there are no unread data in the receive buffer. Note that the TXC Flag must be cleared before each transmission (before UDR is written) if it is used for this purpose. 4.1.2 Data Transmission The USART Transmitter The USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in the UCSRB Register. When the Transmitter is enabled, the normal port operation of the TxD pin is overridden by the USART and given the function as the transmitters serial output. The baud rate, mode of operation and frame format must be set up once before doing any transmissions. If synchronous operation is used, the clock on the XCK pin will be overridden and used as transmission clock. 4.1.2 Data Transmission The USART Receiver The USART Receiver is enabled by writing the Receive Enable (RXEN) bit in the UCSRB Register to one. When the receiver is enabled, the normal pin operation of the RxD pin is overridden by the USART and given the function as the receivers serial input. The baud rate, mode of operation and frame format must be set up once before any serial reception can be done. If synchronous operation is used, the clock on the XCK pin will be used as transfer clock. For the code refer to appendix.
38
CHAPTER 5
39
SEARCHING ALGORITHIM
Finding the index of a specific value in a sorted list is useful because, given the index, other data structures will contain associated information. Suppose a data structure containing the classic collection of name, address, telephone number and so forth has been accumulated, and an array is prepared containing the names, numbered from one to N. A query might be: what is the telephone number for a given name X. To answer this the array would be searched and the index (if any) corresponding to that name determined, whereupon the associated telephone number array would have X's telephone number at that index, and likewise the address array and so forth. If the list of names is in sorted order, a binary search will find a given name with far fewer probes than the simple procedure of probing each name in the list, one after the other in a linear search, and the procedure is much simpler than organizing a hash table. However, once created, searching with a hash table may well be faster, typically averaging just over one probe per lookup. With a non-uniform distribution of values, if it is known that some few items are much more likely to be sought for than the majority, then a linear search with the list ordered so that the most popular items are first may do better than binary search. The choice of the best method may not be immediately obvious. If, between searches, items in the list are modified or items are added or removed, maintaining the required organisation may consume more time than the searches.
Even if we do not know a fixed range the number k falls in, we can still determine its
value by asking
simple yes/no questions of the form "Is k greater than x?" for
40
some number x. As a simple consequence of this, if you can answer the question "Is this integer property k greater than a given value?" in some amount of time then you can find the value of that property in the same amount of time with an added factor of log2k. This is called a reduction, and it is because of this kind of reduction that most complexity theorists concentrate on decision problems, algorithms that produce a simple yes/no answer.For example, suppose we could answer "Does this n x n matrix have determinant larger than k?" in O(n2) time. Then, by using binary search, we could find the (ceiling of the) determinant itself in O(n2log d) time, where d is the determinant; notice that d is not the size of the input, but the size of the output.
In order to discuss the method in detail, a more formal description is necessary. The basic idea is that there is a data structure represented by array A in which individual elements are identified as A(1), A(2),,A(N) and may be accessed in any order. The data structure contains a sub-element or data field called here Key, and the array is ordered so that the successive values A(1).Key A(2).Key and so on. The requirement is that given some value x, find an index p (not necessarily the one and only) such that A(p).Key = x. To begin with, the span to be searched is the full supplied list of elements, as marked by variables L and R, and their values are changed with each iteration of the search process, as depicted by the flowchart. Note that the division by two is integer division, with any remainder lost, so that 3/2 comes out as 1, not 1. The search finishes either because the value has been found, or else, the specified value is not in the list.
41
Figure 5.1 : Flow Chart of Binary Search algorithm 5.3.1 Working The method relies on and upholds the notion If x is to be found, it will be amongst elements (L + 1) to (R 1) of the array. The initialisation of L and R to 0 and N + 1 make this merely a restatement of the supplied problem, that elements 1 to N are to be searched, so the notion is established to begin with. The first step of each iteration is to check that there is something to search, which is to say whether there are any elements in the search span (L + 1) to (R 1). The number of such elements is (R L 1) so computing (R L) gives (number of elements + 1); halving that number (with integer division) means that if there was one element (or more) then p = 1
42
(or more), but if none p = 0, and in that case the method terminates with the report "Not found". Otherwise, for p > 0, the search continues with p:=L + p, which by construction is within the bounds (L + 1) to (R 1). That this position is at or adjacent to the middle of the span is not important here, merely that it is a valid choice. Now compare x to A(p).Key. If x = A(p).Key then the method terminates in success. Otherwise, suppose x < A(p).Key. If so, then because the array is in sorted order, x will also be less than all later elements of the array, all the way to element (R 1) as well. Accordingly, the value of the right-hand bound index R can be changed to be the value p, since, by the test just made, x < A(p).Key and so, if x is to be found, it will be amongst elements earlier than p, that is (p 1) and earlier. And contrariwise, for the case x > A(p).Key, the value of L would be changed. Thus, whichever bound is changed the ruling notion is upheld, and further, the span remaining to be searched is reduced. If L is changed, it is changed to a higher number (at least L + 1), whereas if R is changed, it is to a lower number (at most R 1) because those are the limits for p. Should there have been just one value remaining in the search span (so that L + 1 = p = R 1), and x did not match, then depending on the sign of the comparison either L or R will receive the value of p and at the start of the next iteration the span will be found to be empty. Accordingly, with each iteration, if the search span is empty the result is "Not found", otherwise either x is found at the probe point p or the search span is reduced for the next iteration. Thus the method works, and so can be called an Algorithm. 5.3.2 Speed After each iteration, the span left to be searched is roughly[vague] halved. If the original number of items is N = 2p, then after the first iteration there will be roughly 2p-1 items remaining, then roughly 2p-2, and so on. In the worst case, the algorithm must continue iterating until the span has been reduced to a single item, i.e. 20; this will have taken p = log2(N) iterations. When compared to the linear search, whose worst-case behaviour is N iterations, we see that the binary search is substantially faster as N grows large. In most cases, N will not be an integer power of 2. In these cases, the worst-case iteration count will be ceil(log2(N)), where ceil() denotes the ceiling function.
43
5.3.3 Average performance There are two cases: for searches that will fail because the value is not in the list, the search span must be successively halved until no more elements remain and this process will require at most the p probes just defined, or one less. This latter occurs because the search span is not in fact exactly halved, and depending on the value of N and which elements of the list the absent value x is between, the span may be closed early. For searches that will succeed because the value is in the list, the search may finish early because a probed value happens to match. Loosely speaking, half the time the search will finish one iteration short of the maximum and a quarter of the time, two early. Consider then a test in which a list of N elements is searched once for each of the N values in the list, and determine the number of probes n for all N searches.
Linear Search operates by checking every element of a list one at a time in sequence until a match is found. Linear search runs in O(n). If the data are distributed randomly, the expected number of comparisons that will be necessary is:
where n is the number of elements in the list and k is the number of times that the value being searched for appears in the list. The best case is that the value is equal to the first element tested, in which case only 1 comparison is needed. The worst case is that the value is not in the list (or it appears only once at the end of the list), in which case n comparisons are needed The simplicity of the linear search means that if just a few elements are to be searched it is less trouble than more complex methods that require preparation such as sorting the list to be searched or more complex data structures, especially when entries may be subject to frequent revision. Another possibility is when certain values are much more likely to be searched for than others and it can be arranged that such values will be amongst the first considered in the list.
44
The following pseudo code describes the linear search technique. For each item in the list: Check to see if the item you're looking for matches the item in the list. If it matches. Return the location where you found it (the index). If it does not match. Continue searching until you reach the end of the list. If we get here, we know the item does not exist in the list. Return -1.
Whereas Binary Search uses less number of comparison to get the search done. Linear Search: Worst case performance -- (n) Best case performance -- O(1) Average case performance O(n/2) Binary Search : Worst case performance -- (log n) Best case performance -- O(1) Average case performance -- O(log n) From above mentioned time complexity binary search is far more better than linear search ,thus its being used in our searching module.
45
The electronic dictionary searches any word in its database in less than 0.2 seconds. There is no word meaning mismatch or any other errors in the dictionary. Therefore the electronic dictionary is completely efficient.
46
Its main application is for candidates preparing for exams like GRE, GMAT, CAT . It can be customized for any type of word list which can be helpful to tourists. Can be used for developing a good vocabulary.
Word
Abhor Abjure Abnegate Abominable Abrogate Abscission Absolve Abysmal Accede Accoutrement
Meaning
Detest Renounce Give up Bad Abolish Separation Pardon Dismal Proposal Paraphernalia
47
Accrue Acerbity Acrid Actuarial Adage Addendum Addled Adept Adjure Admonish Adroit Advert Aerie Affable Affected Agility Agog Alacrity Alcove Alfresco Allay Allegiance Allure Aloof Amble Ambulatory Ameliorate Amiable
Accumulate Harshness Sharp Calculating Saying Addition Not fresh Expert at Exhort Rebuke Adept Refer to Eyrie Pleasant Mannered Nimbleness Curious Promptness Recess Outdoor Calm Loyality Attract Reserved Stroll Walking Improve Polite
48
Amorous Amulet Anguish Annals Anomaly Antediluvian Aphorism Apostate Apothegm Apparition Appellation Apprehend Argot Articulate Artless Askew Asperity Assay Assent Assiduous Astute Atone Aureole Austere Avarice Aversion Awry Bacchanalian
Loving Charm Pain Records Oddity Ancient Maxim Defector Adage Ghost Epithet Grasp Slang Speak Ingenious Awry Sharpness Analyze Agree Diligent Wise Expiate Halo Strict Cupidity Revulsion Not straight Drunken
49
Bait Bane Bard Bauble Bawdy Beatific Bedlam Beholden Bellicose Benevolent Beseech Besmirch Blandishment Blasphemy Bolster Boorish Botch Bromide Bugaboo Byzantine Dally Dank Debacle Decoy Deleterious Delude Demented Demotic
Harass Curse Poet Trinket Obscene Blissful Chaos Obligated Warlike Generous Entreat Defile Flattery Profanity Support Rude Mess Platitude Bugbear Complicated Procrastinate Damp Fiasco Lure Harmful Deceive Insane Colloquial
50
Demur Deride Desecrate Despot Destitute Detrimental Diabolical Diadem Diatribe Dictum Dingy Disaffected Disband Discern Disgorge Dissuade Distill Divulge Dregs Drivel Droll Dross Facetious Faction Falter Fatuous Fetter Febrile
Hesitate Ridicule Defile Dictator Poor Harmful Devilish Crown Invective Saying Dull Disloyal Separate Know Vomit Discourage Refine Reveal Sediment Nonsense Funny Garbage Humorous Opposition Hesitate Foolish Shackle Nervous
51
Fecundity Feign Fiat Filch Filial Finicky Fissure Flaccid Flag Flay Flounder Flux Foment Forbearance Fortitude Foster Fracas Frail Fraught Fugitive Furtive Gag Gamely Gamut Gaunt Garish Garner Garrulous
Fertility Pretend Command Steal Duties Fussy Crevice Weak Droop Criticize Hesitate Flowing Incite Patience Bravery Encourage Melee Weak Filled Evanescent Surreptitious Joke Resolutely Range Angular Gaudy Granary Talkative
52
Genial Germane Giddy Glower Glut Gnarled Goad Gratis Gravity Grisly Grouch Gruff Grumpy Guffaw Gully Gusto Haughty Hegemony Hermetic Hiatus Horrendous Hubris Humdrum Humility Hummock Jaunt Jejune Jeopardize
Amiable Apposite Dizzy Glare Surplus Knotted Stimulate Free Enormity Ghastly Complaint Impatient Gruff Chortle Ravine Zest Arrogant Dominance Closed Gap Terrible Pride Monotonous Humbleness Knoll Trip Dull Imperil
53
Jibe Jocose Jocund Kindle Knave Labile Languid Larceny Lax Lechery Leery Levity
Gibe Humorous Enjoying Motivate Dishonest Unstable Weary Theft Careless Lustfulness Wary Frivolity
#include <avr/io.h> #include <avr/interrupt.h> #include <avr/stdint.h> #include <avr/math.h> #include <avr/lcd.h>
54
#define BIT0 0x01 #define BIT1 0x02 #define BIT2 0x04 #define BIT3 0x08 #define BIT4 0x10 #define BIT5 0x20 #define BIT6 0x40 #define BIT7 0x80 #define CHECKBIT(x,b) #define SETBIT(x,b) #define CLEARBIT(x,b) #define TOGGLEBIT(x,b) #define TOTAL 50 (x&b) x = x|b; x = x&(~b); x = x^b;
unsigned char flag_error=1; //const char *words[TOTAL]={"AB","ABACUS","BOY","MS","dog","fiscal"}; //const char *meaning[TOTAL]={"ab1","abacus2","boy3","Manish Sharma","dog5","fiscal6"}; const char *words[TOTAL]={"ABERRANT","ABET","ABHOR","ABJURE","ABNEGATE","AB ORGATE","ABSCISSION","ABSCOND","ABSOLVE","ABYSMAL","ACCEDE","AC CESSORY","ACCURE","ACRID","ADAGE","ADDENDUM","ADJURE","ADJUTAN T","ADMONISH","ADROIT","ADVERT","AFFABLE","AFFECTED","AFFRONT","A CLOVE","ALFRESCO","ALLAY","ALLEVIATE","ALLUDE","ALLURE","ALOOF"," AMBLE","AMELIORATE","AMIABLE","ANGUISH","ANNALS","ANOMLY","ANT EDILUVIAN","APOTHEGM","APPARITION","APPELATION","APPREHEND","ART LESS","ASSAY","ASSIDUOUS","AUGMENT","BAFFLE","BALEFUL","BARD","BE DRAGGLED"}; const char *meaning[TOTAL]={"abnormal","to make sb to do wrong","to hate","renounce","to give up","abolish","separation","to escape","to pardon","dismal","to agree a proposal","accomplice","accumulate","sharp","wise saying","addition","exhort","assistant","rebuke","adept","refer to","pleasant","mannered","to insult","recess","outdoor","calm","relive","refer indirectly","to attract","reserved","stroll","improve","polite","accute pain","historical records","oddity","extremely ancient","adage","ghost","thing or place","to
55
understand","honest","analyze","dilligent","suplement","confuse","sinister","poet","made wet"};
int mycmp(const char *ch1,const char *ch2) { unsigned char i=0; while((*(ch1+i)==*(ch2+i))&& *(ch1+i)!='\0') { i++; } return (*(ch1+i)- *(ch2+i)); }
int binary_search(const char *cmp) { int min=0,max=TOTAL-1; int flag=1,pointer; while(flag) { pointer=(min+max)/2; flag=mycmp(words[pointer],cmp); if(flag==0) break; else if(flag<0) { min=pointer+1; } else { max=pointer-1; }
56
int getkey() { //PORTD=0x0f; SETBIT(PORTD,BIT0); while(1) { // to stop mcu reading the i/p several times in a one go { if(CHECKBIT(PIND,BIT7) && !CHECKBIT(PINA,BIT0)) { return 1; } else if(CHECKBIT(PIND,BIT7) && CHECKBIT(PINA,BIT0)) { return 2; } else if(CHECKBIT(PIND,BIT6) && !CHECKBIT(PINA,BIT0)) { return 3; } else if(CHECKBIT(PIND,BIT6) && CHECKBIT(PINA,BIT0)) { return 4; }
57
else if(CHECKBIT(PIND,BIT5) && !CHECKBIT(PINA,BIT0)) { return 5; } else if(CHECKBIT(PIND,BIT5) && CHECKBIT(PINA,BIT0)) { return 6; } else if(CHECKBIT(PIND,BIT4) && !CHECKBIT(PINA,BIT0)) { return 7; } else if(CHECKBIT(PIND,BIT4) && CHECKBIT(PINA,BIT0)) { return 8; } //else continue; } CLEARBIT(PORTD,BIT0); SETBIT(PORTD,BIT1); //WaitMs(100); { if(CHECKBIT(PIND,BIT7) && !CHECKBIT(PINA,BIT0)) { return 9; } else if(CHECKBIT(PIND,BIT7) && CHECKBIT(PINA,BIT0)) { return 10;
58
} else if(CHECKBIT(PIND,BIT6) && !CHECKBIT(PINA,BIT0)) { return 11; } else if(CHECKBIT(PIND,BIT6) && CHECKBIT(PINA,BIT0)) { return 12; } else if(CHECKBIT(PIND,BIT5) && !CHECKBIT(PINA,BIT0)) { return 13; } else if(CHECKBIT(PIND,BIT5) && CHECKBIT(PINA,BIT0)) { return 14; } else if(CHECKBIT(PIND,BIT4) && !CHECKBIT(PINA,BIT0)) { return 15; } else if(CHECKBIT(PIND,BIT4) && CHECKBIT(PINA,BIT0)) { return 16; } } CLEARBIT(PORTD,BIT1); SETBIT(PORTD,BIT2); //WaitMs(100);
59
{ if(CHECKBIT(PIND,BIT7) && !CHECKBIT(PINA,BIT0)) { return 17; } else if(CHECKBIT(PIND,BIT7) && CHECKBIT(PINA,BIT0)) { return 18; } else if(CHECKBIT(PIND,BIT6) && !CHECKBIT(PINA,BIT0)) { return 19; } else if(CHECKBIT(PIND,BIT6) && CHECKBIT(PINA,BIT0)) { return 20; } else if(CHECKBIT(PIND,BIT5) && !CHECKBIT(PINA,BIT0)) { return 21; } else if(CHECKBIT(PIND,BIT5) && CHECKBIT(PINA,BIT0)) { return 22; } else if(CHECKBIT(PIND,BIT4) && !CHECKBIT(PINA,BIT0)) { return 23; }
60
//WaitMs(100); { if(CHECKBIT(PIND,BIT7) && !CHECKBIT(PINA,BIT0)) { return 25; } else if(CHECKBIT(PIND,BIT7) && CHECKBIT(PINA,BIT0)) { return 26; } else if(CHECKBIT(PIND,BIT6)) { return 27;//backspace } else if(CHECKBIT(PIND,BIT5)) { return 28;//enter } else if(CHECKBIT(PIND,BIT4)) { return 29;//reset program
61
} CLEARBIT(PORTD,BIT3); SETBIT(PORTD,BIT0); } } }
62
return 0; }
//for microcontroller 1 void uart0_init(void) { UCSRB = 0x00; //disable while setting baud rate UCSRA = 0x00; UCSRC = BIT(URSEL) | 0x06; UBRRL = 0x33; //set baud rate lo UBRRH = 0x00; //set baud rate hi UCSRB = 0x98; } //************************************************** //Function to receive a single byte //************************************************* unsigned char receiveByte( void ) { unsigned char data, status; while(!(UCSRA & (1<<RXC))); // Wait for incomming data status = UCSRA; data = UDR; return(data); } //*************************************************** //Function to transmit a single byte //*************************************************** void transmitByte( unsigned char data ) { while ( !(UCSRA & (1<<UDRE)) ); //Wait for empty transmit buffer UDR = data; //Start transmition }
63
//*************************************************** //Function to transmit a string stored in Flash //*************************************************** void transmitString_F(const unsigned char* string) { while (*string) transmitByte(*string++); }
//*************************************************** //Function to transmit a string from RAM //*************************************************** void transmitString(unsigned char* string) { while (*string) transmitByte(*string++); } //******************** END ******************** int main() { avr_init(); int ch; char str[16]=""; int point=0; char no; DDRB = 0xFF; DDRD = 0x0F; DDRA = 0x00; //PORTA= 0x00;
64
unsigned char i=0; if(flag_error) { lcd_cmd(0x01); lcd_string("E DICTIONARY"); WaitMs(1000); lcd_cmd(0x01); } while(1) { str[0]='\0'; point=0; lcd_cmd(0x01); while(flag_error) { ch=getkey(); WaitMs(100); if(ch==1) { str[point]='A'; lcd_char('A');
65
} if(ch==3) { str[point]='C'; lcd_char('C'); point++; } if(ch==4) { str[point]='D'; lcd_char('D'); point++; } if(ch==5) { str[point]='E'; lcd_char('E'); point++; } if(ch==6) { str[point]='F'; lcd_char('F'); point++; } if(ch==7) { str[point]='G'; lcd_char('G');
66
point++; } if(ch==8) { str[point]='H'; lcd_char('H'); point++; } if(ch==9) { str[point]='I'; lcd_char('I'); point++; } if(ch==10) { str[point]='J'; lcd_char('J'); point++; } if(ch==11) { str[point]='K'; lcd_char('K'); point++; } if(ch==12) { str[point]='L';
67
lcd_char('L'); point++; } if(ch==13) { str[point]='M'; lcd_char('M'); point++; } if(ch==14) { str[point]='N'; lcd_char('N'); point++; } if(ch==15) { str[point]='O'; lcd_char('O'); point++; } if(ch==16) { str[point]='P'; lcd_char('P'); point++; } if(ch==17) {
68
str[point]='Q'; lcd_char('Q'); point++; } if(ch==18) { str[point]='R'; lcd_char('R'); point++; } if(ch==19) { str[point]='S'; lcd_char('S'); point++; } if(ch==20) { str[point]='T'; lcd_char('T'); point++; } if(ch==21) { str[point]='U'; lcd_char('U'); point++; } if(ch==22)
69
{ str[point]='V'; lcd_char('V'); point++; } if(ch==23) { str[point]='W'; lcd_char('W'); point++; } if(ch==24) { str[point]='X'; lcd_char('X'); point++; } if(ch==25) { str[point]='Y'; lcd_char('Y'); point++; } if(ch==26) { str[point]='Z'; lcd_char('Z'); point++; }
70
else if(ch==27) { //command to backspace on lcd; //printf("\b%c\b",' '); point--; lcd_gotoxy1(point); lcd_char(' '); lcd_gotoxy1(point); } else if(ch==28) { lcd_cmd(0x01); str[point]='\0'; lcd_string("Searching..."); no=binary_search(str); //lcd_showvalue(no); WaitMs(200); //if(no<0) if(no>TOTAL) { lcd_cmd(0x01); lcd_string("NOT FOUND"); WaitMs(1000); break; //command to print word not found //printf("\n%s not found",str); } else
71
{ //command to print on lcd the meaning //printf("\n %s",meaning[no]); lcd_cmd(0x01); PORTB=0xff; SETBIT(PORTB,BIT0); lcd_string(meaning[no]); WaitMs(2000); CLEARBIT(PORTB,BIT0); PORTB=0x00; break; // printf("\n"); } break; } else if(ch==29) { break; }
else { continue; } }
} while(1); return 0;
72
//for microcontroller 2 void uart0_init(void) { UCSRB = 0x00; //disable while setting baud rate UCSRA = 0x00; UCSRC = BIT(URSEL) | 0x06; UBRRL = 0x33; //set baud rate lo UBRRH = 0x00; //set baud rate hi UCSRB = 0x98; } //************************************************** //Function to receive a single byte //************************************************* unsigned char receiveByte( void ) { unsigned char data, status; while(!(UCSRA & (1<<RXC))); // Wait for incomming data status = UCSRA; data = UDR; return(data); } //*************************************************** //Function to transmit a single byte //*************************************************** void transmitByte( unsigned char data ) { while ( !(UCSRA & (1<<UDRE)) ); //Wait for empty transmit buffer UDR = data; //Start transmition }
73
//*************************************************** //Function to transmit a string stored in Flash //*************************************************** void transmitString_F(const unsigned char* string) { while (*string) transmitByte(*string++); } //*************************************************** //Function to transmit a string from RAM //*************************************************** void transmitString(unsigned char* string) { while (*string) transmitByte(*string++); } //******************** END ******************** void main() { DDRD=0xff; PORTD=0xff; DDRC=0xff; PORTC=0xff; WaitMs(100); PORTC=0x00; DDRD=0x00; while(1) { if(CHECKBIT(PIND,BIT6)) { PORTC=0xff; }
74
else {PORTC=0x00;} }}
1. WIN AVR Complier for AVR Microcontroller C programs. 2. AVR Studio Integrated Development Environment for AVR. 3. Pony Prog For programming the Atmega32L using USB port.
75
REFERENCES
Books:
1. Embedded C Programming and the Atmel AVR, 2nd Edition Barnett. Cox and
OCull
2. Programming and Customizing the AVR Microcontroller Dhananjay V. Gadre
Internet:
1. http://www.dharmanitech.com/
1. http://www.scienceprog.com/connect-lcd-to-atmega-using-3-wires/ece-wise
1. http://extremeelectronics.co.in/avr-tutorials/using-the-usart-of-avr-
Microcontrollers that use the Harvard architecture have separate memory buses for instructions and data, allowing accesses to take place concurrently. This architecture can improve performance by enabling simultaneous instruction and data fetching. In contrast, other designs may share a single bus for both instructions and data, which could result in slower data processing. The Harvard architecture's separation typically results in faster execution, particularly in applications where instruction and data manipulation are intensive .
In-circuit programming and debugging support enable developers to program and troubleshoot microcontrollers while they remain in their operational circuits. This reduces development time by allowing for easy updates and diagnostics without requiring physical removal from the board, facilitating a quicker and more efficient development cycle .
Non-volatile memory in microcontrollers provides storage for programs and operational parameters. Common types integrated into microcontrollers include ROM, EPROM, EEPROM, and Flash memory. These memory types retain information even when the power is off, ensuring critical data for the system's operation is preserved across power cycles .
Microcontrollers often include dedicated instructions for bit-wise operations, enabling compact and efficient control programs. In contrast, general-purpose processors might require multiple instructions to perform similar operations. This design choice is significant for control applications as it directly improves performance and reduces code size, which is essential for systems with limited memory and processing capabilities .
Pulse Width Modulation (PWM) in embedded systems is used to control power devices such as converters and motors with high efficiency. By adjusting the width of the pulse, PWM allows for precise control of device operation without burdening the CPU with constant intervention via tight timing loops. Applications include adjusting the speed of an electric motor, dimming an LED, and controlling the power output of DC-DC converters .
Inclusion of various serial communication interfaces, such as UART, I²C, and SPI, greatly enhances a microcontroller's usability by enabling connections to different peripherals and systems. These interfaces allow microcontrollers to adapt to various communication needs, from long-distance data transmission to short-range sensor data acquisition, thereby extending their application across numerous industrial, consumer, and automotive systems .
Embedded systems handle analog input data using analog-to-digital converters (ADC). These converters transform analog signals from devices into digital data that the processor can interpret and process. Since processors operate on digital data, the ADC is crucial for converting varying analog signals into a binary form, allowing the embedded system to interact meaningfully with its environment .
Programming microcontrollers in assembly language allows for granular control over hardware resources, optimizing performance and memory usage. However, it is complex and error-prone, limiting portability and developer productivity. High-level languages, such as C, simplify code writing and maintenance, increase portability, and reduce error incidence, though they might not achieve the same performance efficiency as carefully optimized assembly code .
The Programmable Interval Timer (PIT) in embedded systems counts down from a pre-set value to zero, issuing an interrupt when it finishes counting. This interrupt can trigger events in the system, such as measuring temperatures at set intervals for a thermostat, thus aiding in automating control applications without needing constant monitoring from the CPU. This functionality is essential for time-critical control applications .
Integrating peripherals on a microcontroller chip reduces the number of chips required, which allows for a smaller and cheaper circuit board. This reduction in complexity also decreases the labor required to assemble and test the circuit, leading to potential cost savings. Although the cost of a microcontroller with integrated peripherals may be slightly more than a separate CPU and external peripherals, the overall system cost often decreases due to the fewer components and smaller board size required .