What pins are needed for programming pic microcontrollers. Tutorial on programming PIC controllers for beginners (E.A

I have repeatedly asked myself the question of which language to start learning from. I firmly answer - C, because. There is a lot of routine and conventions in asma, which deprives creativity. You must constantly check and recheck yourself to see if you have forgotten this or that action. Assma has its undeniable advantages, but more about them later, because... This can only be felt in practice. We decided on the language. In reality, there is no need to learn C. I'll tell you this - my C is basically ten puzzles and a sea of ​​logic that I combine. You may not know anything, it is important to understand the mechanism, i.e. what influences what and what leads to what. It's like playing Tetris in which you just need to spin the pieces and place them closer together. If you have played Tetris (I'm not sure if you know this game), then you will easily understand what C is.

Next about the breadboard (prototyping board). And I was asked a question on this topic. And I came to the conclusion that a person who is no stranger to electronics is not interested in making some kind of board or scarf with buttons and LEDs. A student will find the flashing light, beeper and button interesting. But not for an adult. Moreover, all this can be done in Proteus. Proteus is studied in 30 minutes. Then you ask me, what should I do? Make a practical device for which you will have a goal - the goal is to complete this device to the end. This is the most important psychological stimulus.

What components should the device consist of? Several buttons (at least a dozen), seven-segment indicators of 2-5 digits, a PIC16F628A microcontroller (or without A) (you can fantasize a lot on this microcontroller), and leave 1-2-3 free lines to connect or control something external. For me, it all starts with an idea and a question about what to assemble and connect to the MK, and I immediately think how it will connect to the MK and whether such a connection can work. Well, the actual process of drawing a printed circuit board goes in parallel. It is necessary to know and take into account when drawing that not all legs work equally. And it is precisely this important initial condition that is outlined in the tutorial from the very beginning.

In this regard, your task now, according to my tutorial, is to understand the conclusions (legs), how, which ones, in which direction, under what conditions these conclusions work. As simple as the task is, you will come across a lot of other simple things to learn.

What will you get in the end?
1) Understanding how to connect what and with what.
2) How these connections are managed at the elementary level.
3) You will begin to get used to the interface of the development environment.
4) Start studying the structure of the program text.
5) You will begin to understand the mechanism of the program.


Part 1 Contents

Introduction

1 . Preparing the tools

2. What is a microcontroller and how does it work

3. PIC16F84A command system

4 . What is a program and the rules for its preparation. Creation example

self-oscillating multivibrator programs. Directives.

5 . Integrated design environment MPLAB IDE and work in it

7. Example of creating a program (beginning)

8 . Example of creating a program (continued)

9 . Working in a simulator. Debugging the program

10 . How to track program execution

eleven . Interrupts. Stack. An example of program development with interruptions

12 . Organizing a calculated transition. Working with EEPROM data memory

13 . Flags. Working with flags. How does a digital comparator work? Transfer and loan

14 . An example of using the C flag in a three-byte adder.

Cyclic shift. Multiplication operation

15 . Introduction to the principle of constructing a dynamic display subroutine.

Indirect addressing

16 . Converting binary numbers to BCD. Final

generating the text of the dynamic display subroutine

17. The principle of counting. Working with timer TMR0.

The principle of installing groups of counting commands in the program text

…………………………………………………………………

…………………………………………………………………

Introduction

Epigraph: a programmer working in assembly language must be the “Lord of the Rings”. And one more thing: banality is a tired truth.

