Опубликовано 2010-01-24 11:11:02 автором MRS

Where to start programming AVR microcontrollers. Lesson 1


In this tutorial, avr, I tried to describe the most basic for beginners programming of microcontrollers. avr . All the examples are built on the microcontroller atmega8. This means that for the repetition of all the lessons you need just one MK. atmega8 microcontroller as an emulator of electronic circuits used Proteus - in my opinion, is the best option for beginners. The program in all the examples are written for a C compiler for avr CodeVision AVR. Why not some assembler? Because the young, and so loaded with information, but the program that multiplies two numbers, assembler takes approximately a hundred lines, and in large, complex projects using C. the Compiler CodeVision AVR geared for the atmel, has a convenient code generator, a nice interface and direct flash microcontroller.

In this tutorial, you will be told and shown in a simple example like this:

  • Start programming microcontrollers, where to start, what to do this.
  • What program to use for writing firmware for avr, simulation and debug code on the PC,
  • What peripheral devices are inside MK how to manage them using your program
  • How to write a ready firmware to the microcontroller and how to configure
  • How to make the printed circuit Board for your device
To make the first steps towards programming MK, you need only two programs:
  • Proteus - program - emulator (it is possible to develop a scheme without having to real soldering and then this scheme to test our program). We all projects will first run in Proteus before soldering the real device. Here
  • CodeVisionAVR compiler the C programming language for AVR. In it we will develop the software for the microcontroller, and directly from it will be possible to flash the real MC. here
After installation, Proteus, run it первие steps in Proteus He offers us show projects that go with it, we politely refusing. Now let's make it the elementary scheme. For this клацнем icon first project Proteus nothing happens. Now you need to click on the little G (choose from a library) in the list panel the components dialog window, select the components select device in Proteus in the mask field, enter the name of the component that we want to find in the library. For example, we need to add the atmega8 microcontroller choice mega8 in Proteus in the list of results we click on the atmega8 and click OK. we in the list of components appears atmega8 microcontroller add mega8 in Proteus Thus adding to the list of components resistor, typing mask word res and led led add a resistor in Proteus choice led in Proteus To place the parts in the diagram, click on the item, then click on the schema field, select the location of the component and again click. To add the earth or the total minus the diagram on the left click on "Terminal" and choose the Ground. Thus, by adding all the components and combining them, and we get such a simple shemku scheme Hello World Proteus Everything is now our first schema is ready! But you may ask, what can it do? And nothing. Nothing, because for the microcontroller is earned for him to write a program. The program is a list of commands to be performed by the microcontroller. We need to microcontroller installed on the leg PC0 logical 0 (0 volts) and logical 1 (5 volts) .

Writing a program for the microcontroller

Program, we will write the C compiler CodeVisionAVR. After running CV, he asks us what we want to create: Source or Project project Selection in CodeVisionAVR We choose the latter and click OK. Next, we will be prompted to run the wizard CVAVR CodeWizard (this is an invaluable tool for the beginner as it can generate a basic skeleton of the program) start the wizard code CVAVR CodeWizard choose the Yes choice chip CVAVR CodeWizard Wizard starts with a tab active Chip, here we can choose the model of our MK is atmega8, and the frequency at which will work MK (default mega8 exhibited at a frequency of 1 megahertz ), so putting all as shown in the screenshot above. Go to the tab Ports choice chip CVAVR CodeWizard In the atmega8 microcontroller 3 port: Port C Port D Port B. each port 8 legs. Legs ports can be in two States:
  • the Entrance
  • Output
With register DDRx.y we can set up the leg of an input or output. If the
  • DDRx.y = 0 - the output works as a the ENTRANCE
  • DDRx.y = 1 conclusion runs on OUTPUT
When the leg is configured as an output, we can put on it the log 1 ( +5 volts ) and logical 0 (0 volts) . This is done entry in the register PORTx.y . Next will provide details on the I / o ports . And now expose all as shown on the screenshot, and click File - > Generate, Save and Exit. Next CodeWizard will offer us save the project, we store and look at the code:
#include <mega8.h>  // library for micro mega8  
#include <delay.h>  // library for creating temporary delays  
 
