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

Programming AVR microcontrollers. AVR microcontrollers. Programming for beginners Step-by-step instructions for programming atmega8 microcontrollers

December 2015

1. Advantages of the proposed method

Device circuits based on microcontrollers (MCUs) are usually distinguished by a combination of two difficult-to-combine qualities: maximum simplicity and high functionality. In addition, the functionality can be changed and expanded in the future without making any changes to the circuit - just by replacing the program (flashing). These features are explained by the fact that the creators of modern MKs tried to place on one chip everything that a developer might need electronic device- at least as much as possible. As a result, there was a shift in emphasis from circuitry and installation to software. With the use of MK, there is now less need to “load” the circuit with parts, and there are fewer connections between components. This, of course, makes the circuit more attractive for repetition by both experienced and novice electronics engineers. But, as usual, you have to pay for everything. This, too, was not without its difficulties. If you buy a new MK, install it in a circuit correctly assembled from serviceable parts and apply power, then nothing will work - the device will not work. The microcontroller needs a program.

It would seem that everything is simple with this too - on the Internet you can find many schemes with free firmware. But here there is one catch: the firmware must somehow be “uploaded” into the microcontroller. For someone who has never done this before, such a task often becomes a problem and the main repulsive factor, often forcing them to abandon the delights of using MK and look for schemes based on “loose” and rigid logic. But everything is not as complicated as it might seem at first glance.

After analyzing publications on the Internet, you can see that this problem This problem is most often solved in one of two ways: buying a ready-made programmer or making a homemade one. At the same time, published circuits of homemade programmers are very often unreasonably complex - much more complex than is really necessary. Of course, if you plan to flash the MK every day, it is better to have a “cool” programmer. But if the need for such a procedure arises infrequently, from time to time, then you can do without a programmer altogether. No, of course, we are not talking about learning to do this with the power of thought. This means that by understanding how the programmer interacts with the microcontroller when writing and reading information in its programming mode, we can make do with available tools for a wider purpose. These tools will have to replace both the software and hardware parts of the programmer. The hardware must provide a physical connection to the MK microcircuit, the ability to apply logical levels to its inputs and read data from its outputs. The software part must ensure the operation of the algorithm that controls all necessary processes. We also note that the quality of recording information in the MK does not depend on how “cool” your programmer is. There is no such thing as “better recorded” or “worse”. There are only two options: “registered” and “not registered”. This is explained by the fact that the recording process inside the crystal is directly controlled by the MK itself. You just need to provide it with high-quality power (no interference or ripple) and properly organize the interface. If the results of the test reading reveal no errors, then everything is in order - you can use the controller for its intended purpose.

In order to write a program into the MK without having a programmer, we need a USB-RS232TTL port converter and, as well. The USB-RS232TTL converter allows you to use a USB port to create a COM port that differs from the “real” one only in that its inputs and outputs use TTL logical levels, that is, voltage in the range from 0 to 5 volts (you can read more in the article " "). In any case, such a converter is useful to have in your household, so if you don’t already have one, it’s definitely worth purchasing. As for the logical levels, in our case TTL is even an advantage over a regular COM port, because the inputs and outputs of such a port can be directly connected to any microcontroller powered by 5 V, including ATtiny and ATmega. But do not try to use a regular COM port - they use voltages in the range from -12 to +12 V (or -15...+15V). In this case, direct connection to the microcontroller is unacceptable!!!

The idea of ​​creating a script for the Perpetuum M program, which implements the functions of the programmer, arose after reading a number of publications on the Internet offering certain solutions for MK firmware. In each case, serious deficiencies or excessive difficulties were discovered. Often I came across programmer circuits that contained a microcontroller, and at the same time, advice was given quite seriously like: “... and to program the microcontroller for this programmer we will need... that’s right - another programmer!” Next, it was suggested to go to a friend and look for paid service etc. The quality of the software distributed on the network for these purposes was also not impressive - many problems were noticed both with functionality and with "cloudiness" user interface. It often takes a lot of time to understand how to use a program - it must be studied even to carry out the simplest actions. Another program can do something for a long time and diligently, but the user learns that nothing is being written to the MK only after the entire firmware has been completely completed and subsequent test reading. The following problem also occurs: the user tries to select his MK from the list of supported crystals, but it is not in the list. In this case, you will not be able to use the program - inclusion in the list of missing MKs, as a rule, is not provided. In addition, manually selecting a controller from the list looks strange, considering that the programmer in many cases can itself determine the type of MK. All this is said not in order to throw mud at existing products, but in order to explain the reason for the appearance of the script for the Perpetuum M program, described in this article. The problem really exists, and it concerns primarily beginners who do not always manage to overcome this “wall” in order to take their first step into the world of microcontrollers. The proposed script takes into account the shortcomings found in other programs. Maximum “transparency” of the algorithm’s operation has been implemented, an extremely simple user interface that does not require learning and leaves no chance of getting confused and “clicking the wrong thing.” If the required MK is not among the supported ones, you can add its description yourself, taking the necessary data from the documentation downloaded from the MK developer’s website. And, most importantly, the script is open for study and modification. Anyone can, by opening in text editor, study and edit it at your own discretion, changing existing functions to your taste and adding missing ones.

