Showing posts with label avr. Show all posts
Showing posts with label avr. Show all posts

Part 2 of 3 Using AVR Microcontroller for Projects

Tuesday, 25 June 2013
Part 2 of 3
Using AVR Microcontroller for Projects
 
In the first part of this article, we had described the main features of the AVR microcontroller and the hardware/software required for an AT-PROG programmer board interfaced to the printer port of a PC. Further, we explained the methods for message display on a liquid crystal display (LCD).

This part dwells on the architecture of ATmega8535 along with application programs exploiting its important features for embedded control.

Architecture of ATmega8535

Pin configuration of ATmega8535 was shown in Fig. 1 of Part 1. The device has ports for input/output, interrupts, serial communication and various others functions. There are a total of 32 pins, which are arranged as ‘A,’ ‘B,’ ‘C’ and ‘D’ ports for various functions as shown in Table I.

A crystal of maximum 16MHz or 8MHz frequency can be connected across pins 12 and 13 of ATmega8535 or its low-voltage version ATmega8535(L), respectively. Pin 9 serves as the active-low reset pin.
The non-volatile program and data memories built into ATmega8535 are:
1. 8 kB of self-programmable flash for storing the software code of the application program.
2. 512 bytes of SRAM, which is a read/write memory.
3. 512 bytes of EEPROM for storing the data.  Unlike the flash memory, it can be accessed in a program for writing and reading.

Programming the on-chip code/program memory
The on-chip flash memory is programmed by pulling up the reset pin and sending data through pins 6 (MOSI) and 7 (MISO), and pin 8 (SCK), which is used for clocking the the code data into the flash memory. This is accomplished by the host computer by sending appropriate instructions and the code bytes; data verification is done by reading the flash memory and comparing it with the original code data. Writing the lock bits to prevent reading of the code in the chip is accomplished through the instructions and the relevant data.

Fig. 11: Circuit diagarm of real-time clock
For using the AVR device, these instructions are built into the ATPROG program (explained in Part I), which is run on the host PC.

Selection of clock. There are some additional fuse bits, which can be programmed for some extra operational functions. Note that the AVR device, as shipped, is preset to work at 1 MHz with its internal oscillator. If you want to use an external crystal, say, of 8MHz frequency, you have to exercise this option by programming the fuse bits accordingly. A fuse bit is just like a flash code memory location.

The CKSEL fuse bits can be programmed to select the desired crystal. The device clocking options are selectable by Flash Fuse bits as shown in Table II. The clock from the selected source is input to the AVR clock generator and routed to the appropriate modules.

Since the default oscillator is 1MHz, unless we set the CKSEL bits to an appropriate value, the external crystal on pins 12 and 13 will not function for ATmega8535.



Fig. 12: Bit description for status register; I-global interrupt-enable bit, T-T bit copy storage, H-half carry flag, S-sign bit, V-overflow in 2’s complement arithmetic, N-negative number flag (2’s complement arith.), Z-zero flag, C-carry flag

Programming the fuse bits. The fuse bit programming option is available on the screen when the AT-PROG is run on the PC. When this option is selected, it pops up a menu of its own. On this menu, you can write the necessary code for CKSEL programming. (Details of programming the fuse bits, lock bits and other options like boot memory option are given on pages 236 and 252 of the ATmega8535(L) manual provided in the EFY-CD of Nov. 2005.)

Internal registers. Six of the 32 registers can be used as three 16-bit indirect address register pointers for data space addressing, enabling efficient calculations. One of three address pointers (X, Y and Z registers, described under ‘register operations’ section) is also used for table look-up.

The I/O memory space contains 64 addresses for CPU peripheral functions like control registers, timers/counters and analogue-to-digital converter (ADC). It can be accessed directly or as the data space locations following those of the register files, i.e., after ‘20H’ and up to ‘5FH.’

The memory space contains important registers for use in interrupt selection, timer control, UART, SPI interface, watchdog and reset selection modes, etc. Table III shows the exact addresses of these I/O registers.

The bit description for the status register (SREG) is shown in Fig. 12.


