TVs. Consoles. Projectors and accessories. Technologies. Digital TV

Programming for microcontrollers in C. How to start programming AVR? Recommendations. Where are microcontrollers used?

There are various programming languages ​​for AVR microcontrollers, but perhaps the most suitable are assembler and C, since these languages ​​best implement all the necessary capabilities for managing microcontroller hardware.

Assembly language is a low-level programming language that uses the direct instruction set of the microcontroller. Creating a program in this language requires a good knowledge of the command system of the programmable chip and sufficient time to develop the program. Assembly language is inferior to C in speed and ease of program development, but has noticeable advantages in the size of the final executable code, and, accordingly, the speed of its execution.

C allows you to create programs with much greater comfort, providing the developer with all the advantages of the language high level.
It should be noted once again that the architecture and command system of AVR were created with the direct participation of the developers of the C language compiler and it takes into account the features of this language. Compiling C source code is fast and produces compact, efficient code.

The main advantages of C over assembler: high speed program development; universality, which does not require a thorough study of the microcontroller architecture; better documentability and readability of the algorithm; availability of function libraries; support for floating point calculations.

The C language harmoniously combines programming capabilities low level with the properties of a high level language. The ability to low-level programming allows you to easily operate directly on hardware, and the properties of the high-level language allow you to create easily readable and modifiable program code. In addition, almost all C compilers have the ability to use assembler inserts to write program sections that are critical in terms of execution time and resource consumption.

In a word, C is the most convenient language for both beginners getting acquainted with AVR microcontrollers and serious developers.

Compilers are used to convert the source code of a program into a microcontroller firmware file.

Atmel provides a powerful assembly compiler that is included in the Atmel Studio development environment running on Windows. Along with the compiler, the development environment contains a debugger and an emulator.
Atmel Studio is completely free and available on the Atmel website.

Currently, there are quite a lot of C compilers for AVR. The most powerful of them is considered to be the compiler from IAR Systems from Stockholm. It was its employees who participated in the development of the AVR command system in the mid-90s. IAR C Compiler has extensive code optimization capabilities and comes as part of the IAR Embedded Workbench (EWB) integrated development environment, which also includes an assembler compiler, linker, project and library manager, and debugger. Price full version package is 2820 EUR. You can download it for free on the company website evaluation version for 30 days or unlimited with a code size limit of 4 KB.

The American company Image Craft from Palo Alto, California produces a C language compiler that has gained quite wide popularity. JumpStart C for AVR has acceptable code optimization and a not too high price (from $50 to $499 depending on the version). The demo version of JumpStart C for AVR is fully functional for 45 days.

The Romanian Code Vision AVR C Compiler has gained no less popularity; the price of the full version of this compiler is relatively low and amounts to 150 EUR. The compiler comes with an integrated development environment, which, in addition to standard features, includes a rather interesting feature - CodeWizardAVR Automatic Program Generator. The presence of a serial terminal in the development environment allows you to debug programs using the serial port of the microcontroller. You can download a free evaluation version from the developers with a code size limit of 4 KB and disabled saving of the generated source code in C.

The company MikroElektronika, located in the Serbian city of Belgrade, produces a whole family of compilers for AVR microcontrollers. A compiler for the C language called mikroC PRO for AVR costs $249. There are also mikroBasic and mikroPascal for the same price. There are demo versions on the developers' website with a code size limit of 4096 bytes. The advantage of this family of compilers is a single platform and a single ideology, which can provide an easy transition not only between languages, but also between microcontrollers (there are compiler versions for PIC, STM32, 8051...).

The integrated development environment has become truly iconic. It includes powerful C and assembler compilers, the AVRDUDE programmer, a debugger, a simulator, and many other supporting programs and utilities. WinAVR integrates seamlessly with Atmel's AVR Studio development environment. The assembler is identical in input code to the AVR Studio assembler. C and assembler compilers have the ability to create debug files in COFF format, which allows you to use not only built-in tools, but also use the powerful AVR Studio simulator. Another important advantage is that WinAVR is distributed free of charge without restrictions (manufacturers support the GNU General Public License).

As a summary, it is worth saying that WinAVR is an ideal choice for those who are starting to master AVR microcontrollers. It is this development environment that is considered as the main one in this course.