The first version of the script was created in June 2015. This version provides only support for Atmel's ATtiny and ATmega series microcontrollers with flash memory write/read functions, configuration bit settings, automatic detection controller type. Writing and reading EEPROM is not implemented. There were plans to supplement the functionality of the script: add writing and reading of EEPROM, implement support for PIC controllers, etc. For this reason, the script has not yet been published. But due to lack of time, the implementation of the plan was delayed, and so that the best did not become the enemy of the good, it was decided to publish the existing version. If the functions already implemented are not enough, please do not be upset. In this case, you can try to add the desired function yourself. I will not hide: the idea of ​​​​creating this script initially also carries an educational meaning. By understanding the algorithm and adding something of your own to it, you will be able to better understand the operation of the MK in programming mode, so that in the future you will not find yourself in the position of a girl in front of a broken down car, thoughtfully looking at its insides and not understanding why it “doesn’t work.”

2. MK interface in programming mode

There are several in various ways put the controller into programming mode and work with it in this mode. The easiest to implement for controllers of the ATtiny and ATmega series is, perhaps, SPI. We will use it.

But, before we begin to consider the signals necessary to generate SPI, we will make a number of reservations. The microcontroller has configuration bits. These are something like toggle switches, switching which allows you to change some properties of the microcircuit in accordance with the needs of the project. Physically, these are non-volatile memory cells, like those into which a program is written. The difference is that there are very few of them (up to three bytes for ATmega), and they are not part of the address space of any memory. Writing and reading configuration data is performed by separate commands in the MK programming mode. Now it is important to note that some configuration bits affect the very ability to use SPI. With some of their values, it may turn out that SPI cannot be used. If you come across such a microcontroller, the method proposed in this article will not help. In this case, you will either have to change the settings of the configuration bits in the programmer, which supports a different programming mode, or use a different microcontroller. But this problem only applies to used MKs, or those with which someone has already unsuccessfully “played around”. The fact is that new MCUs come with configuration bit settings that do not prevent the use of SPI. This is confirmed by the test results of the programmer script for the Perpetuum M program, during which four different MKs (ATmega8, ATmega128, ATtiny13, ATtiny44) were successfully flashed. They were all new. Initial setup configuration bits were consistent with the documentation and did not interfere with the use of SPI.

Given the above, you should pay attention to the following bits. The SPIEN bit explicitly allows or disables the use of SPI, therefore in our case its value must be enabling. The RSTDISBL bit is capable of turning one of the outputs of the microcircuit (predetermined) into the input of the reset signal, or not (depending on the value written to this bit). In our case, the “reset” input is necessary (if it is absent, it will not be possible to switch the MK to programming mode via SPI). There are also bits of the CKSEL group that specify the source of the clock signal. They do not prevent the use of SPI, but they also need to be kept in mind, because if there are no clock pulses at all, or if their frequency is lower than acceptable for a given SPI speed, nothing good will happen either. Typically, new MCUs that have an internal RC oscillator have the CKSEL group bits configured to use it. This suits us quite well - clocking is provided without any additional effort on our part. There is no need to solder the quartz resonator or connect an external generator. If the specified bits contain a different setting, you will have to take care of clocking in accordance with the setting. In this case, it may be necessary to connect a quartz resonator or an external clock generator to the MCU. But in this article we will not consider how this is done. The examples of connecting an MK for programming contained in this article are designed for the simplest case.

Rice. 1. Data exchange via SPI in programming mode