Instruction set for ATmega8535
The instruction set comprises several arithmetic, logical, branch and bit-test type instructions. You can download a 150-page user manual for the AVR instruction set from Atmel’s site‘www.atmel.com/dyn/resources/prod_documents/doc0856.pdf.’ A summary of the instruction set is given on pages 299 through 301 of the Atmega8535(L) datasheet.

Some of the important instructions are given in Table IV.
Points to be noted
1. When the relative call or jump instruction is executed, the entire memory address space can be accessed.
2. During interrupts and subroutine calls, the return address value is stored in the stack space, which is to be defined by the user at the beginning of every program in SRAM space.
3. The 16-bit stack pointer is read-/write-accessible in the I/O space.
4. The 512-byte data RAM is easily accessed through five different addressing modes supported.
5. A flexible interrupt module has its control registers in the I/O space with an additional global interrupt enable bit in the status register. Every interrupt has a separate address for vectoring, where the instruction causing it to jump to the memory area of that particular interrupt has to be kept stored by the programmer.

There are many interrupts available in ATmega8535. In order to use any interrupt, you need to place the address of the program of the respective interrupt service routine at the vector address.


Fig. 13: Bit details for TCCR0 register; bits 0, 1 and 2 are defined in Table IV reproduced from the original datasheet


Fig. 14: Bit details for TIMSK register


From location ‘001H’ to ‘014H, ’there are 20 such interrupt vector locations in the order of their priority. Address ‘000H’ is used for the reset vector. A reset may be caused by power-on reset, brownout reset and watchdog reset, or externally by making pin 9 low. Table 19 on page 45 of the datasheet lists the details of reset and interrupt vectors.

Note that here we are dealing with word addresses, so each location is actually two bytes long. In this twobyte location, if you place a RETI (return from interrupt) instruction, nothing will be done upon that interrupt. For example, if you place a jump instruction to the required routine, you can write:

rjmp timer_routine                         

Then you can use that interrupt to jump to the timer_routine.

As mentioned above, the interrupt vectors follow the reset address at ‘000H,’ wherein a jump instruction to the corresponding actual memory addresses, defined by the labels, is placed. For example, the instruction:

RJMP Int0                                    

It means that the external interrupt routine has the label ‘Int0,’ to which the processor jumps upon pin 17 getting a high logic signal. Also, at the label ‘Int0,’ if a simple return instruction is entered as:

Int0:   reti                                    


This instruction simply ignores such an interrupt and returns to the main program. In case you need to process the interrupt, enter the necessary code starting at label ‘Int0.’

After the interrupt processing instructions, the various subroutines are entered. Then comes the main program. In the main program, the first thing to write is the stack initialisation instructions. Here, the stack pointer is set to the highest end of the internal RAM, for which a temporary register is used, and the high and low addresses are written to the stack pointer using an instruction at the Ext_Int0 vector address (0x001) such as:
ldi temp,low(RAMEND)
out spl,temp               
 ldi temp,high(RAMEND)  outsph,temp      






Register operations. Each register is assigned a data memory address, mapping it directly into the first 32 locations of the data space. Register pairs R26-R27, R28-R29 and R30-R31 serve as 16-bit registers, which are used for indirect addressing of the data memory space. These three 16-bit registers are known as ‘X’ (R27:R26), ‘Y’ (R29:R28) and ‘Z’ (R31:R30) registers, respectively. The last 16 registers in the register file (R16 through R31) cannot be used with the first 16 registers (R0 through R15).

The operating instructions for registers have direct and single-cycle access to the registers. The following instructions—constant arithmetic instructions—use the second half of the registers in the register file and cannot be used with the first half:

sbci, subi, cpi, andi, ori and ldi         

The following general instructions that use two registers or only a single register can use the entire register file:

Sbc, sub, cp and & or                    

Embedded control functions and their applications
Here we’ll use the following four functions of ATMega8535 for typical control applications:
1. Timers; two 8-bit and one 16-bit with add-on features
2. Pulse-width modulated output
3. Analogue-to-digital converter
4. Serial RS-232 interface

Timers and their applications. Both timer 0 and timer 1 are 8-bit timers, while timer 1 is a 16-bit timer. The clock inputs to the timers can have a variety of selections.  The CPU clock itself, divided by a prescaling divider with divisors of 8, 64, 256 and 1024, can be chosen.  Further, it can also count an externally applied clock at T1 pin (for timer 1).