(you'll understand later)

People come to microprocessor technology in different ways. Personally, for the time being, I did not feel any particular need to do this, until, at one fine moment, I realized that I was beginning to not correspond to the times. What I had developed “before” turned out to be hopelessly outdated, and also “looks funny” both against the “background” of the modern element base, and against the “background” of the knowledge that you need to have in order to work with it.

In addition, for me personally, it was somehow neither beautiful nor worthy to “eat scraps from the royal table” if there was an opportunity to “sit down at it as a full-fledged participant in the meal.”

It was necessary to choose: either “give up” and move into the category of gradually “extinct” (disqualified),

or deal with these “terrible and terrible” microcontrollers, which more and more resembled “a plug in every barrel.”

I didn’t want to “die out” at all, so the choice was clear. And then something began that resembled “moving through the jungle.”

The information “mess” in this “sector” turned out to be so impressive that “the hair stood on end.”

Where to go? “There’s nowhere to retreat, Moscow is behind us.”

By the way, many people are now in exactly the same position (I know from letters), for whom “entry” into microprocessor technology has become not only some kind of “fad,” but a very natural necessity of life, which is quite understandable, because m/controllers are part of almost any more or less modern, small-sized (and not only) equipment (and “the further into the forest, the more firewood”...).

Only the Lord God knows what I suffered through: there was no help and I had to rely only on my own strength.

After all these “ordeals”, a logical question arose: “What is this all about? Is it really possible that everyone who intends to “encroach” on these “pieces of hardware” must “break his nose bloody” by driving it across the “battery”?

Is it really impossible to do without this, or at least make this process less painful?

I figured...

But, by God, it’s possible!

True, you will have to “plow an unplowed field,” but for a combination of reasons, this makes sense.

What you will read in the "Tutorial..." is the result of the above-mentioned painful process, presented "on a silver platter."

The principle of presenting information is the maximum degree of “chewing”, since the “Self-Teacher...” is intended specifically for beginners.

One of the main troubles of novice programmers is the lack of consistency in the perception of information and its “overdose”, associated with an excessive desire to quickly achieve the desired goal, without taking into account objective factors.

This kind of desire, of course, is commendable, but in the absence of planning, clearly expressed priorities and the ability, at first, to consciously limit the amount of perceived information to only the most truly necessary, it plays a cruel joke on a person.

The result is a “mess” in the head, disorientation in the flow of information and, in the worst case, regret about wasted time, although, by and large, everything is not as super complicated as it might seem at first glance.

I'm not saying it's easy at all. You'll have to work, but you shouldn't be scared at all, so

as “the devil is not as terrible as he is painted.”

Another problem is the underestimation of the enormous importance of knowledge and the ability to apply brainstorming strategies and tactics in practice.

Although any “brainstorming” is useful, the “brainstorming” of a programmer who has at least a basic understanding of his strategy and tactics is much more effective and efficient than the “convulsive actions” of a programmer who does not have these ideas. But the work of a programmer is “all brainstorming”!!!

Everyone has brains, but there are huge problems with the strategy and tactics of this “assault”. You can, foolishly, “get a bullet” (according to a scenario like “heroic death of a programmer”).

IN In my work, I proceed from the fact that the brain is not only a logical “machine”, but also a “container of personality.”

The latter is either clearly underestimated or not taken into account at all by the authors of “creations” similar to mine, which is a huge miscalculation of theirs, nullifying most of their efforts.

This kind of “one-sidedness”, which is widespread, in most cases, leads to the fact that information is perceived by the learner as a logically sophisticated, intense (without a sense of proportion) and “hopeless rape by the author of his (the learner’s) brain”, with the purpose of “mockery” over low level of his training and direct or indirect decrease in “microcontroller” self-esteem.

Of course, in many ways, this is not true, but what can you do, this is the natural, subconscious, defensive reaction of the psyche of a normal person to a large amount of information that it is not ready to work effectively with.

In order to understand the enormous harm of this approach to training, remember about Afghanistan or Chechnya and the fate of those unexamined and psychologically unprepared children who were “thrown into this meat grinder.”

I do not wish you such a fate, and for this reason, in the “Tutorial...”, a peculiar attempt was made to gradually “integrate” zeros and ones into the personality (their “spiritualization”) and the formation of a certain “ideology of a software wax officer” (“combat spirit", "core"), without which any "war" (programming is a purely male and "hooligan" activity called "war with one's stupidity") is lost without even starting and which is the main basis of any effective "school" of training. I have nothing to compare with, and therefore I work at my own peril and risk.

Don’t judge me harshly, since I work “from scratch” and am not a “psychological specialist”. I hope that other authors will continue this extremely important and the “criminally” ignored “psychological topic.” I would like to believe that when reading the “Self-Teacher...”, you will feel such a friendly and respectful attitude towards your not at all easy work (I know from myself), and your subconscious will not issue SOS signals about the “savage rape of the brain.”

I would like to address separately “hooligans”, “fighters” and “bullies” (in the common sense of these words), whose “brain activity” is clearly expressed.

You don’t need to explain what it means to “take a hit,” “dodge,” “fight back,” and “black eyes” don’t confuse you. For this reason, programming is, first of all, your “patrimony”, where you can have a nice “hunt”.

IN programming, aggressiveness is an advantage, not a disadvantage.

Here you can, from the heart, intellectually “wave your fists” (no restrictions), plus, “break the necks” of many respectable “enemies” (no restrictions), from which, by the way, you will definitely get great pleasure.

So, information will be provided in a certain sequence and according to the principle “from simple to complex.”

Please adhere to this sequence and do not move on to the next sections without understanding the previous ones. This is a leisurely affair and does not require fuss.

I won’t “lump everything into a heap”; I’ll also try not to create “overexertion”. "Tutorial..." is designed for beginners, but it is assumed that they at least know the basics of digital technology.

I express my sincere gratitude to those people who helped in the development of this textbook.

1. Prepare the tools

Microcontrollers (and all processors in general) initially understand only machine codes, that is, a certain set of zeros and ones.

Those who imagine the operation of counters, registers, flip-flops, etc. will immediately understand the nature of machine code.

Since such people are the majority among electronics engineers, in my opinion, they will all agree with this axiom: machine codes are useful in “small doses.”

A That’s when “large doses” begin (complex devices with dozens of packages of m/circuits), then “the brains begin to smoke” even among great electronics engineers with remarkable abilities.

In this case, the most unpleasant thing is that as the circuit complexity of the device increases, the electronics engineer’s work efficiency drops sharply.

And in fact, a lot of effort and money is invested, but the result is something that is not very reliable, bulky, difficult to manufacture, energy-intensive and expensive.

In order to “slam down” all these problems in one fell swoop, the “eggheads” first came up with “large” processors (what is used in computers), and then “small” ones, calling them microcontrollers.

Inside the m/controller there is a “set” of modules, each of which is multifunctional. By manipulating the very powerful capabilities of this “set,” it is possible to implement millions of types of devices.

Naturally, all this “economy” needs to be “steered” somehow. This “taxiing” is what is called programming.

If we are talking about large “arrays” of machine codes, then programming directly (in machine codes) is something you wouldn’t wish on your enemy: there’s no pleasure in it, yes, what a good thing, and you can end up in a “psychiatric hospital” (there are exceptions - people with outstanding abilities and geniuses) . In order for ordinary people to be able to write programs without much effort, various programming languages ​​have been invented.

The point of all of them is to replace machine codes with words, word abbreviations, abbreviations, etc., that is, with what a person can easily and meaningfully perceive and with which he can comfortably operate when composing the text of a program.

All these “digestible amenities”, upon completion of the compilation of the program text, are translated into machine codes with one “light movement of the hand” (the programmer’s brain is not involved).

To make this “light movement of the hand” take place, the “eggheads” came up with the so-called “integrated development environment”.

This is a set of programs in which the programmer works with the maximum degree of comfort, and, moreover, across the entire “array” of tasks he solves (including composing the text of the program, etc., etc.).

What is the first thing to do, for example, for a Russian who has arrived in England and is going to live there?

Learn English.

When “entering” programming, you need to do the same (the task is even much simpler).

The "mother" of all programming languages ​​is assembler.

Although it is considered the simplest, the word “simple” refers primarily to the set of its commands: their number is the minimum necessary, and nevertheless, quite sufficient to solve the most complex problems, but not to the comfortable perception of them by a person.

Assembly instructions are either abbreviations of English words, or a set of the first letters of English phrases, or both.

The minimum "gentleman's" set of assembler for PIKs is 35 commands. In reality, most often, from 10 to 20 commands are used.

In the future, just set yourself up for stupid memorization (at first) of all this English “abracadabra”, such as cramming (I have no inclination towards foreign languages ​​at all, but it’s okay, I’ve mastered it), it’s not such a difficult task, I assure you . In the future, your imaginative thinking and visual memory will help you.

A it's really worth learning assembler because it may not be very

"digestible", but it is in this language that the most compact, fast and reliable programs are written, and for this reason, serious programmers work

mainly in assembler.

Warning: do not mess with assembler at this stage! Everything has its time. For now, a general idea is enough (let it settle in your brain).

Programs for PIKs are compiled primarily in assembler.

Even if the program for them is written in a higher-level language, eventually the integrated development environment will translate everything into assembler.

About the integrated development (design) environment: It performs a whole range of tasks.

In its specialized text editor, the program text is compiled.

The program text cannot be written to PIK, since it only “understands” machine codes. Therefore, it is necessary to convert the program text from assembly language into machine codes.

That is, the so-called assembly (compiling) of the source text of the program is necessary, which is done in the same integrated development environment.

This is where beginners usually get confused: the phrase "assembling the source code of the program" does not mean translating the source text of a program into assembly language (the program text is already written in assembly language), but, on the contrary, converting the text of a program written in assembly language into machine codes, which are first appropriately archived and placed inside a special file with the extension (format) .HEX (for the convenience of storing and transporting machine codes), and then unzipped from the HEX file and take their original form in the program servicing the programmer.

With this program, the machine codes of the program are written into the PIC. The above phrase, used all the time, is certainly not successful.

Pay attention to this and always keep in mind that it does not reflect the meaning of what is happening, although I will use it further, since it is standard. I've only covered two of the main features of the IDE.

Its capabilities are far from exhausted by them.

The integrated development environment for PICs is called MPLAB.

This program (or rather a set of programs) was created by the manufacturer of PIKs, that is, the company

Microchip Technology Inc.

In Russia, the representative of this company is Micro-Chip LLC, which has its own technical support site on the Internet in Russian http://www.microchip.ru (by the way, on this site, in the “Beginners” section, there is a link to my site).

Personally, I use version MPLAB 5.70.40, which I advise you to do as well.

This is “a good old horse that won’t ruin the furrow” and his capabilities are “above the roof.”

The main disadvantage of this version is that it works slowly (it counts), but for beginners, “reactive” speed is not necessary.

Its main advantage is reliability.

IN later versions, to one degree or another, trade speed for reliability, which is sometimes not good.

In the future, I will focus on version 5.70.40.

Note: MPLAB version 5.70.40 (and 2 more versions) is available on CD. You need to download the MPLAB distribution into a folder with an English name (the My Documents or Desktop folder will not work), otherwise you will have problems.

It is best to organize it in the Program Files folder on drive C.

The MPLAB program is an integrated development environment for PICs and contains everything necessary for writing and editing the program, and for creating HEX files, as well as for debugging the program.

Thus, the need for a separate text editor for writing a program, a separate assembler program for creating a HEX file and a separate program debugger (simulator) is eliminated, since MPLAB has all this (and even more).

Install MPLAB on your computer, make sure that it is not “crooked” and forget about it for a while, since in order to work with it, you need to thoroughly prepare, which is what we will do in the future.

Next step - programmer assembly, since the HEX program file created in MPLAB must be “converted” into machine codes, which will be written to the PIC (the so-called “firmware”).

At the first stage, I cannot offer anything simpler and more reliable than the PonyProg programmer, although, of course, there are other “worthy” programmers.

You will find information on assembling the PonyProg programmer in "Appendix No. 1".

It should be noted that the PonyProg programmer works best on relatively “slow” computers of older releases, since, at one time, the PonyProg program was created for them.

When connecting the programmer to modern high-speed computers with “sophisticated” operating systems, conflicts may arise such as “inconsistency” of the PonyProg program with the operating system or exceeding the maximum permissible data exchange rate between the computer and the programmable PIC, that is, the programmer may simply not work.

This is not a fact at all, but it could be.

The best solution is to use a computer with a clock frequency of up to 500 MHz and the Windows95/98 operating system for these purposes.

Personally, I did this: I bought an “ancient old lady” practically for nothing, deceived the BIOS by attaching an additional 8GB hard drive to the native hard drive as an “assistant,” installed Windows98 and turned on the afterburner.

It turned out “cheap and cheerful”, and primarily for the reason that when doing programming, creating printed circuit boards, drawing circuits and other amateur radio activities, special speed is not required, since all these activities are leisurely, and there is no special sense in using them for this task high-speed computers do not.

My “old lady” has almost 2GB of this kind of programs, including some pretty “sophisticated” ones, and nothing works great.

With what must be available, I hope it’s clear, and now about the useful “little things”. Download these two small but useful and convenient programs:

HEX - calculator: file CALC32.rar is attached (folder "Programs"). Number system converter: BCONV32 file is attached (folder "Programs").

They are so simple that you can easily figure out why they are needed. Most often, a number system converter is required.

One of the active participants in the work, Peter Vysochansky, has developed a number system converter program that is most adapted to practical needs:

Converter of calculation systems by Peter Wysochansky: file Hex-Dec_Bin.exe attached

(Applications folder)

When opened, the converter program installs the English keyboard layout (what you need).

So, everything you need to start programming PIC controllers is available. For now, these are nothing more than beautiful and intriguing “things” with a purpose that is not entirely clear.

You can look at them at your leisure, click on something, just, in order to avoid further misunderstandings, do not touch the default settings.

Continue to the next section.

"Tutorial on programming PIC controllers for beginners" http://ikarab.narod.ru E-mail: [email protected]

2. What is a microcontroller and how does it work

First of all, a microcontroller is a processor with all its “attributes”, plus built-in, non-volatile memory (programs and data), which allows you to abandon external program memory and place the program in its non-volatile memory.

This allows you to create very simple (in terms of circuitry) and compact devices that nevertheless perform quite complex functions.

Sometimes you even wonder: this little “thing” replaces a whole “pillar of old iron” (K555, etc.).

Any microcontroller, in terms of its capabilities, is, of course, inferior to a computer processor, but nevertheless, there is a very broad class of devices that are mainly implemented on microcontrollers.

AND In fact, you can’t put a computer in your pocket and you can’t power it with batteries. Therefore, in many cases, there is simply no alternative to microcontrollers. The “heart” of the microcontroller is the arithmetic logic unit (ALU).

The easiest way to imagine it is in the form of a banal calculator, the buttons of which are controlled by a program written in assembly language (that is, by a programmer).

If you think about it, there is nothing particularly complicated in the control mechanism of this kind of calculator.

AND in fact, if you need, for example, to add numbers A and B, then in the program text the constants A and B are first specified, and then the “add” command is given.

It is not at all necessary for a programmer to know what happens with zeros and ones (unless only for general development), after all, a calculator is a calculator in order to save the user from “fussing” with machine codes and other “inconveniences”. When you work with a computer, you do not need to know in detail what is happening in the wilds of the operating system.

If you “climb” there, you will “go crazy”, and a microcontroller, in its essence, is the same computer, but only simple.

The programmer only needs to know in detail exactly how to “order the piece of hardware” to do what is necessary to achieve the plan.

A microcontroller can be imagined as a kind of universal “set” of multifunctional modules (blocks), the “control levers” of which are in the hands of the programmer.

There are quite a large number of these “levers,” and naturally, you need to master them and know exactly what will happen if you “pull” (give a command in assembly language) one or another “lever.”

This is where you need to know, like “Our Father,” every detail and not waste time on this “recognition.”

Only in this way can an empty “blank” (an unprogrammed PIC) be “forced” to perform some “meaningful” actions, the result of most of which can be checked in the MPLAB simulator (more on this later), without even writing the program into the PIC. So, a transition to “modular” thinking is necessary.

Any microcontroller can be likened to a children's construction set, which includes many different objects, by manipulating which one can obtain one or another final “product”.

Let's sort them out and "put everything into order."

As an example, I will use one of the most common PIC controllers

PIC16F84A.

It is, as it were, the “protomother” of more complex PICs, contains a minimum “set” of modules and is perfectly suited for the initial “entry into m/controllers”.

Non-volatile memory.

Let's start with non-volatile memory (program memory and data memory). Information stored in non-volatile memory is retained when the power is turned off, and therefore it is in it that the program is written.

That “place” of non-volatile memory where the program is written is called program memory.

The amount of program memory may vary. For PIC16F84A, it is 1024 words. This means that it is designed to work with programs whose size does not exceed

So, you've decided to learn how to program pic controllers. First, let's talk about what you need to work with these controllers.

The controller works according to a certain program, which must somehow get into it. Typically, a program in machine code, ready to be written to the controller, is called firmware. Therefore, you need some kind of device that will write (in slang they usually say upload or flash) the program into the controller. This device is called a programmer. We will talk more about programmers and uploading programs later, in the last part of our epic (when there is already something to upload), but for now, let’s take it in order - how to write this program.

The program for the controller is, as I already said, a set of machine codes written in a file with the extension “hex” (), which must be uploaded to the controller using a programmer. The controller does not understand any other language. Therefore, a special program is needed that will translate program text written in any programming language into machine codes. The most convenient in this regard are integrated development environments (IDEs), since they can not only translate program text into machine code, but also simulate its operation. Moreover, the simulation can be carried out step by step, and you can observe the state of the registers or even change their state at will. In short, integrated environments, in addition to compilation itself (translation into machine codes), provide excellent opportunities for debugging a program.

There are many IDEs, as well as programmers. Personally, I use MPLAB and recommend it to you, for the simple reason that MPLAB is an IDE from the manufacturer of PIC controllers, Microchip, and therefore has excellent support (including in Russian, which is especially nice). From the official Microchip website you can download this package itself and a detailed description of how to work with it. If you haven’t found it or it’s difficult to search, it’s true that this is no longer the latest version.

The description in Russian explains everything: from installation and configuration to removal. In most cases, the entire installation consists of running setup and answering a couple of questions, such as where to install drivers and the like, I’ll just add that in order to avoid glitches, you need to install the package in a folder so that only English letters are in the path ( and not to something like C:\Programs\PIC\MPLAB). In general, it is better not to use the Cyrillic alphabet in paths to files or in file names, otherwise glitches are possible.

MPLAB allows you to write programs in two languages: SI and Assembly. The Internet is simply bursting with squabbles between SI guys and assemblers, who are foaming at the mouth to prove to each other which language is better. I consider myself an assembler, so naturally I’ll tell you why Assembler is better.

The assembler is a set of elementary commands executed by the controller. Each command is interpreted into machine code completely unambiguously, and the result of its execution and execution time are always the same. That is, if you have a listing in assembly language, then you can say exactly what the controller is doing at each moment in time and how exactly the desired result is achieved.

A program in the SI language (and indeed in any high-level language) is already a set of commands not from the controller, but from the corresponding language. During compilation, each such command is replaced by a set of commands for the controller, but with what exact set of commands it is replaced - you no longer know this, only the developer of the programming language knows this. Accordingly, it is impossible to understand exactly how the controller performs the desired action.

In short, in the case of a high-level language, you study how some guy called his ways of implementing the functions you need and by what rules they should be written. In this case, we can draw the following analogy: you want to talk to a Chinese person, but they tell you: “Chinese is too difficult a language, but there is one uncle in Bulgaria who lived in China for 20 years and learned it perfectly. And the Bulgarian language and Russian are very similar and Russian people understand it intuitively, so learn Bulgarian, and your uncle will translate."

In the case of assembler, you learn the controller itself and the rules by which you need to talk to the controller. At the same time, the controller has only a few dozen commands that fit on one sheet of paper and can be easily glanced at at a glance.

Hopefully by now you've already made your choice of programming language, so let's move on.

What needs to be done in MPLAB to get the desired firmware? As I already said, read the details in the MPLAB IDE manual, it’s in Russian and everything is clear there (if it’s not clear, go to the forum), I’ll just briefly list the most basic things and give some recommendations.

So, we have installed MPLAB, we want to write a program for the controller in it and get ready-made firmware.

First you need to create a project. For each project, I recommend creating a separate folder, because, firstly, the project may contain several files, and, secondly, MPLAB itself will create several more auxiliary files (*.lst, *.err, *.cod, *. bkx). If several projects are in one folder, then you can easily get confused which files belong to which project. In short, we create a new folder for the project, then launch MPLAB and select the menu Project -> New Project…

In the window that appears, in the explorer on the right, select our folder, on the left side (in the field under the inscription File Name) write the name of the future project, for example my1.pjt (don’t forget to specify the extension), and click OK.

A window appears with the title Edit Project. This is a project manager, which specifies the project parameters (which files and libraries need to be connected to the project, what stone will be used, whether simulation will be used, and much more). Find the input field with the name Development Mode. To the right of this field there is a button Change... Click.

A window with the name opens Development Mode, in which we see a bunch of tabs. On the tab Tools put a tick next to MPLAB SIM Simulator(it’s a sin not to use the simulator for debugging), in the input field Processor select the controller with which we will work. On the tab Clock We indicate what frequency the generator will have. Click OK. We don’t pay attention to the error and warning, they just tell us that they can’t create .hex yet (well, that’s right, we don’t even have a program yet) and that if the settings change, we need to recompile the project again (we’ve never compiled it before) .

In the input field Language Tool Suite choose Microchip.

Click the button with the name Add Node… In the window that appears, in the explorer on the right, select the project folder, in the input field on the left write the name of the file with the text of the assembler program, for example my1.asm (don’t forget to specify the extension), and click OK. That's it, now we have connected the my1.asm file to the project (indicated that the program text will be in this file).

This is where we finish with the Edit project - click OK.

Now you need to actually create a file with the program text (in the project manager we simply indicated that the text will be in such and such a file, but in fact this file has not yet been created). To do this, go to the menu File and select the item New. An editor window named Untitled1 will open. Selecting a menu File -> Save As…, in the explorer on the right we indicate the project folder, in the input field File Name we write the file name that we specified in the project manager, that is, in our example it will be my1.asm. If everything is done correctly, the title of the editor window will change from Untitled1 to \path\my1.asm.

That's all! Now all that remains is to type the program text in the editor window and compile the project (menu Project->Build All) and, if there are no errors in the program (which is very rare the first time), then ready-made firmware (a file with a hex extension) will appear in the project folder, which can be uploaded to the controller.

  1. Part 1. Necessary tools and programs. MPLAB Basics

In 2006, I had a desire to master assembler for PIC microcontrollers. The decision to master PIC was not formed by chance. There are only 35 assembler commands to start with. You can memorize them in a few days by applying them in practice, when writing your own program. Or simply learn it using the datasheet on any of the PIC controllers. Fortunately, some of the documentation is available in Russian.

Well, the first design is, of course, a clock. And it’s not difficult (at least at the beginning it seemed so to me) it’s easy to find a use for a clock or timer both at home and at work. The only obstacle that I had to face was the lack of clear and consistently presented information on directly programming methods.

There are many sites on the Internet with microcontroller topics, but often this information is laid out in the form of a sort of vinaigrette, which is very difficult to understand with zero experience in programming chips.
After launching the “first project on a microcontroller” circuit - blinking the LED - a frantic search for useful information began. And quite by accident, while scouring the network in search of information on the next scheme from the magazine "Radio" (Denisov's frequency meter), I came across Evgeniy Korabelnikov's website.

I can’t say that my search ended there. I came up with some approaches myself, and my own code, as a rule, is always better than the one invented by someone else.
But I have not yet found a more consistent and methodical presentation of questions on the structure of microcontrollers, options for protocols for exchanging PIC information with external devices (indicators, sensors), working with memory chips and much more.

Evgeniy is an Author with a capital A, he managed to organize and translate a huge amount of material into a normally readable text, making it understandable and accessible, even for those who have never encountered programming before.

If you need a quick start and assembly language programming for PIC controllers, then I recommend Evgeniy Aleksandrovich’s website.

Assembly language programming for

PIC microcontrollers

Tutorial on programming PIC controllers for beginners

(microcontroller device design guide)

General notes on the entry strategy.

“The self-instruction manual...” is compiled in such a way that, in cases where there are any ambiguities that arise after reading the previous sections, in subsequent sections they are gradually clarified through additional information. At the initial stage of “entry”, the main thing is to understand the meaning, and everything else will be added to it, over time.

Introduction
1. Prepare the tools. Making a programmer and working with it.
2. What is a microcontroller and how does it work.
3. PIC16F84A command system.
4. What is a program and the rules for its preparation. An example of creating a program for a self-oscillating multivibrator. Directives. Schematic diagram of a multivibrator
5. Integrated design environment MPLAB IDE and work in it.
6. What's next?
7. An example of creating a program (beginning).
8. Example of creating a program (continued).
9. Work in the simulator. Debugging the program.
10. How to track program execution
11. Interrupts. Stack. An example of program development with interruptions.
12. Organization of a calculated transition. Working with EEPROM data memory.
13. Flags. Working with flags. How does a digital comparator work? Transfer and loan.
14. An example of using the C flag in a three-byte adder. Cyclic shift. Multiplication operation.
15. Introduction to the principle of constructing a dynamic display subroutine. Indirect addressing.
16. Converting binary numbers to BCD. Final formation of the text of the dynamic display subroutine.
17. Counting principle. Working with timer TMR0. The principle of installing groups of counting commands in the program text.
Conclusion

November 15, 2009 at 2:56 pm

Programming PIC16/PIC18 microcontrollers in C. Article two. Basic information about the platform. First program

  • Microcontroller programming

If everything worked out well in the first article, we received a basic software environment for continuing training.

As I said earlier, for now I will explain on the basis of MK PIC16F628A.
Be sure to download the documentation for it. I recommend for searching - alldatasheet.com
DataSheet is the main document for development based on MK.
I recommend printing out the main tables and sections for ease of use.

We open the DS.

The most important information about the crystal:
- maximum operating frequency - 20 MHz;
- 2048x14 bit flash ROM;
- 224 bytes of static RAM;
- 128 bytes of non-volatile ROM;
- 16 available pins;
- transceiver module;
- 3 timers.

This crystal is a representative of the so-called mid-range PIC family.

I’ll briefly tell you what you need to understand.

Data memory devices is divided into 4 jar.
Banks contain special purpose registers (SFR) and general purpose registers (GPR).
SFR - used to control the device and its modules.
General purpose registers are presented in the form of static RAM, where we can store our variables.
Special registers occupy 32 initial positions in each bank.
The DS on pages 18-21 shows all the special purpose registers. Print them out - they will come in handy more than once.

This is quite a voluminous topic, and there is no way to skip it.
On the other hand, it’s boring and uninteresting.
Try to overcome yourself and read about memory organization and special-purpose registers in DS and Shpak (mentioned in the first article).

I/O ports.

U of this device two ports: PORTA and PORTB.
Each port pin can be used directly as a simple pin or as a pin for other MK modules.
At the very beginning of the DS, you should have noticed that each pin, in addition to the main name, for example RB1, also contains another name RX and DT.
This is where RX is a secondary output function - as an input to a transceiver.
But for now we will not touch the peripheral modules of the device.

Each port pin can function as an input or output.
For example, if we need to light an LED, we configure the pin to which it is connected as an output and set the appropriate level on it.
But if we need to connect a button to a port and read the fact of pressing, then here we need to configure this pin as an input.
I/O configuration is done using registers TRIS.
If you write 1 to the corresponding bit of the TRIS register, then this pin will become an input, if 0 - an output (apparently due to the similarity of 1 and Input, and 0 and Output)
Eg:

TRISA = 0; // All port A pins are outputs
TRISB = 0xff; // All port B pins are inputs
TRISA5 = 1; // Pin 5 of port A is input. By the way, not all compilers allow you to access each output directly

Register names can be viewed in the “HT-PICC\include folder” folder for the corresponding controller.

To set a certain level at the output, we use the PORT register.
Eg:

PORTA = 0; // All port A pins are low
PORTB = 0xff; // All port B pins are high
RB5 = 1; // The fifth pin of port B is high

So. We reach a point when it is necessary to make a digression on the C language itself.
I'll probably write a small example here. Let's compile. We’ll run it in Proteus, and I’ll write about the basic C language in the next article.

Let's write a small program. Let's flash the LED.
We use a previously created project, or create a new one, according to the scheme from the first article.

First, let's connect the header file.


We don't choose specific model, and indicate pic.h. If you open it, you will see a script for selecting a specific file based on the selected device when creating the project.
void main(void)
{
while(1);
}

We write at the beginning:
TRISA = 0; // Port A - all pins are outputs
PORTA = 0; // with logical zero
TRISB = 0; // Port B - all pins are outputs
PORTB = 0; // With logical zero

Let's go to the "HT-PICC\samples\delay folder".
Let's copy delay.c and delay.h from there and paste them into the project folder.

Let's add a line at the beginning:
#include "delay.c"
We will use the DelayMs(x) function to create a pause between LED toggles.

Let's say the LED is connected to RB0.
To switch it, a logical exclusive “OR” will be used:


As a result, the code looks like:
#include #include "delay.c"

Void main(void)
{
TRISA = 0;
PORTA = 0;
TRISB = 0;
PORTB = 0;

While(1)
{
DelayMs(250); // Let's pause for half a second
DelayMs(250);
RB0 ^= 1; // invert the output
}
}

The firmware is ready.
Now let's set the configuration bits.
Click Configure -> Configuration bits.
Uncheck the box "Configuration Bits set in code", since we didn’t set anything in the code.

We see several points.
We display it as on the screenshot.
Oscillator- HS - a high-frequency quartz resonator will be used as a clock generator.
WatchDog Timer- Off, if enabled, the microcontroller will be reset periodically to avoid any freezes. We have such an opportunity Bye need not.
Power Up Timer- Enabled, the MK will be in a reset state until the supply voltage reaches the required threshold level.
Brown Out Detect- On, MK reset if the supply voltage drops below a certain level.
Low Voltage Program- Disabled, we prohibit the use of low-voltage in-circuit programming of the MK. This depends on your programmer.
Data EE Read Protect- Off, allow reading data and EEPROM memory of the MK.
Code Protect- Off, disable code protection in MK. If you set it to On, it will be impossible to read the program from the MK. Us Bye this option is not needed.

Press F10 again.
Let's close.

Let's run the program in Proteus.
Launch Proteus ISIS.
While in the section Component mode click Pick from libraries and, using the search, add components to the form:
- PIC16F628A;
- LED-RED;
- RES;

Double-click on each of them and set the parameters.
For MK - select the *.hex firmware file from our project folder, and set the frequency to 4 MHz.
For LED-RED, select Model type - Digital.
For the resistor, select a resistance of 300 Ohms.
Add to the form Ground In chapter Terminals mode and connect as in the screenshot.

Click Play - the LED should blink.

In the next article I will take a closer look at the C language.
This will be followed by an article on controller peripherals and code examples for it.
And after that I plan to talk about USB and PIC 18.
This is the plan for now :-)

Internet