Now let's turn to Figure 1, taken from the documentation for the ATmega128A MK. It shows the process of transmitting one byte to the MK and simultaneously receiving one byte from the MK. Both of these processes, as we see, use the same clock pulses, coming from the programmer to the microcontroller at its SCK input - one of the pins of the microcircuit, for which this role is assigned in the SPI programming mode. Two more signal lines provide data reception and transmission one bit per clock. Through the MOSI input, data enters the microcontroller, and read data is taken from the MISO output. Notice the two dotted lines drawn from SCK to MISO and MOSI. They show at what moment the microcontroller “swallows” the data bit set at the MOSI input, and at what moment it itself sets its data bit to the MISO output. Everything is quite simple. But to enter the MK into programming mode, we still need a RESET signal. Let's also not forget about the common GND wire and VCC power supply. In total, it turns out that only 6 wires need to be connected to the microcontroller to flash its firmware via SPI. Below we will analyze this in more detail, but for now we will add that data exchange with the MK in programming mode via SPI is performed in packets of 4 bytes. The first byte of each packet is basically entirely dedicated to instruction encoding. The second byte, depending on the first, can be a continuation of the command code, or part of the address, or can have an arbitrary value. The third byte is used primarily for transmitting addresses, but can have an arbitrary value in many instructions. The fourth byte usually transmits data or has an arbitrary value. Simultaneously with the transmission of the fourth byte, some commands receive data coming from the microcontroller. Details for each command can be found in the controller documentation in the table called "SPI Serial Programming Instruction Set". For now, we only note that the entire exchange with the controller is built from a sequence of 32-bit packets, each of which transfers no more than one byte useful information. This is not very optimal, but overall it works well.

3. Connecting the MK for programming

To ensure that all the necessary signals are supplied to the microcontroller inputs to organize the SPI interface and read data from its MISO output, it is not necessary to create a programmer. This can be easily done using the most common USB-RS232TTL converter.

On the Internet you can often find information that such converters are inferior and that nothing serious can be done with them. But with regard to most converter models, this opinion is wrong. Yes, there are converters on sale that do not have all the inputs and outputs available compared to a standard COM port (for example, only TXD and RXD), while having a non-separable design (the microcircuit is filled with plastic - it is impossible to reach its pins). But these are not worth buying. In some cases, you can get the missing port inputs and outputs by soldering the wiring directly to the chip. An example of such an “improved” converter is shown in Figure 2 (chip PL-2303 - more details about the purpose of its pins in the article “”). This is one of the cheapest models, but has its own advantages when used in homemade structures. Full-featured adapter cords with a standard nine-pin connector at the end, like a COM port, are also widespread. They differ from a regular COM port only in TTL levels and incompatibility with legacy software and some older hardware. It can also be noted that the cords on the CH34x chip show themselves to be much more reliable and stable in various extreme tests compared to converters on the PL-2303. However, during normal use the difference is not noticeable.

When choosing a USB-RS232TTL converter, you should also pay attention to the compatibility of its driver with the version of the operating system you are using.

Let's take a closer look at the principle of connecting a microcontroller and a USB-RS232TTL converter using the example of four different models MK: ATtiny13, ATtiny44, ATmega8 and ATmega128. Figure 3 shows the general diagram of such a connection. It may surprise you to know that the RS232 signals (RTS, TXD, DTR and CTS) are being used inappropriately. But don't worry about it: the Perpetuum M program is able to work with them directly - set output values ​​and read input states. In any case, the widely used USB-RS232TTL converters on CH34x and PL-2303 chips provide this capability - this has been verified. There should also be no problems with other popular converters, since standard Windows functions are used to access the port.

Resistors shown in general scheme, in principle, you don’t have to install it, but it’s still better to install it. What is their purpose? Using the TTL inputs and outputs of the converter and the five-volt power supply of the microcontroller, we thereby get rid of the need to coordinate logical levels - everything is already quite correct. This means that the connections can be direct. But during experiments, anything can happen. For example, according to the law of meanness, a screwdriver can fall just in the place where it could not fall, and short-circuit something that in no case should be short-circuited. Of course, anything can turn out to be a “screwdriver.” Resistors in this case sometimes reduce the consequences. one of their purposes is to eliminate a possible conflict of outputs. The fact is that after programming is completed, the microcontroller goes into normal operation mode, and it may happen that its output connected to the output of the converter (RTS, TXD or DTR) also becomes an output, according to the program just recorded in the MK. In this case, it will be very bad if two directly connected outputs “fight” - try to set different logical levels. In such a “struggle,” someone may “lose,” but we don’t want that.

The values ​​of the three resistors are selected at the level of 4.3 KOhm. This applies to connections between the converter output and the microcontroller input. The accuracy of the resistors does not matter: you can reduce their resistance to 1 KOhm or increase it to 10 KOhm (but in the second case, the risk of interference increases when using long wires on the way to the MK). As for the connection between the converter input (CTS) and the microcontroller output (MISO), a 100 Ohm resistor is used here. This is explained by the peculiarities of the input of the converter used. During the tests, a converter was used on the PL-2303 microcircuit, the inputs of which, apparently, are connected to the power supply positive with a relatively low resistance (of the order of several hundred Ohms). To “break the pull-up” I had to install a resistor with such a small resistance. However, you don’t have to install it at all. On the converter this is always the input. It cannot become a way out, which means there will be no conflict of exits in any development of events.