We shall use these timers for developing a real-time clock with time display on the LCD (see Fig. 1). For the purpose, the registers to be used in timer 0 are:
1. TCCR0: Timer counter control register 0
2. TIMSK: Timer interrupt mask register

TCCR0 register bits. Fig. 13 shows the bit details for TCCR0 register. Bits WGM01, COM00, COM01, WGM00 and FOC0 (bits 3 through 7) of TCCRO register are used with the timer-based comparators for waveform and pulsewidth-modulated output generation. Since these bits are not required for the normal timing operation of the timer, they have not been used here.

The timer clock is selected by using the remaining three bits (CS00, CS01 and CS02). We will set these bits to ‘0,’ ‘1’ and ‘1,’ respectively, for dividing the 1MHz default internal clock of ATmega8535 k (with no external crystal) by ‘64.’ This division gives 65 microseconds per clock. Then we accumulate the counts for getting one second and divide it by ‘60’ to get minutes and again by ‘60’ to get hours, which are counted up to ‘12’ and the process is repeated.

TIMSK register bits. Fig. 14 shows the bit details for TIMSK register. Bit 0 refers to ‘timer-overflow interrupt enable.’ It must be set to enable the interrupt action on overflow. The TIMO_OVF interrupt ($0009 address) is used to direct a vector at this address to the respective interrupt service routine, where we will perform the relevant action that is needed upon timer-0 overflowing, i.e., when the number in its TCNT0 register (timer counter 0) crosses ‘255’ (decimal). So in the software program for real-time clock, we initialise TIMSK to ‘01.’

Software program for real-time clock (8535clk.asm). The 8535clk.asm program with suitable explanations and comments is given at the end of this article. The assembled hex file ‘8535clk.hex’ is included in this month’s EFY-CD, which can be straightaway programmed in the ATmega8535 IC. The programmed IC can be fixed to the RTC circuit board to show real-time clock on the LCD.

Source Code
 
Read more ...

Part 1 of 3 USING AVR MICROCONTROLLERS FOR PROJECTS

Tuesday, 25 June 2013
Part 1 of 3
USING AVR MICROCONTROLLERS FOR PROJECTS
The AVR 8535 microcontroller and its new version ATmega8535 are versatile, high-performance but low-cost chips. This article series covers typical applications of this processor illustrating its power and cost-effectiveness in an embedded system.

The AVR family comprises several chips, all with almost the same instruction set. Of them, the 90S8515, 90S8535 and ATmega8535 chips are low-cost and readily available with the complete set of port pins. The ATmega8535-16 is more powerful and available for around Rs 250. Capable of running at 16 MHz and achieving almost 16 million instructions per second (MIPS), it is one of the fastest devices available in the market today.

Fig. 1: Pin configuration of ATmega8535


Fig. 2: A simple LED display circuit using ATmega8535

Using ATmega8535, you can build a microcontroller-based project with following features:
1. Four ports, of which one of them has eight analogue-to-digital converter (ADC) channels
2. ADC conversion time is as little as 60 microseconds. Imagine adding an external ADC to 8051 or any other microcontroller chip—that would have taken the cost to over four digits. And mind you, it is a 10-bit ADC, not just 8-bit.
3. If an 8MHz crystal is connected, each instruction executes in 1/8th of a microsecond. The 89C51 at 12MHz clock had its internal division by twelve, so it ran at just one microsecond. Thus, ATmega8535 chip is eight times faster with an 8MHz crystal. However, you can also use a higher-frequency crystal. The chip is basically a RISC processor that executes most instructions in one clock cycle itself.
4. The chip has RS-232 transmit and receive terminals much like the 8051 family, but it can support even higher baud rates.
5. It has quite a few internal registers, RAM, EEPROM and CODE memory (flash memory in excess of 4kB).
6. The instruction set is versatile, complete with several arithmetic, logic and transfer instructions and related jump instructions, etc.
7. An analogue comparator pin, which can compare an external analogue voltage and take control action.
8. Reset is possible through the software, and a watchdog is provided. Power-down or sleep modes are available.
9. An additional serial interface, known as the SPI bus, with three wires: data (2) and clock (1). These pins can be used for programming or loading the code from a PC through the printer port or serial port. For programming the internal flash memory locations, just 5V supply is enough.
10. Two PWM output pins, which are useful for power control applications.
11. Several timers as in other members of the 8051 family, but with much better time resolution.
12. Additional features like input capture and output compare.