I decided to write a short introductory article for those who took up programming microcontrollers for the first time and were never familiar with the C language before. We won’t get into details, we’ll talk about everything a little to get a general idea of ​​working with CodeVisionAVR.

More detailed information you can look at English in the CodeVision User Manual, and also recommend the site http://somecode.ru with video lessons on C for microcontrollers and the book “How to Program in C” by Deitel, this is the only good book with which I myself started.

Let's start with the fact that no matter what actions we do, ultimately it all comes down to the firmware of the microcontroller. The firmware process itself occurs as follows: using a certain program, a firmware file is selected, parameters are selected, a button is pressed and the firmware is directly flashed, which, in essence, is a copy. Just like you copy music or documents from a computer to a flash drive, the physics of the process are the same.

The firmware itself has a .hex extension and is a set of instructions, in the form of ones and zeros, which is understandable to the microcontroller. Where can I get the firmware from? You can download it from electronics websites, or write it yourself. You can write it in special programs, which are called the development environment. The most well-known to me are AVR Studio, IAR, CodeVision, WinAVR... It’s impossible to say which of these environments is better or worse, to each his own. We can say that these programs differ mainly in convenience, programming language and price. Within this site, only CodeVision is considered.

We've sorted out the environment, now let's look at the process of writing firmware. In CodeVision, you first need to create a project. It can be created using the code wizard or empty. In any case, you need to select the type of microcontroller used and indicate its frequency. When using the wizard, you will be asked to select initial settings and generate source code with settings. Next, a window will appear in which you can edit this code. Although you can write your source code in Notepad and then attach it to the project in the settings.

The source code file is a set of commands in a programming language, CodeVision's task is to translate these commands into binary code, your task is to write this source code. CodeVision understands the C language, source code files have the extension “.c”. But CodeVision has some constructs that are not used in C, which is why many programmers don’t like it, and the language used is called C-like. However, this does not prevent you from writing serious projects. A lot of examples, a code generator, and a large set of libraries give CodeVision a big advantage. The only negative is that it is paid, although there is free versions with code restriction.

The source code must contain a header with the type of microcontroller used and the main function. For example, ATtiny13 is used

#include void main(void) ( ) ;

#include void main(void) ( );

To main functions you can connect the necessary libraries, declare global variables, constants, settings. The library is separate file, usually with a ".h" extension that already contains pre-written code. In some projects we may need this code, but in others we do not need it. For example, in one project we use LCD displays, but in another we do not. You can connect the library for working with the LCD display “alcd.h” like this:

#include #include void main(void) ( ) ;

#include #include void main(void) ( );

Variables are areas of memory in which certain values ​​can be placed. For example, if you add two numbers, you need to save the result somewhere to use it in the future. First you need to declare the variable, i.e. allocate memory for it, for example:
int i=0;
those. we declared the variable i and put the value 0 in it, int is the type of the variable, or more simply, it means the size of the allocated memory. Each variable type can only store a certain range of values. For example, int can be written as numbers from -32768 to 32767. If you need to use numbers with a fractional part, then the variable must be declared as a float; for characters, use the char type.

bit, _Bit 0 or 1 char from -128 to 127 unsigned char from 0 to 255 int from -32768 to 32767 unsigned int from 0 to 65535 long int from -2147483648 to 2147483647 unsigned long int from 0 to 4294967295 float from ±1.1 75e- 38 to ±3.402e38

Inside the main function, the main program is already running. After executing the function, the program will stop, so they make an infinite while loop, which repeats the same program constantly.

void main(void) ( while (1) ( ) ; ) ;

void main(void) ( while (1) ( ); );

You can write a comment in any part of the source code; it will not affect the operation of the program in any way, but will help make notes on the written code. You can comment out a line with two slashes //after which the compiler will ignore the entire line or several lines /**/, for example:

/*Basic math operations:*/ int i= 0 ; //declare the variable i and assign it the value 0//Addition: i = 2 + 2 ; //Subtraction: i = 2 - 2 ; //after executing this expression, the variable i will be equal to 0//Multiplication: i = 2 * 2 ; //after executing this expression, the variable i will be equal to 4//Division: i = 2 / 2 ; //after executing this expression, the variable i will be equal to 1