If the chip has a separate AVCC pin for powering the analog-to-digital converter (for example, ATmega8 or ATmega128), it should be connected to the common VCC power pin. Some ICs have more than one VCC power pin or more than one GND. For example, ATmega128 has 3 GND pins and 2 VCC pins. In a permanent design, it is better to connect pins of the same name to each other. In our case, during programming, you can use one VCC and GND pin each.

And here is what the ATtiny13 connection looks like. The figure shows the pin assignments used when programming via SPI. Next to the photo is what a temporary connection looks like in reality.


Some may say that this is not serious - connections on the wiring. But you and I are sensible people. Our goal is to program the microcontroller, spending a minimum of time and other resources on it, and not to show off in front of someone. The quality does not suffer. Method "on wires" in in this case quite effective and justified. Flashing the controller's firmware is a one-time procedure, so there is no point in covering it with rhinestones. If it is intended to change the firmware in the future without removing the controller from the circuit (in the finished product), then this is taken into account during installation during the manufacture of the device. Usually a connector (RESET, SCK, MOSI, MISO, GND) is installed for this purpose, and the MK can be flashed even after installation on the board. But these are creative delights. We are considering the simplest case.

Now let's move on to the ATtiny44 MK. Everything is pretty much the same here. Based on the drawing and photo, even a beginner will not have any difficulty figuring out the connection. Like the ATtiny44, you can connect the ATtiny24 and ATtiny84 microcontrollers - the pin assignments for these three are the same.


Another example of temporarily connecting a controller for programming it is ATmega8. There are more pins here, but the principle is the same - a few wires, and now the controller is ready to “fill” information into it. The extra black wire in the photo coming from pin 13 does not take part in programming. It is designed to remove a sound signal from it after the MK exits the programming mode. This is due to the fact that while debugging the script for "Perpetuum M" the program was downloaded to the MK music box.


Often one controller is available in different housings. In this case, the assignment of pins for each case is distributed differently. If the housing of your controller is not similar to the one shown in the figure, check the purpose of the pins in the technical documentation, which can be downloaded from the MK developer’s website.

To complete the picture, let’s look at the connection of an MK microcircuit with a large number of “legs”. The purpose of the extra black wire in the photo coming from pin 15 is exactly the same as in the case of the ATmega8.


You are probably already convinced that everything is quite simple. Anyone who knows how to count the pins of microcircuits (from the mark in a circle counterclockwise) will figure it out. And don't forget about accuracy. Microcircuits love neat people and do not forgive careless treatment.

Before moving on to the software part, make sure that the USB-RS232TTL converter driver is installed correctly (check the manager Windows devices). Remember or write down the number of the virtual COM port that appears when you connect the converter. This number will need to be entered into the text of the script, which you can read about below.

4. Script - programmer for "Perpetuum M"

We figured out the hardware part of the “programmer”. This is already half the battle. Now all that remains is to deal with software part. Its role will be performed by the Perpetuum M program under the control of a script, which implements all the necessary functions for interacting with the microcontroller.

The archive with the script should be unpacked into the same folder where the perpetuum.exe program is located. In this case, when you run the perpetuum.exe file, a menu will be displayed on the screen with a list of installed scripts, among which there will be the line “AVR MK Programmer” (it may be the only one). This is the line we need.

The script is located in the PMS folder in the file "MK Programmer AVR.pms". This file can be viewed, studied and edited if necessary in a regular text editor like Windows Notepad. Before using the script, you will most likely need to make changes to the text related to port settings. To do this, check the device manager Windows name port used and, if necessary, make the appropriate amendment to the line "PortName="COM4";" - instead of the number 4 there may be another number. Also, when using a different USB-RS232TTL converter model, you may need to change the signal inversion settings (script lines starting with the word “High”). You can check the inversion of signals by the USB-RS232TTL converter using one of the examples contained in the instructions for the Perpetuum M program (section of functions for working with the port).

The MK_AVR subfolder contains files with descriptions of supported controllers. If the controller you need is not among them, you can add the one you need yourself, proceeding by analogy. Take one of the files as a sample, and using a text editor, enter the necessary data, taking it from the documentation for your microcontroller. The main thing is to be careful, enter the data without errors, otherwise the MK will not be programmed, or will be programmed incorrectly. The original version supports 6 microcontrollers: ATtiny13, ATtiny24, ATtiny44, ATtiny84, ATmega8 and ATmega128. The script implements automatic recognition of the connected controller - no need to specify it manually. If the identifier read from the MK is not among the available descriptions, a message is displayed that the controller could not be recognized.

The archive with the script also contains additional information. The AVR controller inc files folder contains a very useful and extensive collection of controller definition files. These files are used when writing your own programs for MK. Four more folders "MusicBox_..." contain files with a program in Assembly language and firmware ready for downloading to the MK separately for ATtiny13, ATtiny44, ATmega8 and ATmega128. If you have already connected one of these MKs for programming, as suggested in this article, then you can flash it right now - you will get a music box. More on this below.