Here, we shall delve into the chip’s operations with typical programs and circuits. All the development tools including ‘C’ compiler are available for free from the Internet.

The features of ATmega8535 make it the right candidate for various embedded control applications. Even a digital filter can be implemented on the device, provided you are fully conversant with its hardware and software features. You can download the databook of ATmega8535 from the ‘ATMEL.com’ Website to understand its features and work out simple applications.

The sample programs given here can be used to yield a powerful controller for many applications like a filter or motor controller.

Programming the chip

The AVR source code file with ‘.asm’ extension can be written using either the EDIT, Wordpad or notebook programs.

As with all microprocessor or microcontroller programs, for the source code, one has to enter the program by mnemonics and assembler directives and then convert the same into a code list for the program. (Directives are assembler commands used to control the input, output and data allocation of the assembler. These are, however, not translated into op-codes directly.) This is done using the cross-assembler software ‘avrasm.exe.’


Fig. 3: Circuit diagram of AVR programmer (Pod)
To describe the modus of writing of an Assembly language program, a simple program (LED.ASM) for AVR processors is given below:


This program helps you understand:
1. Access to the output port (here port B, where LEDs are connected)
2. The different parts of a typical assembler program
3. Different conventions like use of semicolon, upper-/lower-case letters, etc

Explanatory notes for LED.ASM
1. In Assembly language, all the text on a line after a semicolon (;) is treated by the cross-assembler as comments and it does not use it for code formation.

2. Including the m8535def.inc processor-specific file in Assembly program means all the I/O register names, I/O register bit names, etc appearing in the datasheet can be used. Failure to include this file may result in a number of error messages. Ensure that this file is placed in the same directory as your source code file (LED.asm in this case). Else, give complete path for the m8535def.inc file.

3. Following conventions havebeen used in the program:
(a) Words in upper-case letters are used for command directive words of the Assembly language or predefined ports of the processor.
(b) Mnemonic words are written in lower case.

4. LIST directive turns on the listing output if it had been previously turned off. Similarly, NOLIST directive, if used, will turn off the listing output.

5. DEF directive is used to define a text-substitution label for a string. A label/name is easy to remember. Here, register R16 is replaced with ‘mp’ name. Thus whenever ‘mp’ is encountered in the source code, it will be automatically replaced with ‘R16.’

Fig. 4: Screenshot of AVR-Programmer


Fig. 5: Screenshot of AVR-Programmer showing activity window
6. ‘.org $0000’ defines the reset address. When power is switched on, the program starts from this location. A restart from the reset address can be activated by resetting the respective hardware pin of the chip (pin 9) or upon watchdog timer reaching its zero count. A relative jump command (rjump) at this reset location directs the program execution to label (main)—as long as the label is within 2k locations from the reset address (0000). Incidentally, ‘rjmp main’ is the first code-generating instruction.

7. It is essential to set up the stack pointer before being able to call any subroutine, since stack is required for saving the return address, where the next program execution is to start from. The program lines starting with ‘ldi R16,low(RAMEND)’ and ending with ‘out SPH, R16’ do just that.

8. The ‘ldi mp, 0b11111111’ and ‘out DDRB, mp’ lines set port-B pins as the output. The first line, interpreted as ‘load immediate (ldi) into register ‘mp’’, loads binary value ‘11111111’ into the ‘mp’ register. The second line transfers the contents of ‘mp’ (11111111) to the data direction register of port B (DDRB). DDRB is already defined in the m8535def.inc file. (If you want to set port-B pins as input, load binary ‘00000000’ into ‘mp’ and output it to DDRB.) Incidentally, ‘0b’ precedes a binary number. Similarly ‘0x’ precedes a hex number. Numbers without these prefixes denote decimal numbers by default. Hence you may replace ‘0b11111111’ with either ‘0xFF’ or simply ‘255’ to achieve the same results.

Fig. 6: Circuit for message display on the LCD