/*Basic mathematical operations:*/ int i=0; //declare variable i and assign it the value 0 //Addition: i = 2+2; //after executing this expression, the variable i will be equal to 4 //Subtraction: i = 2-2; //after executing this expression, the variable i will be equal to 0 //Multiplication: i = 2*2; //after executing this expression, the variable i will be equal to 4 //Division: i = 2/2; //after executing this expression, the variable i will be equal to 1

Often, a program needs to transition from one piece of code to another, depending on conditions; for this, there are conditional if() operations, for example:

if(i>3) //if i is greater than 3, then assign i the value 0 ( i=0; ) /*if i is less than 3, then go to the code following the body of the condition, i.e. after brackets ()*/

Also if can be used in conjunction with else - otherwise

if(i<3) //если i меньше 3, то присвоить i значение 0 { i=0; } else { i=5; //иначе, т.е. если i больше 3, присвоить значение 5 }

There is also a comparison operator “==”, which should not be confused with “=” assign. The reverse operation is not equal to "!=", let's say

if(i==3)//if i is 3, assign i the value 0 ( i=0; ) if(i!=5) //if i is not 5, assign i the value 0 ( i=0; )

Let's move on to more complex things - functions. Let's say you have a certain piece of code that is repeated several times. Moreover, this code is quite large in size. It is inconvenient to write it every time. For example, in a program that somehow changes variable i, when you press button 0 and 3 of port D, the same code is executed, which, depending on the value of variable i, turns on the legs of port B.