When you select the line “MK AVR Programmer” in the script menu, the script begins to be executed. At the same time, it opens the port, sends a command to the MK to switch to programming mode, receives confirmation from the MK about the successful transition, requests the MK identifier and searches for a description of this MK by its identifier among the available files with descriptions. If it doesn't find the required description, displays a corresponding message. If a description is found, then the main menu of the programmer opens. You can see its screenshot in Figure 8. Further understanding is not difficult - the menu is very simple.

In the first version of the script, some functions of a full-fledged programmer are not implemented. For example, there is no way to read and write to EEPROM. But if you open the script in a text editor, you will see that it is very small in size, despite the fact that the main thing is already implemented in it. This suggests that adding missing functions is not so difficult - the language is very flexible, it allows small program implement rich functionality. But for most cases, even the existing functions are enough.

Some functionality limitations are described directly in the script text:
//implemented recording only from the zero address (Extended Segment Address Record is ignored, LOAD OFFSET - too)
//the order and continuity of records in the HEX file is not checked
//checksum is not checked
This applies to working with a HEX file, from which the firmware code for the MK is taken. If this file is not corrupted, checking the checksum will have no effect. If it is distorted, it will not be possible to detect it using the script. In most cases, the remaining restrictions will not hurt, but you still need to keep them in mind.

5. Music box - a simple craft for beginners

If you have one of these microcontrollers: ATtiny13, ATtiny44, ATmega8 or ATmega128, you can easily turn it into a music box or music card. To do this, it is enough to write the appropriate firmware into the MK - one of those four that are located in the "MusicBox_..." folders in the same archive with the script. Firmware codes are stored in files with the extension ".hex". Using ATmega128 for such a craft, of course, is “fatty”, just like ATmega8. But this may be useful for testing or experimentation, in other words - in educational purposes. The texts of the programs in Assembler are also attached. The programs were not created from scratch - the music box program from A.V. Belov’s book “AVR Microcontrollers in Amateur Radio Practice” was taken as a basis. The original program has undergone a number of significant changes:
1. adapted for each of the four MKs: ATtiny13, ATtiny44, ATmega8 and ATmega128
2. buttons have been eliminated - nothing needs to be connected to the controller except power and a sound emitter (melodies are played one after another in an endless loop)
3. the duration of each note is reduced by the duration of the pause between notes to eliminate disturbances in musical rhythm
4. the eighth melody is connected, not used in the book version
5. from the subjective: some “improvements” to optimize and make the algorithm easier to understand

In some melodies one can hear falsehood and even gross errors, especially in “Smile” - in the middle. The ringtone codes were taken from the book (or rather, downloaded from the book’s author’s website along with the original asm file) and have not been modified. Apparently, there are errors in the encoding of the melodies. But this is not a problem - anyone who is “friendly” with music can easily figure it out and fix everything.

In ATtiny13, due to the lack of a 16-bit counter, an 8-bit counter had to be used to reproduce notes, which led to a slight decrease in the accuracy of the notes. But this is hardly noticeable by ear.

About the configuration bits. Their settings must correspond to the state of the new microcontroller. If your MK has been used somewhere before, you need to check the state of its configuration bits, and, if necessary, bring them into line with the settings of the new microcontroller. You can find out the state of the configuration bits of the new microcontroller from the documentation for this MK (section "Fuse Bits"). The exception is ATmega128. This MCU has the M103C bit, which enables compatibility mode with the older ATmega103. Activating the M103C bit greatly reduces the capabilities of the ATmega128, and this bit is active on the new MK. You need to reset the M103C to an inactive state. To manipulate configuration bits, use the corresponding section of the programmer script menu.

There is no point in giving a diagram of the music box: it only contains a microcontroller, power supply and a piezo-sound emitter. Power is supplied in exactly the same way as we did when programming the MK. The sound emitter is connected between the common wire (GND pin of the controller) and one of the MK pins, the number of which can be found in the file with the program assembly code (*.asm). At the beginning of the program text for each MK in the comments there is a line: “the sound signal is generated at pin XX.” When the programmer script is completed, the microcontroller exits the programming mode and goes into normal operation. Playback of melodies begins immediately. By connecting a sound emitter, you can check this. You can leave the sound emitter connected while programming the crystal only if the sound is taken from a pin that is not used in SPI, otherwise the additional capacitance on the pin may interfere with programming.

Atmega8 microcontrollers are the most popular representatives of their family. In many ways, they owe this to, on the one hand, simplicity of operation and understandable structure, on the other hand, a fairly wide functionality. This article will cover Atmega8 programming for beginners.