9. The rest of the program starting at label ‘loop:’ and ending with ‘rjmp loop’ achieves switching on and off of the LEDs with a delay. The delay subroutine starting at label ‘delay:’ and ending with return instruction ‘ret’ is called from within the loop.

Initially, ‘mp’ is loaded with hex value ‘00’ and output through port-B pins, making them low. Since the cathodes of all the eight LEDs are connected to these port pins via current-limiting resistors, the LEDs light up. Thereafter, the delay subroutine (Rcall delay) is called and ‘mp’ is loaded with hex value ‘FF’ and transferred to the port-B output to turn off the LEDs. The loop is repeated as long as the power is switched on.

10. The internal R-C clock of ATmega8535 is 1 MHz by default. In the absence of ‘Rcall delay’ instruction, each of ‘ldi’ and ‘out’ instructions requires 1000 ns, while ‘rjmp’ instruction requires 2000 ns. Thus loop execution would take 4000 ns. This amounts to LED switching rate of 250 kHz.

Introduction of delay between switching on and off reduces this frequency to around 0.5 Hz by decrementing registers ‘r19’ and ‘r17’ from ‘255’ to ‘0,’ thereby making the elapsed time slower by 256×256 (which works out to around 0.5Hz rate).

After assembling the LED.asm source file, the program will have eight words. The LED.LST file stores the result of the assembly process in the form of a listing.

Once a program has been written using any editor, wordpad or notepad, it is assembled using the avrasm.exe AVR assembler, which is included in this month’s EFY-CD. Of course, the AVRSTUDIO 4.0 integrated development environment (IDE) is more versatile and user-friendly software for development, but the avrasm.exe assembler is simpler and direct.

Simply typing ‘avrasm -i LED.asm LED.lst LED.hex’ under the DOS prompt makes the cross-assembler generate code for the LED.hex file and also provide a text file giving both the code and the program together in LED.lst. Thus, you get the LED.lst listing file and the LED.hex Intel hex code file.