void main(void) ( if (PIND.0== 0 ) //check if the button on PD0 is pressed( if (i== 0 ) //if i==0 enable PB0( PORTB.0= 1 ; ) if (i== 5 ) // if i==5 enable PB1( PORTB.1= 1 ; ) ) … if (PIND.3== 0 ) // do the same thing when checking the PD3 button( if (i== 0 ) ( PORTB.0= 1 ; ) if (i== 5 ) ( PORTB.1= 1 ; ) ) )

void main(void) ( if(PIND.0==0) //check whether the button on PD0 is pressed ( if(i==0) //if i==0 turn on PB0 ( PORTB.0=1; ) if( i==5) // if i==5 turn on PB1 ( PORTB.1=1; ) ) ... if(PIND.3==0) // do the same thing when checking the PD3 button ( if(i==0 ) ( PORTB.0=1; ) if(i==5) ( PORTB.1=1; ) ) )

In general, the code is not very large, but it could be many times larger, so it would be much more convenient to create your own function.
For example:

void i_check() ( if (i== 0 ) ( PORTB.0= 1 ; ) if (i== 5 ) ( PORTB.1= 1 ; ) )

void i_check() ( if(i==0) ( PORTB.0=1; ) if(i==5) ( PORTB.1=1; ) )

void means that the function does not return anything, more on this below i_check() - this is the name of our function, you can call it whatever you want, I called it exactly that - check i. Now we can rewrite our code:

void i_check() ( if(i==0) ( PORTB.0=1; ) if(i==5) ( PORTB.1=1; ) ) void main(void) ( if(PIND.0==0 ) //check whether the button on PD0 is pressed ( i_check(); ) ... if(PIND.3==0) ( i_check(); ) )

When the code reaches the line i_check(); then it will jump inside the function and execute the code inside. Agree, the code is more compact and clearer, i.e. functions help replace the same code, just one line. Please note that the function is declared outside the main code, i.e. before the main function. You can say, why do I need this, but while studying the lessons you will often come across functions, for example, clearing the LCD screen lcd_clear() - the function does not accept any parameters and does not return anything, but it clears the screen. Sometimes this function is used almost every other line, so the code savings are obvious.

It looks much more interesting to use a function when it takes values, for example, there is a variable c and there is a function sum that takes two values ​​of type int. When the main program executes this function, the arguments will already be in parentheses, so "a" will become equal to two, and "b" will become equal to 1. The function will be executed and "c" will become equal to 3.

int c= 0 ; void sum(int a, int b) ( c= a+ b; ) void main(void ) ( sum(2 , 1 ) ; )

int c=0; void sum(int a, int b) ( c=a+b; ) void main(void) ( sum(2,1); )

One of the most common similar functions is to move the cursor on the LCD display lcd_gotoxy(0,0); which, by the way, also takes arguments - x and y coordinates.

Another option for using a function, when it returns a value, now it will no longer be void, let's improve the previous example of a function for adding two numbers:

int c= 0 ; int sum(int a, int b) ( return a+ b; ) void main(void) ( с= sum(2, 1) ; )

int c=0; int sum(int a, int b) ( return a+b; ) void main(void) ( с=sum(2,1); )

The result will be the same as last time c=3, but note that we assign the variable “c” the value of a function that is no longer void, but returns the sum of two numbers of type int. This way we are not tied to a specific variable “c”, which adds flexibility in using functions. A simple example of such a function is reading ADC data, the function returns the measured value result=read_adc();. Let's finish with the functions.

Now let's move on to arrays. An array is related variables. For example, you have a sine table with several points, you will not create variables int sinus1=0; int sinus2=1; etc. An array is used for this. For example, you can create an array of three elements like this:
int sinus=(0,1,5);
The total number of array elements is indicated in square brackets. You can assign the value of the third element to the variable “c” like this:
с=sinus;
Please note that the numbering of array elements starts from zero, i.e. "c" will become equal to five. This array does not have a sinus element!!!
You can assign a value to an individual element like this:
sinus=10;

You may have already noticed that CodeVision does not have string variables. Those. you cannot create a variable string hello=”hello”; To do this, you will have to create an array of individual characters.

lcd_putchar(hello); lcd_putchar(hello); lcd_putchar(hello);

etc.
It turns out quite cumbersome, this is where cycles come to the rescue.
For example while loop

while(PINB.0!=0) ( )

Until the button is pressed, do nothing - run an empty loop.

Another option is the for loop

int i; for (i= 0 ; i< 6 ; i++ ) { lcd_putchar(hello[ i] ) ; }

int i; for(i=0;i<6;i++) { lcd_putchar(hello[i]); }

The meaning is exactly the same as that of while, only the initial condition i=0 and the condition that is executed every cycle i++ are added. The code inside the loop is as simplified as possible.

After you have written your program, the source code is compiled, and if there are no errors, then you will receive the coveted firmware in the project folder. Now you can flash the microcontroller and enjoy the operation of the device.

You shouldn’t immediately try to use loops, arrays and functions in your firmware. Your main task is to make the firmware work, so do it as it is easier for you and do not pay attention to the size of the code. The time will come when you want not only to write working code, but to write it beautifully and compactly. Then it will be possible to delve into the wilds of the C language. For those who want to master everything, I once again recommend the book “How to Program in C”, there are many examples and tasks. Install Visual Studio, create a win32 console application and practice there to your heart's content.

Task: Let's develop a program to control one LED. When the button is pressed, the LED lights up and when released, it goes out.

First, let's develop a schematic diagram of the device. I/O ports are used to connect any external devices to the microcontroller. Each of the ports is capable of operating as both input and output. Let's connect the LED to one of the ports and the button to the other. For this experiment we will use a controller Atmega8. This chip contains 3 I/O ports, has 2 eight-bit and 1 sixteen-bit timer/counter. Also on board there is a 3-channel PWM, 6-channel 10-bit analog-to-digital converter and much more. In my opinion, a microcontroller is great for learning the basics of programming.

To connect the LED we will use line PB0, and to read information from the button we will use line PD0. The diagram is shown in Fig. 1.

Lesson No. 2. LED switching

Lesson No. 3. LED flashing

Lesson No. 4. Running lights

Lesson No. 5. Running lights using a timer

Lesson No. 6. Running lights. Using Timer Interrupts

Lesson No. 7. Bit Control Operators

Lesson No. 8. Implementation of PWM

Digital devices, for example, a microcontroller can only work with two signal levels, i.e. zero and one or off and on. Thus, you can easily use it to monitor the load status, such as turning an LED on or off. You can also use it to control any electrical device using the appropriate drivers (transistor, triac, relay, etc.). But sometimes you need more than just “turning on” and “turning off” the device. So if you want to control the brightness of an LED (or lamp) or the speed of a DC motor, then digital signals simply can't do it. This situation is very common in digital technology and is called Pulse Width Modulation (PWM).

Programming AVR microcontrollers for beginners. Programming the most popular microcontrollers - ATMega8, ATTiny13.

What is a microcontroller? A microcontroller is essentially a microcomputer with a processor, RAM and ROM, input/output ports; many microcontrollers have an analog-to-digital converter.

First of all, to write programs for Atmel AVR, you need to install the Atmel Studio program, you can download it from the official Atmel website on the Microchip website (Microchip bought out Atmel), the program is completely free:

http://www.microchip.com/mplab/avr-support/atmel-studio-7

In order to test a written program and not constantly assemble it on real physical components for testing, you will also need a program that emulates the operation of hardware, and this program is Proteus, but it is no longer free.

(Note - sometimes the result of work on real hardware may differ from the result of hardware emulation, so when making the final, final version of the written program, testing on real hardware is mandatory).

Atmel Studio installed.

(if an error occurs during startup or installation " Cannot find one or more components.Please reinstall the application"(One or more components were not found. Please reinstall the application.) - you need to remove the program, rename the folder C:\ProgramData\Package Cache(you should not delete it, because if something happens, you can rename it again to its original name if some applications stop working after that) , then the program will install and start normally).

Launched.

In the upper left corner select:

File => New => Project

Choose GCC C Executable Project(in the image below the number 1 ), At the bottom, in the Name( 2 ) indicate the name of our project in the Location field( 3 ) we can select the project location or leave the default path, click OK.

Then we select the model of our microcontroller from the list, in our case it is ATMEGA8 (you can select Attiny13 or another microcontroller you need and have):

A coding development environment will appear in the window, where there will already be standard C code and several commented lines indicating authorship and date:

Under number 1 there is a window for writing code, under number 2 files with source code, libraries and all files associated with the source code, in the main.c file there is the text of our code.

What does this code do?

line #include connects a standard library of input and output ports of AVR microcontrollers,

it can be found along the path (if you did not change the path during installation) " C:\Program Files\Atmel\Studio\7.0\toolchain\avr8\avr8-gnu-toolchain\avr\include\avr"

The main function is the standard C input function that the program starts with.

Inside the main function is a while loop that goes on forever.

And there is nothing in the body of the loop, i.e. The program doesn't do anything, it just loops forever and the main function doesn't exit, so there's no return keyword that returns the specified value.

In order to compile the written code, you need to select Build => Build “Your_Project_Name” at the top.

If the code is error-free, the program will compile and Build succeeded will be written at the bottom.

As a result, the compiled firmware will be in .HEX format and will be located at the address (again, if you have not changed the standard location):

C:\Users\UserName\Documents\Atmel Studio\7.0\ProjectName\ProjectName\Debug\ProjectName.hex

Note: If you select the Release build option, the firmware will be located in the corresponding folder i.e. not in the Debug folder, but in the Rele folder ase.

Code that does nothing is not very interesting, let's write a program that blinks an LED 2 times per second:

#define F_CPU 1000000UL // 1 MHz Here we set the frequency of the microcontroller #include //input/output library #include //delay library int main(void) // start of the main program(DDRD = 0xff; // set all ports D (see pinout of MK) as outputs while (1) ( // endless loop PORTD = 0xff ; // set "1" (on) on all lines of port D _delay_ms(250) ; // wait 250 milliseconds PORTD = 0x00 ; // set "0" (off) on all lines of port D _delay_ms(250) ; // wait 250 milliseconds } //closing parenthesis of an infinite loop } //bracket of the input function main

#define F_CPU 1000000UL // 1 MHz Here we set the frequency of the microcontroller #include //input/output library #include //delay library int main(void) // start of the main program ( DDRD = 0xff; // set all D ports (see pinout μ) as pins while (1) ( // endless loop PORTD = 0xff; // set "1 "(on) on all lines of port D _delay_ms(250); // wait 250 milliseconds PORTD = 0x00; // set "0" (off) on all lines of port D _delay_ms(250); // wait 250 milliseconds) // closing parenthesis of an infinite loop ) //input function parenthesis main

We compile the code and get ready-made firmware.

We flash the microcontroller with this firmware and assemble the circuit on hardware.

If you don’t know how to flash it, you can find out here:

In the next article we will learn how to check written code in Proteus i.e. We will emulate the operation of hardware.

There are many development tools for programming AVR microcontrollers, however, the most popular, undoubtedly, is the package AVR Studio. There are a number of reasons for this popularity: free package, developed by the company ATMEL, it combines text editor, assembler and simulator. AVR Studio is also used in conjunction with hardware debugging tools. This article uses examples to discuss how to work with the package, which will help novice programmers quickly understand the interaction of individual components of AVR Studio.

The next part of the article will talk about debugging programs written in the C language in the AVR Studio environment.

The AVR Studio package has a solid history of development, which is reflected in the number of existing versions. At the end of 2003, version 4.08 was released, which has a number of useful additions, and at the beginning of 2004 an update (Service Pack 1) was released, adding support for the third generation AVR controllers of the ATmega48 family. Production of microcircuits of this family is scheduled for the second half of 2004.

The package distribution and Service Pack can be downloaded from the website www.atmel.com or you can obtain a CD with this distribution from the Russian distributor of ATMEL.

It is convenient to consider the operation of the AVR Studio package on any specific program. To illustrate, we'll look at creating a project for the simplest program, which will light up two LEDs in turn. To be specific, let’s take the microcircuit Atmega128 and connect two LEDs to pins 31 and 32 (these are bits 6 and 7 of port D of the ATmega128 chip). AVR controllers have powerful output stages, the typical current of each output is 20 mA, the maximum output current is 40 mA, and this applies to both the inflow and outflow current. In our example, the LEDs are connected by their anodes to the controller terminals, and the cathodes are connected to ground through quenching resistors. This means that the LED is lit by applying a “1” to the corresponding port pin. Schematic diagram shown in the figure. The diagram also shows two buttons that will be used in one of the programs.

Here it is appropriate to make a short digression about choosing the type of microcircuit for a simple example. Indeed, at first glance it may seem strange why such a powerful crystal is needed in a 64-pin package where an 8-pin microcircuit would suffice ATtiny12? However, there is logic in this approach. It is known that almost any AVR controller is based on the same core. By and large, controllers differ in memory capacity, number of I/O ports, and set of peripheral modules. Features of each specific controller are the binding of logical names of I/O registers to physical addresses, addresses of interrupt vectors, definitions of port bits, etc. are described in files with the .inc extension that are included in the AVR Studio package. Consequently, using a specific type of crystal, you can debug the program both for it itself and for any junior crystal. Further, if you use the oldest crystal as a debugging crystal, today it is ATmega128, you can debug the program for almost any AVR controller, you just need to not use hardware resources that the target microcontroller does not have. Thus, for example, you can debug a program on the ATmega128 that will be executed on ATtiny13. In this case, the source code will remain almost the same, only the name of the included file will change from 128def.inc to tn13def.inc. This approach also has its advantages. For example, “extra” I/O ports can be used to connect LCD indicator, to which debugging information can be output. Or, use an in-circuit emulator that connects to the JTAG port of the ATmega128 chip (the ATtiny13 controller does not have such a port). Thus, you can use a single debugging board on which the “senior” AVR controller is installed to debug any newly developed systems, naturally also based on AVR microcontrollers. One of these boards is called AS-megaM. It was this that was used to create the example programs given in the article. This is a universal single-board controller based on the ATmega128 chip, which contains external RAM, two ports RS-232, port for connecting LCD indicator, in-circuit programmer and emulator AT JTAG ICE. The board also has space for unsoldering a FLASH-ROM series chip AT45 in TSOP32/40/48 housings and two-channel DAC series AD5302/ AD5312/ AD5322. Now, after explaining the reasons for using an AVR monster to ignite a pair of LEDs, you can move on.

When programming in the AVR Studio environment, you need to perform the standard sequence of actions:

  • compilation
  • Creating a project begins by selecting the menu bar Project\New Project. In the “Create new Project” window that opens, you must specify the name of the project (in our case, sample1) and the name of the initialization file. After clicking the “Next” button, the “Select debug platform” window opens and device”, where the debugging platform (simulator or emulator) and the type of microcontroller are selected.

    You can choose one of the proposed in-circuit emulators; note that each emulator has its own list of supported chips. For the example under consideration, we choose the AVR Simulator and the ATmega128 chip as the debugging platform. After clicking the “Finish” button, we see the actual working windows of the AVR Studio package, which are still empty. You should place the source text of the program in the right window. This can be done in two ways, either by typing all the text directly in the editor window, or by loading an existing file. Below is the full text of the simplest program with comments.

    ; Example "LED Control"; written for the AS-MegaM development board; Master oscillator frequency 7.37 MHz; The LEDs are connected to pins PD6 and PD7 and through resistors to the common wire. ; connecting the ATmega128 chip I/O description file .include "m128def.inc" ; start of the program begin: ; the first operation is stack initialization; if this is not done, then call a subroutine or interrupt; will not return control back; the pointer to the end of the stack is set to the last address of the internal RAM - RAMEND ldi r16,low(RAMEND) out spl,r16 ldi r16,high(RAMEND) out sph,r16 ; in order to control the LEDs connected to pins PD6 and PD7, ; it is necessary to declare these conclusions as holidays. ; To do this, you need to write “1” to the corresponding bits of the DDRD (DataDiRection) register ldi r16,(1<<6) | (1<<7) out DDRD,r16 ; основной цикл программы loop: ldi r16,(1<<6) ; светится один светодиод out PORTD,r16 rcall delay ; задержка ldi r16,(1<<7) ; светится второй светодиод out PORTD,r16 rcall delay ; задержка rjmp loop ; повторение цикла; процедура задержки; примерно полсекунды при частоте 7,37 МГц; три пустых вложенных цикла соответственно delay: ldi r16,30 ; 30 delay1: ldi r17,200 ; 200 delay2: ldi r18,200 ; и еще 200 итераций delay3: dec r18 brne delay3 dec r17 brne delay2 dec r16 brne delay1 ret ; возврат в главную программу

    A project can consist of several files, with one file designated as the main one. All operations are conveniently performed using the contextual mouse button. After connecting the source file, the windows look like this:

    The project is compiled using the \Project\Build command or by pressing the F7 button. The compilation process is displayed in the “Output” window. This window can be pulled out using the \View\Output command.

    In principle, we have already received an output file in .hex format, which can already be loaded into the microcircuit and the LEDs blinking. However, the purpose of the article is to show the full cycle of work in the AVR Studio environment, so we move on to the debugging stage. This is done with the \Debug\Start Debugging command.

    Now we set the quartz frequency to 7.3728 MHz in the “Simulator Options” window to accurately measure the program execution time.

    The remaining options should be left unchanged. Now you can execute the program step by step using the mouse or the F11 button.

    The AVR Studio package contains powerful tools for viewing and editing the state of the internal registers and input/output ports of the microcontroller being debugged, as well as the program execution time. They are accessed through the “I/O” window.

    In fact, the amount of information available through AVR Studio's viewing windows is so great that for maximum comfort, you need to use a computer in a dual-monitor configuration.

    To debug our example, to access the port D bits, we need to expand the I/O ATMEGA128 line and then the PORTD line. Now all three registers of this port, PORTD, DDRD and PIND, are visible. To see the Value, Bits and Address fields, you will have to expand the right border of the window, crowding out the window with the source text of the program.

    Now, going through the program step by step, you can see changes in the current states of these registers in the Bits field. It is possible to quickly change the state of any bit of the port registers, and this can be done either by writing a new code in the Value field, or directly by clicking on the desired register bit.

    For independent exercises, the following program is offered, which differs from the previous one in that the lighting of the LEDs is controlled by two buttons.

    ; Example “Controlling LEDs from buttons”; written for the AS-MegaM development board; The LEDs are connected to pins PD6 and PD7 and through resistors to the common wire. ; buttons - on PE4 and PE5 .include "m128def.inc" ; main program begin: ; stack initialization ldi r16,low(RAMEND) out spl,r16 ldi r16,high(RAMEND) out sph,r16 ; initialization of LEDs ldi r16,(1<<6) | (1<<7) out DDRD,r16 ; инициализация выводов, к которым подключены кнопки (на вход) ; внутренние подтягивающие резисторы подключены; для этого в PORTE нужно установить соответствующие биты в единицы ldi r16,(1<<4) | (1<<5) out PORTE,r16 ; а в DDRE - в нули ldi r16,0 out DDRE,r16 ; бесконечный цикл forever: in r16,PINE ; теперь в r16 находится текущее "состояние" кнопок com r16 ; кнопка "нажимается" нулем, поэтому инвертируем регистр lsl r16 ; переносим биты 4,5 в позиции 6,7 lsl r16 ; и обновляем "показания" светодиодов andi r16,(1<<6) | (1<<7) out PORTD,r16 rjmp forever ; цикл выполняется бесконечно

    Thus, using the example of the simplest programs, some of the capabilities of the AVR Studio package are shown. You must understand that this is only the first acquaintance, which will allow you to quickly get used to the basic commands of the package. Meanwhile, the capabilities of the package in question are much wider. For example, here you can debug programs written in high-level languages. In particular, the ImageCraft C compiler uses the AVR Studio debugger “as if it were native.” To do this, when compiling the source code, you need to set the option to generate an output file in a format compatible with AVR Studio. In this case, it becomes possible to debug in source codes.

    Another of the many features of the AVR Studio package is the ability to connect external programs. For example, to call the AS2 in-circuit programmer shell, you need to perform a few simple operations.

    In the Tools menu of the main AVR Studio window, select Customize;

    In the Customize window, select Tools;

    Double-click the mouse button or press Insert on the keyboard, add a new command to the list and name it “AS2 Programmer”;

    Specify the path to the programmer executable file by entering it directly into the "Command" input field, or by clicking on the "..." button to the right of this field;

    Now the “AS2 Programmer” item has appeared in the Tools menu.

    The tools of the AVR Studio 4.08 package allow you to connect auxiliary programs - plugins. The first plugin for AVR Studio is a graphics editor program that simplifies the process of initializing an LCD display that can be directly controlled by the ATmega169 AVR controller. The maximum logical size of an LCD indicator is 100 segments; each element of the indicator is assigned a bit in a special register of the controller. To simplify the routine of assigning specific bits to each segment, the above program can be used.

    During a visit to the “homeland of AVR” - the Norwegian office of ATMEL, one of the authors of the article talked with Lars Kvenild, the head of the programming group that created and maintains the AVR Studio package. This man, a classic programmer, with a beard, wearing a sweater and wearing sandals on his socks, spoke about the prospects for the development of the package. The next version (4.09) will include an interface for a new in-circuit emulator - JTAGICE mkII (also called AT JTAGICE2), which will replace AT JTAGICE in the second half of the year. This emulator has two significant differences. On the one hand, support has been added for a new single-wire debug interface for junior AVR controllers, debugWIRE. This interface is interesting because it does not take up additional pins of the microcontroller for its operation, since it uses the Reset pin of the microcontroller for exchange! On the other hand (you can take this expression literally), the AT JTAGICE2 emulator will finally have a USB interface for communication with a computer.

    Literature

    1. Materials of the technical seminar AVR Technical Training. Atmel. Norway. December 2003.
    2. Nikolay Korolev, Dmitry Korolev AVR microcontrollers of the second generation: developer tools. // Components and technologies, 2003 No. 7
    3. Second generation AVR microcontrollers: new hardware capabilities // Components and Technologies. 2003. No. 4.
    4. Nikolai Korolev, Dmitry Korolev. AVR microcontrollers: big in small. // Circuitry", 2001, No. 5
    5. Nikolai Korolev, Dmitry Korolev. AVR microcontrollers: software // Components and Technologies, 2000. No. 4.
    6. Nikolai Korolev. AVR: developer hardware // Components and Technologies, 1999 No. 1
    7. Nikolai Korolev. RISC microcontrollers from ATMEL //Chip-News 1998, No. 2
    8. Nikolay Korolev, Dmitry Korolev AVR: new 8-bit RISC microcontrollers from ATMEL // Microprocessor Review, 1998, No. 1


    Related publications