void main ( void )  
{  
PORTB = 0x00;  
DDRB = 0x00;  
 
PORTC = 0x00;  
DDRC = 0x01; // do the leg PC0 output  
 
PORTD is set = 0x00;  
DDRD = 0x00;  
 
// Timer / Counter 0 initialization  
TCCR0 = 0x00;  
TCNT0 = 0x00;  
 
// Timer / Counter 1 initialization  
TCCR1A = 0x00;  
TCCR1B = 0x00;  
TCNT1H = 0x00;  
TCNT1L = 0x00;  
ICR1H = 0x00;  
ICR1L = 0x00;  
OCR1AH = 0x00;  
OCR1AL = 0x00;  
OCR1BH = 0x00;  
OCR1BL = 0x00;  
 
// Timer / Counter 2 initialization  
ASSR = 0x00;  
TCCR2 = 0x00;  
TCNT2 = 0x00;  
OCR2 = 0x00;  
 
// External Interrupt ( s ) initialization  
MCUCR = 0x00;  
 
// The Timer ( s ) / Counter ( s ) Interrupt ( s ) initialization  
TIMSK = 0x00;  
 
// Analog Comparator initialization  
ACSR = 0x80 ;  
SFIOR = 0x00;  
 
while ( 1)  
{  
} ;  
} 

Here you may find all the terrible and strange, but actually it not so. The code can be simplified, throwing initialization unused us peripherals MK. After simplifying it looks like this:
 #include <mega8.h> // library for micro mega8  
#include <delay.h> // library for creating temporary delays  
 
void main ( void )  
{  
DDRC = 0x01; /* do the leg PC0 output   entry 0x01 may seem strange, but it is just the number 1 in the hexadecimal form,
this line will be equivalent to 0b00000001 in binary, then I'll write that way. */
 
while ( 1)  
{  
} ;  
} 

All well. But to led замигав, we need to change the logic level on the leg PC0. To do this, in the main loop to add some lines:
 #include <mega8.h> // library for micro mega8  
#include <delay.h> // library for creating temporary delays  
  
void main ( void )  
{  
DDRC = 0x01; /* do the leg PC0 output   entry 0x01 may seem strange, but it is just the number 1 in the hexadecimal form,
this line will be equivalent to 0b00000001 in binary, then I'll write that way. */  
 
while (1) // main cycle program  
{// Opens the control room bracket the main program loop  
PORTC.0 = 1; // set on foot 0 port 1  
delay_ms ( 500 ) ; // make latency of 500 milliseconds  
PORTC.0 = 0 ; // set on foot 0 port 0  
delay_ms ( 500 ) ; // make latency of 500 milliseconds  
} ;// Closes the control room bracket the main program loop  
} 

Now the code is ready. Клацнем the icon to Build all Project files to compile (translate the instructions in the processor MK ) our program. In the folder Setup.exe in our project, must receive a file with the extension hex, this is our firmware file to the MC. To our firmware feed the virtual microcontroller in Proteus, you need to double-click on the image of the microcontroller in Proteus. A window will appear such firmware selection MK Proteus click on the icon of the folder in the Program File, vyberaem hex - file our firmware and click OK. You can now run the simulation of our model. To do this, press the button "Play" at the bottom-left corner of the window Proteus. add resistor in Proteus

Комментарии - (6)

  • yu говорит:
    Здравствуйте! Вот прочитал Вашу статью и решил проверить, но разочаровался…. Сделал все как написано, но ничего не заработало. При этом никаких ошибок обе программы не выдали. В чем может быть проблема? Возможно, такое, что Вы допустили ошибку? Прошу проверьте, пожалуйста, код или еще лучше залейте файлы работоспособного проекта. Спасибо за внимание!
  • Admin говорит:
    Здравствуйте. У меня все правильно проверил.
  • Андрей говорит:
    Здравствуйте сделал все как у Вас после запуска программы сигнал доходит до резистора а дальше не поступает на светодиод. Объясните почему?
  • Admin говорит:
    Здравствуйте. На ножке микроконтроллера 5в устанавливается?
  • Филипп говорит:
    У меня тоже не мигает. Ошибка в том, что сопротивление резистора устанавливается как 10к по умолчанию. На вашем примере просто 10. Когда я у себя убрал букву "К" то диод замигал :)
  • Admin говорит:
    Все правильно, от 10к ему не хватает тока чтобы засветится, у меня стоит просто 10, это 10 ом

Добавить комментарий

Для отправки комментария вы должны авторизоваться.