Fig. 7: Actual-size, single-side PCB layout for AVR
programmer (Pod

Fig. 8: Component layout for the PCB in Fig. 7

Fig. 9: Actual-size, single-side PCB layout for
message display on LCD

Fig. 10: Component layout for the PCB in Fig. 9
http://adf.ly/R66qb
Alternatively, you can prepare a batch file as follows:
Upon DOS prompt, enter ‘copy con avr.bat.’ In the following line, type ‘Avrasm -i %1.asm %1.lst %1.hex.’ Pressing ‘F6’ key in the following line displays ‘Control-Z.’ Now pressing the ‘Enter’ key displays “1 file copied.”

Now the avr.bat file has been prepared. This simple batch file is invoked to assemble this (or any) program by typing ‘Avr LED’ upon the DOS prompt and pressing the ‘Enter’ key.

This assembles the program, and forms both the list file (that contains the code-cum-Assembly listing) and the hex file (the actual Intel-format hex file for use by the programmer).

Likewise, any other assembly program ‘xxx.asm’ can be coded into the hex file by simply typing ‘avr xxx’ on DOS prompt. ‘xxx’ denotes the name of the program. The ‘.asm’ is not to be typed.

In our LED.asm program, we have included the m8535def.inc file. This file is required along with the avrasm.exe cross-assembler. For other AVR processors like 90S8515, 90S8535 and at-Tiny 26, the files to be included are 8515def.inc, 8535def.inc and tn26def.inc, respectively.

The next task is to burn the code into the chip. Note that a chip previously programmed or erased is automatically erased when a new program is burnt into it using the device programmer as described below.

The AVR device programmer
The AT-PROG programmer software is used for programming ATmega8535. This menu-drive programming software is simple to use and invoked from command prompt.

The software uses a simple pod connected to the printer port of a computer. The circuit of the pod (shown in Fig. 3) is very simple. It just connects the IC to be programmed to the pins of the PC’s printer port.

This circuit is assembled on a small PCB with a D25 male-female plug at one end. The IC base is a 40-pin zero-insertion-force socket (ZIF). This enables easy insertion and removal of the IC to be programmed.

The AT_PROG.exe is a simple programming software that can be run under DOS prompt by typing AT-PROG. The files At-prog-hlp.htm, At-prog.exe, At-prog.cfg and At-prog.ini should be placed in one directory before running the AT-PROG. These files have been included in this month’s EFY-CD as part of this article.

The menu-driven window of the AT-PROG programmer has the following menu items:
1. File menu. This menu is used to select or open the LED.hex file, or whatever, which is to be programmed into the device.

Pull down the menu by clicking it. Under ‘Open’ option, enter the file name as ‘LED.hex’ and press ‘Enter.’ The IC to be programmed is selected from the AVR-Programmer window by clicking the edge of the small rectangular window and choosing the IC as shown in Fig. 4. Now connect the printer-port connector to the programming pod, whose circuit is shown in Fig. 3.
2. Write menu. On clicking the ‘Write’ menu, the ‘Activity’ window at the bottom whitens and shows ‘Connecting’  (refer Fig. 5). Then, the data is transferred to the IC and verified after programming, showing ‘ok’ in the same window.
3. Check menu. This menu is used to find out whether the IC is inserted in the socket and whether the connector connections are okay. It will indicate an error if the IC is not there or not responding.

In this mode of programming, the serial-peripheral interface (SPI) of the AVR chip is used. This interface has three wire connections:
(i) Master output and slave input (MOSI)
(ii) Master input and slave output (MISO)
(iii) Serial clock (SCLK)

Using these wires, the SPI interface does the serial transfer of data (i.e., our program codes) into the chip, which is configured as a slave. The data and clock are connected via MOSI and SCLK pins of the chip, respectively. Upon reception of each byte, the chip acknowledges it by sending a byte (53hex).

In ‘Check’ mode, the IC is enquired about its name by the computer (Master), which it replies with its signature code embedded in the chip memory by the manufacturer. Each IC has its specific signature code. Thus, by noting the code itself, what IC is being programmed will be known to the computer. So the small window under the device-select rectangular window can be clicked to show ‘autodetect’ the IC.
4. Options menu. In this menu, the speed of the clock used for transferring data from the computer can be selected as ‘slow,’ ‘normal’ or ‘fast.’ With present high-speed PCs, choose ‘normal’ or ‘slow.’ In the same menu, the ‘read signature bytes’ option is to be enabled and it is so by default.
5. Port menu. The port menu, which is next to the file menu, is useful if a different printer port is available. The program automatically selects the available printer port.

When the ‘Activity’ window shows ‘ok’ after clicking the ‘Write’ menu, remove the programmed chip from the programmer circuit board and fix it onto the target circuit for the LED.asm program (shown in Fig. 2). Now apply 5V and press the switch connected to Reset pin, if needed. (The circuit resets at power-on.) The LEDs start blinking fast and the waveform can be observed on the CRO for any of the pins at the output to the LEDs. It will be around 600 Hz.

Message display on the LCD module
Method I. Given below is the source code for message display on the LCD module along with suitable comments wherever needed.


This program displays ‘Electronics ForU’ on the LCD module (Fig. 6). The message may be displayed on the LCD in a single or two rows depending on the LCD module. In some LCD modules, the first eight characters are written consecutively, while for display of the next eight characters, the program needs to restart the cursor at address $C0. But Hitachi-make single-row types do not need to restart the cursor’s address after the eighth entry; the characters can be written consecutively up to ‘16,’ i.e., in a single row.

The program is named as ‘LCD_CHAR.asm’ and assembled into the ‘.hex’ file by typing ‘avr lcd_char’ and invoking the cross-assembler AVR. Now the lcd_char.hex file is generated. The AT-PROG programmer burns this code into the flash memory of the ATmega8535.

Note that while assembling this program using ‘avr lcd_char’ command, the definition file for IC ATmega8535 (m8535def.inc) should be in the same directory.

Method II. This message display program uses look-up table. In the message display program described in Method I, ‘Call lcdwr’ instruction was written for each character. Here, instead, if we enter all the bytes for ‘Electronics ForU’ in a table, they can be picked up one by one until the end and shown on the LCD screen. For the purpose, there is an instruction called load program memory (LPM).

The table, as also the name, is stored in the program memory. Here is the program along with necessary comments.


The actual-size PCB for programming and LCD message display are given in Figs 7 and 9, while their component layouts are shown in Figs 8 and 10, respectively.
 
Read more ...