General information

Microcontrollers are everywhere. They can be found in refrigerators, washing machines, telephones, factory machines and a large number of other technical devices. Microcontrollers range from simple to extremely complex. The latter offer significantly more features and functionality. But you won’t be able to understand complex technology right away. Initially, you need to master something simple. And Atmega8 will be taken as a sample. Programming on it is not difficult thanks to its competent architecture and friendly interface. In addition, it has sufficient performance to be used in most. Moreover, they are used even in industry. In the case of Atmega8, programming requires knowledge of languages ​​such as AVR (C/Assembler). Where to start? Mastering this technology is possible in three ways. And everyone chooses for themselves where to start working with Atmega8:

  1. Programming via Arduino.
  2. Purchase of a ready-made device.
  3. Self-assembly of a microcontroller.

We will consider the first and third points.

Arduino

This is a convenient platform designed in a form that is suitable for quickly creating various devices. The board already has everything you need in the form of the microcontroller itself, its harness and programmer. By following this path, a person will receive the following benefits:

  1. Low threshold requirements. You do not need to have special skills to develop technical devices.
  2. A wide range of elements will be available for connection without additional preparation.
  3. Quick start to development. With Arduino you can jump straight into creating devices.
  4. Availability of a large number of training materials and examples of implementations of various designs.

But there are also certain disadvantages. So, Arduino programming Atmega8 does not allow you to dive deeper into the world of the microcontroller and understand many useful aspects. In addition, you will have to learn a programming language, which differs from the ones used by AVR (C/Assembler). And one more thing: Arduino has a rather narrow range of models. Therefore, sooner or later there will be a need to use a microcontroller, which is not used in boards. But in general, this is a good option for working with Atmega8. Programming via Arduino will give you a confident start in the world of electronics. And a person is unlikely to give up because of failures and problems.

Self-assembly

Thanks to the friendly design, you can make them yourself. After all, this requires cheap, affordable and simple components. This will allow you to thoroughly study the design of the Atmega8 microcontroller, the programming of which after assembly will seem easier. Also, if necessary, you can independently select other components for a specific task. True, there is a certain disadvantage here - complexity. It is not easy to assemble a microcontroller on your own when you do not have the necessary knowledge and skills. We will consider this option.

What is needed for assembly?

First you need to get Atmega8 itself. Programming a microcontroller without it, you know, is impossible. It will cost several hundred rubles - while providing decent functionality. There is also the question of how the Atmega8 will be programmed. USBAsp is quite good device, which has proven itself to be the best. But you can use some other programmer. Or assemble it yourself. But in this case, there is a risk that if created poorly, it will turn the microcontroller into a non-functional piece of plastic and iron. It also wouldn't hurt to have a breadboard and jumpers. They are not required, but will save you nerves and time. And finally, you need a 5V power source.

Atmega8 programming for beginners using an example

Let's look at how, in general terms, a device is created. So, let's say we have a microcontroller, an LED, a resistor, a programmer, connecting wires, and a power supply. The first step is writing the firmware. By it we mean a set of commands for the microcontroller, which is presented as a final file that has special format. It is necessary to specify the connection of all elements, as well as interaction with them. After this, you can begin assembling the circuit. The VCC pin should be powered. To any other, designed to work with devices and elements, first a resistor is connected, and then an LED. In this case, the power of the first depends on the power requirements of the second. You can use the following formula: R=(Up-Ups)/Is. Here p is the power and s is the LED. Let's imagine that we have an LED that consumes 2V and requires a supply current of 10 mA, convert it into a form more convenient for mathematical operations and get 0.01A. Then the formula will look like this: R=(5V-2V)/0.01A=3V/0.01A=300 Ohm. But in practice it is often impossible to select the ideal element. Therefore, the most suitable one is taken. But you need to use a resistor with a resistance higher than the value obtained mathematically. Thanks to this approach, we will extend its service life.

What's next?

So we have a little diagram. Now all that remains is to connect the programmer to the microcontroller and write the firmware that was created into its memory. There is one point here! When building a circuit, it is necessary to create it in such a way that the microcontroller can be flashed without desoldering. This will save time, nerves and extend the life of the elements. Including Atmega8. In-circuit programming, it should be noted, requires knowledge and skills. But it also allows you to create more advanced designs. After all, it often happens that during desoldering, elements are damaged. After this, the diagram is ready. You can apply voltage.

Important points

