Portal for car enthusiasts

Programming atmel controllers for beginners. The device and programming of AVR microcontrollers

Lesson 0

So, today we are opening a series of lessons on programming microcontrollers of the AVR family.

The following questions will be discussed today:

  1. What is a microcontroller?
  2. Where are microcontrollers used?

Introduction.

Microcontrollers are everywhere. In telephones, washing machines, "smart homes", machine tools in a factory, as well as in countless technical devices. Their widespread use makes it possible to replace complex analog circuits with more compressed digital ones.

So what is a microcontroller?

microcontroller (Micro Controller Unit, MCU) - a microcircuit designed to control electronic devices. You can imagine it as a simple computer that can interact with external devices. For example, open and close transistors, receive data from temperature sensors, display data on lcd screens, etc. . In addition, the microcontroller can perform various processing of input data, just like your personal computer.

That is, microcontrollers open up almost unlimited possibilities for us to control any devices, thanks to the presence of I / 0 ports (input / output ports (output)), as well as the possibility of programming them.

Where are microcontrollers used?

  1. Household appliances (Washing machines, microwave ovens, etc.).
  2. Mobile technology (Robots, robotic systems, communications, etc.).
  3. Industrial equipment (Machine control systems).
  4. Computing equipment (motherboards, peripheral devices control systems).
  5. Entertainment equipment (Children's toys, decorations).
  6. Vehicles (Car engine management systems, security systems)

This is not a complete list of applications for microcontrollers. Often, it is very beneficial to replace the set of control chips with a single microcontroller, due to the simplification of production, lower power consumption.

Getting started with AVR

AVR- a family of Atmel microcontrollers. They have sufficient performance for most amateur devices. They are also widely used in industry.

Microcontrollers (hereinafter referred to as MK) have firmly entered our lives, on the Internet you can find a lot of interesting circuits that are executed on MK. What can not be collected on the MK: various indicators, voltmeters, household appliances (protection devices, switching devices, thermometers ...), metal detectors, various toys, robots, etc. list can be very long. I saw the first circuit on a microcontroller 5-6 years ago in a radio magazine, and almost immediately turned the page, thinking to myself "I still can't assemble it." Indeed, at that time MK for me was something very complicated and misunderstood device, I had no idea how they work, how to flash them, and what to do with them in case of incorrect firmware. But about a year ago, I first assembled my first circuit on an MK, it was a digital voltmeter circuit on 7 segment indicators, and an ATmega8 microcontroller. It so happened that I bought the microcontroller by accident when I was standing in the radio parts department, the guy in front of me was buying an MK, and I also decided to buy it and try to assemble something. In my articles I will tell you about AVR microcontrollers, I will teach you how to work with them, we will consider firmware programs, we will make a simple and reliable programmer, we will consider the firmware process and, most importantly, problems that may arise not only for beginners.

The main parameters of some microcontrollers of the AVR family:

microcontroller

FLASH memory

RAM memory

EEPROM memory

I/O ports

u supply

Additional parameters of MK AVR mega:

Operating temperature: -55…+125*С
Storage temperature: -65…+150*С
Voltage at the RESET pin relative to GND: max 13V
Maximum supply voltage: 6.0V
Maximum I/O line current: 40mA
Maximum current on the power line VCC and GND: 200mA

Pin assignments for ATmega 8X models

Pin assignments for ATmega48x, 88x, 168x models

Pin assignment for ATmega8515x models

Pin assignments for ATmega8535x models

Pin assignment for ATmega16, 32x models

Pin assignments for ATtiny2313 models

At the end of the article, an archive with datasheets for some microcontrollers is attached.

FUSE setting bits MK AVR

Remember, a programmed fuse is 0, an unprogrammed one is 1. Be careful when setting fuses, an erroneously programmed fuse can block the microcontroller. If you are not sure which fuse you need to program, it is better to flash the MK without fuses for the first time.

The most popular microcontrollers for radio amateurs are ATmega8, followed by ATmega48, 16, 32, ATtiny2313 and others. Microcontrollers are sold in TQFP packages and DIP, I recommend that beginners buy in DIP. If you buy TQFP, it will be more problematic to flash them, you will have to buy or solder the board. their legs are very close to each other. I advise microcontrollers in DIP packages, put them on special sockets, it's convenient and practical, you don't have to solder the MK if you want to reflash it, or use it for another design.

Almost all modern microcontrollers have the ability to in-circuit programming ISP, i.e. if your microcontroller is soldered to the board, then in order to change the firmware we do not have to unsolder it from the board.

6 pins are used for programming:
RESET- MK input
VCC- Plus supply, 3-5V, depends on the MK
GND- Common wire, minus power.
MOSI- MK input (information signal in MK)
MISO- MK output (information signal from MK)
SCK- MK input (clock signal in MK)

Sometimes they also use the XTAL 1 and XTAL2 outputs, quartz clings to these outputs if the MK will work from an external generator, in ATmega 64 and 128 the MOSI and MISO outputs are not used for ISP programming, instead the MOSI outputs are connected to the PE0 leg, and MISO to PE1. When connecting the microcontroller to the programmer, the connecting wires should be as short as possible, and the cable from the programmer to the LPT port should also not be too long.

The marking of the microcontroller may contain incomprehensible letters with numbers, for example, Atmega 8L 16PU, 8 16AU, 8A PU, etc. The letter L means that the MK operates at a lower voltage than the MK without the letter L, usually 2.7V. The numbers after the hyphen or space 16PU or 8AU indicate the internal frequency of the oscillator that is in the MK. If the fuses are set to work from an external quartz, the quartz must be set to a frequency not exceeding the maximum according to the datasheet, this is 20MHz for ATmega48/88/168, and 16MHz for other atmegas.

Schematic diagram of the programmer on the LPT port is shown in the figure. Use the 74AC 244 or 74HC244 (K1564AP5), 74LS244 (K555AP5) or 74ALS244 (K1533AP5) chip as a bus driver.

LED VD1 indicates the recording mode of the microcontroller,

LED VD2 - reading,

LED VD3 - the presence of circuit power.

The circuit takes the voltage required for power supply from the ISP connector, i.e. from the programmable device. This circuit is a revised STK200/300 programmer circuit (added LEDs for ease of operation), so it is compatible with all PC programmer programs that work with the STK200/300 circuit. To work with this programmer, use the program CVAVR

The programmer can be made on a printed circuit board and placed in the LPT connector housing, as shown in the figures:




To work with the programmer, it is convenient to use an LPT port extension cable, which is easy to make yourself (for example, from a Centronix cable for a printer), the main thing is not to "spare" the conductors for the ground (18-25 feet of the connector) or buy it. The cable between the programmer and the microchip to be programmed should not exceed 20-30 cm.

Lesson 1

Hello dear readers!

Today we will get close to programming AVR microcontrollers by gathering everything you need to get started. So let's get started.

There are two ways to master AVR. Let's consider each of them.

1.Arduino

Arduino is an electronic designer and a convenient platform for the rapid development of electronic devices. That is, the Arduino board includes everything you need for the rapid development of technical devices. It incorporates an AVR microcontroller, its harness (the necessary components for the operation of the microcontroller), a programmer (a device for “flashing” the microcontroller).

Consider the advantages of this approach:

  1. Rapid start of development. By purchasing this product, you can immediately proceed to the beginning of work with the microcontroller, without additional preparation.
  2. Low entry threshold. You do not need any special skills to start developing technical devices.
  3. A wide range of pluggable "shields"
  4. Community support. On the Internet you will find many lessons and tasks based on the use of the Arduino platform.

However, there are cons that outweigh the positives of the platform. Arduino :

  1. Having bought an Arduino, you lose the opportunity to plunge deeper into the world of AVR, find out what a programmer is, the necessary harness and much more.
  2. Narrow line of models. Very often it is necessary to choose a specific microcontroller for a specific task. Unfortunately, Arduino will not be able to provide you with a range of models for every conceivable and unthinkable task. And sooner or later you will be faced with the need to use a microcontroller that is not in the line of Arduino boards.
  3. Another programming language. The programming language of the Arduino platforms differs significantly from the standard AVR C, AVR ASM. That is, it becomes necessary to switch to the Arduino IDE and learn the Arduino language.

However, despite all the negative aspects, Arduino is quite suitable for the initial study of AVR microcontrollers. But do not abuse it if you really want to know the world of microcontrollers and plunge into it with your head. Therefore, I will offer you the second, in my opinion the best way to get started with the AVR family.

2.Self assembly.

AVR microcontrollers are quite friendly to beginners and allow you to assemble everything you need for their work on their own, from simple, affordable and cheap components.

The advantages of this approach:

  1. Dive depth. You will learn much more by collecting everything you need on your own, gaining a lot of useful knowledge and skills.
  2. Possibility of independent choice of components for solving the task.
  3. Standard AVR C/AVR ASM languages. Possibility to choose the programming environment that suits you. Huge database of knowledge and lessons on these languages.
  4. Cheapness. Often (but not always), it is quite profitable to refuse a ready-made solution, and assemble everything yourself.

Cons of this approach:

  1. Complexity. Assembling everything yourself for the first time, in the absence of skills and knowledge, is quite more difficult than purchasing a ready-to-use product.

But we are not afraid of difficulties, because after going through them we will learn a lot of new and useful things!

So, let's start collecting the necessary things to get started.

1.Microcontroller.

2.Programmer.

Most likely you can buy it in the nearest store, or order using the Internet. However, it is possible to independently assemble a programmer connected to the COM port of a personal computer, consisting of the simplest components, with a total cost of about 50 rubles. Look for links to instructions for self-assembly of the programmer at the end of the article.

Kiselev Roman, May 2007 Article updated 26 May 2014

So, what is a microcontroller (hereinafter referred to as MK)? This is, relatively speaking, a small computer placed in a single integrated circuit. It has a processor (arithmetic logic unit, or ALU), flash memory, EEPROM memory, lots of registers, I/O ports, and additional bells and whistles such as timers, counters, comparators, USARTs, etc. The microcontroller, after power-up, boots up and starts executing the program stored in its flash-memory. At the same time, it can control a wide variety of external devices through the I / O ports.

What does this mean? This means that in the MK you can implement any logic circuit that will perform certain functions. This means that MK is a microcircuit, the internal contents of which, in fact, we create ourselves. That allows, having bought several completely identical MKs, to assemble completely different circuits and devices on them. If you want to make any changes to the operation of the electronic device, then you will not need to use a soldering iron, it will be enough just to reprogram the MK. You don't even need to take it out of your device if you're using an AVR, as these MCUs support in-circuit programming. In this way, microcontrollers bridge the gap between programming and electronics.

AVRs are 8-bit microcontrollers, that is, their ALU can perform simple operations with only 8-bit numbers in one cycle. Now it's time to talk about which MK we will use. I am working with MK ATMega16. It is very common and you can buy it in almost any radio parts store for about 100 rubles. If you don’t find it, then you can buy any other MEGA series MK, but in this case you will have to look for documentation for it, because the same “legs” of different MKs can perform different functions, and by connecting, it would seem, all the conclusions are correct, you might get a working device, or maybe just a cloud of smelly smoke. When buying an ATMega16, make sure it comes in a large 40-pin DIP package and also buy a socket to fit it into. To work with it, you will also need additional devices: LEDs, buttons, connectors, etc.

ATMega16 has a very large number of various functions. Here are some of its characteristics:

  • Maximum clock speed - 16 MHz (8 MHz for ATMega16L)
  • Most commands are executed in one cycle
  • 32 8-bit working registers
  • 4 full 8-bit I/O ports
  • two 8-bit timers/counters and one 16-bit
  • 10-bit analog-to-digital converter (ADC)
  • internal clock generator at 1 MHz
  • analog comparator
  • interfaces SPI, I2C, TWI, RS-232, JTAG
  • in-circuit programming and self-programming
  • pulse width modulation (PWM) module

Full specifications of this device, as well as instructions for their use, can be found in the Datasheet for this MK. True, it is in English. If you know English, then be sure to download this Datasheet, it contains a lot of useful information.

Let's finally get down to business. I recommend making a special breadboard for the microcontroller, on which it will be possible to assemble any electrical circuit with the microcontroller without a soldering iron (or almost without it). The use of such a board will greatly facilitate the work with the MK and speed up the process of learning its programming. It looks like this:

What will be needed for this?

First, the board itself is required. I bought a ready-made one in a radio parts store for 115 rubles. Then I soldered all the necessary parts to it. It turned out to be an incredibly convenient thing, on which you can assemble any electrical circuit in a matter of minutes by poking cables and installing microcircuits and indicators.

To connect circuit elements, it is very convenient to use loops, at the ends of which connectors are installed. These connectors are put on the "legs" sticking out next to each MK port. The microcontroller should be installed in the socket, and not soldered to the board, otherwise it will be very difficult to remove it in case you accidentally burn it. Below is the pinout of MK ATMEGA16:

Let us explain which legs we are now interested in.

  • VCC - power is supplied here (4.5 - 5.5 V) from a stabilized source
  • GND - ground
  • RESET - reset (at low voltage level)
  • XTAL1, XTAL2 - a quartz resonator is connected here
  • PA, PB, PC, PD - input / output ports (A, B, C and D, respectively).

As a power source, you can use anything that produces 7-11 V DC. For stable operation of the MK, a stabilized power supply is needed. As a stabilizer, you can use microcircuits of the 7805 series. These are linear integrated stabilizers, the input of which is supplied with 7-11 V DC unregulated current, and the output is 5 V stabilized. Before and after the 7805, you need to put filter capacitors (electrolytic for filtering low-frequency noise and ceramic for high). If you cannot find a stabilizer, then you can use a 4.5 V battery as a power source. From it, the MK must be powered directly.

Below is the MK connection diagram:

Let's now figure out what is here for what.

BQ1 is a quartz resonator that sets the operating frequency of the MK. You can put any up to 16 MHz, but since we plan to work with a COM port in the future, I recommend using resonators for the following frequencies: 14.7456 MHz, 11.0592 MHz, 7.3725 MHz, 3.6864 MHz or 1 .8432 MHz (it will become clear why later). I used 11.0592 MHz. It is clear that the higher the frequency, the higher the speed of the device.

R1 is a pull-up resistor that maintains 5V at the RESET input. A low voltage level at this input indicates a reset. After the reset, the MK boots up (10 - 15 ms) and starts executing the program again. Since this is a high-resistance input, you cannot leave it "dangling in the air" - a small pickup on it will lead to an unexpected reset of the MK. That's what R1 is for. For reliability, I also recommend installing a capacitor C6 (no more than 20 microfarads).

SB1 - reset button.

The quartz resonator and filter capacitor C3 should be located as close as possible to the MK (no further than 5-7 cm), because otherwise interference may occur in the wires, leading to malfunctions of the MK.

The programmer itself is circled in a blue rectangle in the diagram. It is convenient to make it in the form of a wire, one end of which is plugged into the LPT port, and the other end into a certain connector next to the MK. The wire must not be excessively long. If there are problems with this cable (usually not, but anything can happen), then you will have to solder the Altera ByteBlaster adapter. How to do this is written in the description for the AVReal programmer.

Now that we've got the hardware out of the way, it's time to move on to the software.

There are several development environments for AVR programming. First, this is AVR Studio - the official programming system from Atmel. It allows you to write in assembler and debug programs written in assembler, C and C++. IAR is a commercial programming system in C, C++ and assembly language. WinAVR is an open source compiler. AtmanAVR is a programming system for AVR with an almost one-to-one interface similar to that of Visual C++ 6. AtmanAVR also allows you to debug programs and contains many helper functions that make it easier to write code. This programming system is commercial, but, according to the license, it can be used "for free" for a month.

I suggest getting started with IAR as the most "transparent" development environment. In IAR, the project is entirely created by “handles”, therefore, having made several projects, you will already clearly know what each line of code means and what will happen if you change it. When working with AtmanAVR, you will either have to use a pre-created template, which is very cumbersome and difficult to understand for a person with no experience, or have a lot of problems with header files when building a project from scratch. Having dealt with IAR, we will later look at other compilers.

So, first get some IAR. It is very common and should not be a problem to find. After downloading IAR 3.20 from somewhere, install the compiler / working environment, and run it. After that, you can start working.

Launching IAR, select file/new/workspace, select the path to our project and create a folder for it and give it a name, for example, "Prog1". Now we create a project: Project / Create new project… Let's call it also - "Prog1". Right-click on the project title in the project tree and select "Options"

Here we will configure the compiler for a specific MK. First, you need to select the ATMega16 processor type on the Target tab, on the Library Configuration tab, check the Enable bit definitions in I / O-include files checkbox (so that you can use the bit names of various MK registers in the program code), select the C library type in the same place /EC++. In the ICCAVR category, on the Language tab, check the Enable multibyte support checkbox, and on the Optimization tab, turn off optimization (otherwise it will ruin our first program).

Next, select the XLINK category. Here you need to define the format of the compiled file. Since we are now setting the options for the debug mode (Debug), as described in the title, we need to get a debug file as output. Later we will open it in AVR Studio. To do this, you need to select the .cof extension, and the file type is ubrof 7.

Now click OK, then change Debug to Release.

Again we go to Options, where all the parameters, except for XLINK, are set the same. In XLINK, change the extension to .hex and the file format to intel-standard.

That's all. Now we can start writing our first program. Create a new Source/text and type the following code in it:

#include"iom16.h" short unsigned int i; void main( void) ( DDRB = 255; PORTB = 0; while(1) { if(PORTB == 255) PORTB = 0; else PORTB++; for(i=0; i

The file "iom16.h" is located in the folder (C:\Program Files)\IAR Systems\Embedded Workbench 3.2\avr\inc. If you are using another MK, for example, ATMega64, then select the "iom64.h" file. These header files store information about the MK: the names of registers, bits in registers, interrupt names are defined. Each individual pin of port A, B, C, or D can operate as either an input or an output. This is determined by the Data Direction Register (DDR). 1 makes the "leg" an output, 0 an input. Thus, setting, for example, DDRA = 13, we make the “legs” PB0, PB2, PB3 outputs, the rest are inputs, because 13 in binary would be 00001101.

PORTB is a register that determines the state of the "legs" of the port. By writing 0 there, we set the voltage to 0 V at all outputs. Then there is an infinite loop. When programming MCUs, they always do an infinite loop in which the MCU performs some action until it is reset or until an interrupt occurs. In this cycle, they write, as it were, “background code”, which the MK performs at the very last turn. This may be, for example, the output of information on the display. In our case, the contents of the PORTB register are incremented until it is full. After that, everything starts over. Finally, a for loop for ten thousand cycles. It is needed to form a visible delay in switching the state of port B.



Now we save this file in the project folder as Prog1.c, copy the iom16.h file to the project folder, select Project / Add Files and add "iom16.h" and "Prog1.c". Select Release, press F7, the program compiles and a message should appear:


Total number of errors: 0
Total number of warnings: 0

Here is a photo of my programmer:

Download the AVReal programmer. Copy it (AVReal32.exe) to the Release/exe folder, where the Prog1.hex file should be. We supply power to the MK, connect the programming cable. Open Far Manager (it is most convenient to flash MK in it), go to this folder, press Ctrl + O. Since we have a completely new MK, we fill

avreal32.exe +MEGA16 -o11.0592MHZ -p1 -fblev=0,jtagen=1,cksel=F,sut=1 –w

Don't forget to set the frequency correctly if you're not using 11059200 Hz! At the same time, so-called. fuses - registers that control its operation (use of an internal generator, Jtag, etc.). After that, it is ready to receive the first program. The programmer is given the used LPT port, frequency, file name and others as parameters (all of them are listed in the description for AVReal). We type:

Avreal32.exe +Mega16 -o11.0592MHz -p1 -e -w -az -% Prog1.hex

If the connection is correct, the programmer will report successful programming. There is no guarantee that this will work the first time (the first time the program is called). I myself can be programmed from the second time. Perhaps the LPT port is buggy or there is interference in the cable. If problems occur, check your cable carefully. I know from my own experience that 60% of malfunctions are associated with a lack of contact in the right place, 20% with the presence in an unnecessary one, and another 15% with erroneous soldering. If all else fails, read the description for the programmer, try to assemble Byte Blaster.

Let's assume everything works for you. If you now connect eight LEDs to port B of the MK (do this with the MK turned off, and it is advisable to turn on 300-400 Ohm resistors in series with the LEDs) and apply power, then a small miracle will happen - a “wave” will run through them!

© Kiselev Roman
May 2007