I would like to give it to beginners useful tips about Atmega8 programming. Do not change built-in variables and functions! It is advisable to flash the device with the created program after checking it for the absence of “eternal loops”, which will block any other interference, and using a good transmitter. If you use a homemade product for these purposes, you should be mentally prepared for the microcontroller to fail. When you flash a device using a programmer, you should connect the corresponding outputs VCC, GND, SCK, MOSI, RESET, MISO. And do not violate safety precautions! If technical characteristics It is stipulated that there should be a power supply of 5V, then you need to adhere to exactly this voltage. Even the use of 6V elements can negatively affect the performance of the microcontroller and shorten its service life. Of course, 5V batteries have certain differences, but, as a rule, everything is within reasonable limits. For example, the maximum voltage will be kept at 5.3V.

Training and improvement of skills

Fortunately, Atmega8 is a very popular microcontroller. Therefore, finding like-minded people or simply knowledgeable and skillful people will not be difficult. If you don’t want to reinvent the wheel, but just want to solve a certain problem, then you can search for the required scheme on the vast world wide web. By the way, a little hint: although robotics is quite popular in the Russian-speaking segment, if there is no answer, then you should look for it in the English-speaking segment - it contains an order of magnitude more information. If there are certain doubts about the quality of the existing recommendations, then you can look for books that discuss Atmega8. Fortunately, the manufacturing company takes into account the popularity of its developments and supplies them with specialized literature, where experienced people tell what and how, and also give examples of how the device works.

Is it difficult to start creating something of your own?

It is enough to have 500-2000 rubles and a few free evenings. This time is more than enough to get acquainted with the Atmega8 architecture. After a little practice, you can easily create your own projects that perform specific tasks. For example, a robotic arm. Atmega8 alone should be more than enough to convey the basic motor functions of the fingers and hand. Of course, this is a rather difficult task, but it is quite feasible. In the future, it will be possible to create complex things that will require dozens of microcontrollers. But this is all ahead, before that you need to get good school practice on something simple.

To transfer from a computer to a microcontroller we need USBasp and the AVRDUDE program.Today there is a wide selection of programmers designed for programming AVR microcontrollers. Among them you can find many homemade ones, which can hardly even be called programmers, since they are directly connected to the COM port using just a few resistors. However modern computers and laptops are practically no longer equipped with COM ports, so one of the main criteria when choosing a programmer is the ability to connect it to USB port u. The cheapest, simplest and most common is the USBasp programmer. It can be purchased at almost any radio store at affordable price. Its cost is Chinese internet The store ranges from $1.5 to $3.

Programmer USBasp

The computer communicates with the microcontroller using the USBasp programmer via the USB port, and data is transmitted via the interface SPI S erial P eripheral I interface(serial peripheral interface). To communicate the MK with the programmer, special pins are used: MOSI, MISO, SCK, RESET, VCC, GND. Although SPI assumes the use of only three pins MOSI, MISO and SCK, but we will use all six pins.

When exchanging data via interface SPI The microcontroller can simultaneously either receive (MISO pin) or transmit data (MOSI pin). Setting the mode of receiving or transmitting data is carried out by applying a certain pulse to the SCK pin.

The programmer connector, as a rule, has 10 pins and is connected to the microcontroller using a 10-wire cable. However, it is more convenient to use cables that have a 6-pin adapter, since in this case all pins are occupied. For a ten-pin connector, one pin remains unoccupied, and four pins are connected to the common wire (GND).

In order for the computer to detect the programmer, you must install the USBasp driver.

A photo of the programmer connected to the ATmega8 microcontroller is shown below.

The only drawback or, more correctly, minor inconvenience of this programmer is that it is not supported (without various tricks) by Atmel Studio, so you have to use third party program. The most proven one is AVRDUDE.

Settings

Now we just have to complete the final step. Launch the AVRDUDE program. By default, the Program tab opens. At the bottom of the window in the Settings menu, select the type of programmer usbasp. Next in category Microcontroller choose our ATmega8 microcontroller. Below in the category Flash click on the ellipsis icon and in the menu that opens, specify the path to the compiled file with the extension hex. The path to the file and the file itself will be the same as we previously specified in .

To make sure that the programmer is detected by the operating system (the programmer driver is installed correctly) and is correctly connected to the microcontroller, click on the button Reading. If there are no errors, a window will appear with the entry “ The generator calibration cells have been read!” And the hexadecimal number will be displayed in the top window. Each MK has its own number.

Before you record new program It is recommended to clear the microcontroller memory. This can be done by clicking on the button Erase everything. As a result, a window will appear indicating that the crystal is clean.

Now click on the Program button in the category Flash. When the program is successfully recorded in the MK, a window appears with the entry below.

The result of the recorded, or, as they also say, firmware program is a lit LED connected to the PC0 pin of our microcontroller.

Good day. Let's continue. After we got acquainted with the process of debugging the program we wrote in “atmel studio” and virtually assembled a circuit with one LED in “proteus”, it was time to assemble the circuit in hardware and flash the microcontroller.

To program a prototype ( atmega 8) we will use the USBASP programmer. It looks like this:

A cable will be connected to the connector, into which jumpers are connected, which in turn will be connected to the sockets of the breadboard on which the microcontroller is installed:

The first pin is marked on the connector with an arrow.


After we figured out the programmer. Let's move on to assembling the circuit in hardware. We mount the microcontroller on a breadboard. Let me remind you that the first leg is marked on the MK with a small circle.

The task is to connect the programmer pins to the “stone” pins.

We connect jumpers to the 10-pin connector. We use the following pins MOSI, RST, SCK, MISO, VTG (VCC), GND.

I hope you have already downloaded the datasheet on atmega8. If not, you can download it. We look at the pinout of the microcontroller pins.

We connect jumpers to the following pins:

  • VCC to pin 7 of the MK;
  • SCK to pin 19 of the MK;
  • MISO to pin 18 of the MK;
  • MOSI to pin 17 of the MK;
  • GND (programmer pin 10) to pin 8 of the MK;
  • RST to 1 pin of MK;

For further successful work, operating system When starting the shaitan machine (programmer) for the first time, suggest installing the drivers necessary for the device to operate.

There shouldn't be any problems when working with the expediter. Download. Create a folder into which we unpack the downloaded archive. Then in the Hardware Installation Wizard we specify the path to the folder with the unzipped driver.

If you are running Windows 7 or higher, you may experience minor difficulties. The drivers for the programmer are quite old, so they do not have digital signature. When you try to install such a driver, the operating system will display something like this *

"The digital signature of drivers required for of this device. At last change hardware or software may have been installed that was incorrectly signed or damaged file or malware unknown origin. (Code 52)."

To correct the situation, you need to disable driver digital signature verification. I won’t describe how to disable it (everyone has their own operating system), they can be found on the Internet.

After you disable signature verification, in the Hardware Installation Wizard, specify the path to the folder with the unzipped driver.

I hope everything worked out for you and the programmer is ready to work.

Let's move on to assembling the circuit with the LED.

To flash the microcontroller firmware we will use the “avrdudeprog” program. It is in the general archive.

Select atmega8 from the list of microcontrollers. After selecting the MK, a window will appear informing you that the fuse and Lock bits are set by default.

Then open the Fuses tab. In simple words Fuses are MK configuration settings that are best not played with. For the case when you purchased the same controller as me and you do not have an external quartz resonator (you use an internal oscillator clock frequency), check exactly the same boxes as shown in the picture. There must be a check mark next to the “inverse” item.

The configured settings “command” the Atmega8A to perform its work subject to clocking from the internal oscillator (clocking frequency 8 MHz). In order for the settings to take effect, you need to click the “Programming” button. But before pressing, double check that everything is set properly.

Return to the “Program” page.

After we have already told the program which microcontroller we will be flashing, we select the firmware file that we wrote in the last lesson. It has a HEX extension. Located in the "Debug" folder

Before flashing the “pebble”, click on the “Erase everything” button. This will protect you from incomprehensible mistakes (what if the stone has already been sewn):

We enjoy the result of our work :) To be continued...

Why exactly from this line?

Well, maybe someone knows, maybe someone doesn’t know, the AVR microcontroller is a product of Atmel.

Well, why exactly from the AVR line?

Firstly, AVR microcontrollers - they are widely available, they are in any store, their price is low.

Secondly, due to the availability of numerous software for their programming and firmware, which is also important in our time.

That is, when writing programs you will not violate anyone's copyrights.

Thirdly, it is precisely because I have the most knowledge in my head and skills in programming this particular line.

Therefore, we will program specifically for AVR microcontrollers.

We will start with such a representative of this line as the Atmega 8 microcontroller.

ATMEGA 8A

Why exactly from it, from Atmega 8?

Because, firstly, it is quite a full-fledged microcontroller and inexpensive.

It has three I/O ports on board. We will not go into detail here about what ports are. In short, ports are data buses that operate in two directions - both output and input.

Port B.

Port B, which is incomplete, has 6 legs.

0, 1 leg, 2, 3, 4 and 5. That is, 6 legs.
Port C We also have an incomplete one, from zero to six legs.
But port D We have a full-fledged port, it has all 8 legs, i.e. data byte from 0 to 7.
The microcontroller is powered by 5 volts. You can also power it from 3.3 volts, it will also work fine. But the only thing is that the clock frequency can only be set to a maximum of 8 megahertz. We cannot set 16 at three volts, we can only set it at five volts. Power is supplied to leg 7. The common wire is the eighth.
Well now let's see where we can get software for programming.
Atmel has its own website www.atmel.com. On the main page, you don’t need to go far, on the right side of the page under the main banner there is Download Atmel Studio.



Related publications