Program codes c. What is program code, application, errors

In order for the program to perform the actions prescribed to it, for example, calculate, display the result, respond to user actions, for example, pressing buttons, selecting lines from a list, it is necessary program code.

Program code is a set of words and symbols of a programming language.

Alphabet - This complete set letters, numbers and symbols adopted in the language to designate data and actions on them.

The Visual Basic language alphabet includes the following character set:

Uppercase (A - Z) and lowercase (a - z) letters of the Latin alphabet;

Numbers from 0 to 9;

Signs arithmetic operations(in ascending order of priority): +, -, *, /, |, ^;

Signs of relational operations: =,<, >.

Punctuation marks and separators: ,  . : ; ();

The alphabet of the language also includes reserved words that cannot be used as names variables or procedures. Examples of reserved words: Dim, Sub, Integer, etc. By default, blue font is used to highlight keywords in the Visual Basic code editing window.

Words and symbols must be written strictly according to the rules of the language, without spelling and punctuation errors. It is the exact spelling that will allow the computer to unambiguously understand and execute the program.

Code Window

The program code is written in the code window. Each form has such a window.

Open code window:

1 way - in the window Project Explorer right-click on the desired form and select from the menu that opens Show code.

Note: The code window may not be associated with the form. Separate window code is called Module. Modules in the Project Explorer window are grouped into a group Modules. To open a window with the module code, you need to in the window Project Explorer double click on the module name.

Method 2 - double-click on the control element on the form or on the form itself in the form window.

Note: this not only opens the code window, but also creates an event handling procedure (see below).

Code window structure:

Rice. 7. Program code window.

    List of controls

    List of control events

    Procedure (code)

Procedures

Since when the refrigerator is opened, the lamp lights up, and when the tap is opened, water flows out, we can say that when the event of opening the refrigerator occurs, one procedure is performed, and the event of opening the tap causes another procedure. Similarly, the program code consists of separate procedures, each of which performs its own specific actions, for example, one procedure lights a lamp, another turns on (pumps) water.

Visual Basic - procedural programming language. This means that you can create blocks of code in it, which can then be referenced by name. Once a block of code has a name, it can be called and completed. It's like a program within a program. Small programs "living" in large programs, are called functions if they return some value, and subroutines, if they do not return values.

Subroutines and functions make programming easier and faster, and the code you create more reliable. Creating your own routines and functions is the first step to development encapsulated and reusable code. Encapsulation means hiding the implementation of an object's properties and methods behind its external interface.

Procedure (subroutine) is a separate fragment of program code with the help of which a small task is usually solved; it is a logically constructed, small program block into which the entire program is divided.

If a procedure can only be executed within a given program block (for example, only in this form), and cannot be called from another program block, then such a procedure is local. A local procedure is specified using the Private Sub keyword.

If a procedure can be called from other program blocks (for example, from another form), then such a procedure is global. A global procedure is specified using the Public Sub keyword.

By default, if before the Sub keyword, there is no keyword, then this is a global procedure.

The procedures are:

    Event Procedures. Executed when an event occurs on a control (or form). An event procedure is always associated with some object. To call an object's event procedure, simply double-left click on the object.

    Arbitrary procedures. It is not associated with events and can be called from any other procedure and executed at any time. If the same program block occurs in all forms in a program, then it can be written only once and in one place, in the form of a global general program. The launch of a general program is not associated with an object and with an event, but occurs when it is accessed from other program blocks. Calling a general procedure from the same form: ProcedureName (ParameterList). Calling a generic procedure from another form: OBJECT. ProcedureName (ParameterList). The general procedure can be both local Private and global Public

Procedure structure

The procedure consists of the following elements:

    Procedure header - marks the beginning of the procedure, its type, purpose (event).

An example of a procedure title that is executed when a button named Command1 is clicked.

    Word Private means closed, that is, the procedure belongs only to this form or module and cannot be used by other containers (forms, modules). If this word is omitted, the procedure will be open to other containers.

    Sub- procedure.

Note: In addition to procedures, there are functions. Functions are not associated with events and can additionally return the result of their work (calculations).

    Control element(or form name): This specifies the exact name of the element stored in the property Name.

    Event- name of the event. Here are some events:

    Click - mouse click;

    DblClick - double click;

    KeyPress - key press;

    UnLoad - unloading the form (when closing the form, ending the program);

    Activate - activation of the form (when you click on the form and its title is highlighted);

    Deactivate - deactivate the form (when clicking on another form).

    Initialize - when creating an object of type form.

    Resize - when changing the form size

    Terminate - at the moment of deleting the form

    Arguments- this is the initial data passed to the procedure for processing.

Custom procedures have the following header:

Procedure name there must be unique, must begin with a letter and must not contain spaces or characters other than underscores. The procedure is called by name when it needs to be executed.

    End of the procedure - ends the program code of the procedure: End Sub

Note: for functions: End Function

    Procedure body - these are the lines between the title and the ending. Their number is unlimited. The lines contain instructions that must be executed when the procedure is called (the event occurs).

Subroutine (Sub) - is a procedure that executes program code within its block and does not return a value. The syntax of a simple subroutine is:

( Private | Public ) Sub SubMain ()

..lines of code End Sub

Scope of the subroutine;

Sub - procedure type (namely, subroutine);

subMain the name given to the subroutine;

End Sub - end of the subroutine code block.

Creating a procedure

To create a procedure, do the following:

    1 way - double click on the required element control or form. The code window will open, and the title and end of the procedure will appear in it. If another event is needed, it is selected using the list in the upper right corner of the code window.

    Method 2 - open the code window, go to Tools → Add Procedure → specify the name and parameters of the procedure → Ok.

    3 way - open the code window and enter the required lines from the keyboard.

The result should be:

Private Sub Command1_Click()

Calling procedures for execution

    For an event procedure to execute, the event must occur.

    To execute an arbitrary procedure, specify the name of this procedure in the body of another procedure.

Private Sub Command1_Click()

Here, when you click on the Command1 button, the Click event occurs and the Kvadrat procedure is called and executed.

The procedure code is executed line by line and from top to bottom.

Function (Function) - it is a procedure that executes lines of its code and returns some value. The syntax of a simple function is:

Function FunctionName() As Datatype

... linescode

FunctionName = ReturnValueEnd Function

Function scope;

Function is a Visual Basic keyword indicating that it is a function;

FunctionName () - the name given to the function;

AS is a Visual Basic keyword that precedes the assignment of a data type;

DataType return value data type;

ReturnValue the value that should be assigned to the function name (this is a very important point!);

End Function - the end of this block of code.

The source code is either used to produce object code or executed by an interpreter. Changes are never made to object code, only to source code, and then converted back to object code.

Another important purpose of source code is as a description of a program. Based on the text of the program, you can reconstruct the logic of its behavior. Comments are used to make source code easier to understand. There are also tools, allowing you to automatically receive documentation on the source code - the so-called. documentation generators.

In addition, the source code has many other uses. It can be used as a teaching tool; Beginning programmers may find it useful to examine existing source code to learn programming techniques and methodology. It is also used as a communication tool between experienced programmers, due to its (ideally) concise and unambiguous nature. Sharing Code management is often cited by developers as a contributing factor to improving the programmer experience.

Programmers often move source code from one project to another, which is called code reuse ( Software reusability).

Source code is a critical component for the process of porting software to other platforms. Without the source code of any piece of software, porting is either too difficult or not possible at all.

Organization

The source code of some part of the software (module, component) may consist of one or more files. Program code is not necessarily written in only one programming language. For example, often programs written in C language, for optimization purposes, contain inserts of code in assembly language. It is also possible that some components or parts of a program are written in different languages, and then assembled into a single executable module using a technology known as library linking ( library linking).

Complex software when assembled, it requires the use of dozens or even hundreds of source code files. In such cases, to simplify the build, project files are usually used that contain a description of the dependencies between the source code files and describe the build process. These files may also contain other compiler and design environment parameters. Can be used for different design environments different files project, and in some environments these files may be in text format, suitable for direct editing by a programmer using universal text editors; in other environments, special formats are supported, and files are created and modified using special tool programs. Project files are usually included in the term "source code". The vast majority of modern language environments require the use of project files, regardless of the complexity of the other source code included in the this project. Often, source code also means resource files containing various data, for example, graphic images, needed to build the program.

To facilitate work with source code, for collaboration on code by a team of programmers, version control systems are used.

Quality

Unlike humans, there is no “well-written” or “badly written” code for a computer. But how the code is written can greatly influence the software maintenance process. The quality of the source code can be discussed in the context of the following parameters:

  • code readability (including the presence or absence of code comments - blocks of arbitrary text omitted by the compiler program);
  • ease of support, testing, debugging and error correction, modification and porting;
  • low complexity;
  • low resource usage - memory, processor, disk space;
  • absence of comments output by the compiler;
  • absence of “garbage” - so-called “dead variables” (that is, variables that are not used), operators that are never executed, comments from previous versions of this code, which have lost their meaning, etc.

Non-executable source code

Copyleft licenses for free software require distribution of the source code. These licenses are also often used for works that are not software - for example, documentation, images, data files for computer games.

In such cases, the source code is considered to be the form of the work that is preferred for editing. In licenses other than software, it may also be referred to as the "transparent format" version. This could be, for example:

  • for a file compressed with loss of data - lossless version;
  • for a raster image - vector version;
  • for a two-dimensional image of a three-dimensional model - three-dimensional model
  • for a text image - the same text in text format;

and finally, the file itself, if it satisfies the specified conditions, or if more convenient version it simply didn't exist.

Purpose

The source code is either used to produce object code or executed by an interpreter. Changes are never made to object code, only to source code, and then converted back to object code.

Another important purpose of source code is as a description of a program. Based on the text of the program, you can reconstruct the logic of its behavior. Comments are used to make source code easier to understand. There are also tools that allow you to automatically obtain source code documentation - the so-called. documentation generators.

In addition, the source code has many other uses. It can be used as a teaching tool; Beginning programmers may find it useful to examine existing source code to learn programming techniques and methodology. It is also used as a communication tool between experienced programmers due to its concise and unambiguous nature. Code sharing among developers is often cited as a contributing factor to improving the programmer experience.

Programmers often move source code (in modules, as is, or with adaptations) from one project to another, which is called code reuse.

Source code is a critical component for the process of porting software to other platforms. Without the source code of any piece of software, porting is either too difficult or not possible at all.

Organization

The source code of some part of the software (module, component) may consist of one or more files. Program code is not necessarily written in only one programming language. For example, often programs written in C language, for optimization purposes, contain inserts of code in assembly language. It is also possible that some components or parts of a program are written in different languages, and then assembled into a single executable module using a technique known as library linking ( library linking).

Complex software requires dozens or even hundreds of source code files to be built. In such cases, to simplify the build, project files are usually used that contain a description of the dependencies between the source code files and describe the build process. These files may also contain options for the compiler and design environment. For different design environments, different project files can be used, and in some environments these files can be in a text format, suitable for direct editing by a programmer using universal text editors; in other environments, special formats are supported, and the creation and modification of files is carried out using special tools programs. Project files are usually included in the term "source code". The vast majority of modern language environments require the use of project files, regardless of the complexity of the other source code included in the project. Often, source code also means resource files containing various data, for example, graphic images needed to build a program.

To facilitate work with source code, for collaboration on code by a team of programmers, version control systems are used.

Quality

Unlike humans, there is no “well-written” or “badly written” code for a computer. But how the code is written can greatly influence the software maintenance process. The quality of the source code can be judged by the following parameters:

  • code readability (including the presence of comments to the code);
  • ease of support, testing, debugging and error correction, modification and porting;
  • economical use of resources - memory, processor, disk space;
  • absence of comments output by the compiler;
  • absence of “garbage” - unused variables, unreachable code blocks, unnecessary outdated comments, etc.;
  • adequate error handling;
  • portability - the ability to use a handler (compiler, interpreter, translator) different versions, or even different OS;
  • possibility of interface internationalization.

Non-executable source code

Copyleft licenses for free software require distribution of the source code. These licenses are also often used for works that are not software - for example, documentation, images, data files for computer games.

In such cases, the source code is considered to be the form of the work that is preferred for editing. In licenses other than software, it may also be referred to as the "transparent format" version. This could be, for example:

  • for a file compressed with loss of data - lossless version;
  • for rendering a vector image or a three-dimensional model - respectively, the vector version and the model;
  • for a text image - the same text in text format;
  • for music - a file in the internal format of the music editor;
  • and finally, the file itself, if it satisfies the specified conditions, or if a more convenient version simply did not exist.

See also


Wikimedia Foundation. 2010.

See what “Source code” is in other dictionaries:

    Source materials of the film: negative, counterprint, control copy of the film, original magnetic phonograms of music dubbing, noise, video phonogram master, CD, etc. Synonyms: the text is either directly executed by the interpreter, or... ... Financial Dictionary

    A human-written text of a computer program in any programming language. Dictionary of business terms. Akademik.ru. 2001 ... Dictionary of business terms

    source code- - Telecommunications topics, basic concepts EN source code ... Technical Translator's Guide

    source code- 3.1.13 source code: A computer program expressed in a human-readable form (programming language) that is translated into machine-readable form (object code) before it can be tested with... ... Dictionary-reference book of terms of normative and technical documentation

    source code- source text language... Explanatory translation dictionary

    Source code: Source code is the human-written text of a computer program. Source code techno-thriller directed by Duncan Jones ... Wikipedia

    This term has other meanings, see source code. Source code Source Code ... Wikipedia

    This article lacks links to sources of information. Information must be verifiable, otherwise it may be questioned and deleted. You can... Wikipedia

    Open Source Initiative (OSI) logo Open source software is open source software. The source code of the created programs is open, that is, available for viewing and modification. This is... ... Wikipedia

    Source program (source code)- 48) source program (source code) a corresponding representation of one or more processes that can be converted by a programming system into a form executable by hardware (object code or object language) (categories 6, 7 and 9); ... Official terminology

Today, many companies, as well as individuals, feel the need to have their own website, which is why information on the topic of developing and promoting Internet projects is so in demand. Many people are interested in the question - how to create your own website, program code for which it is like a foundation for a house? Let's try to understand this issue by delving into the topic of web development.

A website is not just a collection of text, links, pictures and colorful banners, it is also a program code that runs on the user’s computer or on the server side. And if today almost anyone can create images of the required format in the required resolution and quality, using ready-made images from the Internet or any popular graphic editor, then create site code for a non-specialist it is fraught with considerable difficulties.

The quality of applications and the Internet project as a whole strongly depends on the skill of the programmer developing the site, the program code of which may contain errors that greatly affect the loading speed of web pages and many other aspects of the operation of the entire site, including those related to security. Therefore, detecting and eliminating errors in the code is a mandatory component when creating any website. It is best to entrust the development of a complex corporate website to specialists (if you are not one), because some errors are difficult to detect, and many of them can further lead to slow loading and incorrect display of web pages in the browsers of Internet users’ computers. Too much long loading can cause an outflow of visitors from the site and a decrease in the quality of traffic, which reduces the profit and efficiency of using commercial Internet projects.

HTML and CSS first

The basis of a web document is code written in HTML markup language. A markup language should not be confused with a programming language, and what the actual difference is is written in detail. In principle, using the set of commands that HTML offers for the site developer, you can set all the necessary parameters of a static web document - the arrangement of elements (block markup), headings, paragraphs, tables, images, etc. And with the help of CSS, a special add-on for HTML, you can position all the listed markup objects, change their style - color, size, format, etc.

Then JavaScript

Interactive and animated elements, for example - banners, ticker, form feedback, on web pages work due to the presence of scripts and code written in server-side or client-side programming languages. Scripts developed using the language are very popular JavaScript programming. Such client scripts do not use the server's capabilities in their work and are executed on the user's computer side, that is, in the browser. This makes JavaScript applications simple and fast.

And finally PHP

When it is necessary to write complex and voluminous codes, for example for forums or guest books, programmers turn to server-side programming languages ​​for help, and in particular to . PHP codes are performed on the server side, so their work may be somewhat slower, since it depends on the connection speed with remote computer and the degree of its workload. WITH using PHP and SQL commands ( special language queries to a relational database) you can organize the interaction of the site with databases and create interactive Internet projects - forums, online stores, message boards, various directories, etc.

The basis of the site is the program code was last modified: March 3rd, 2016 by Admin

(Developer's Guide for HCS08 Family Microcontrollers)

In Example 12.1, we'll look at code that allows you to write and erase native data in flash memory. Such actions are necessary if the user of a device makes additional settings for this device and wants the selected configuration to be preserved after the power is turned off.

Previously, we noted that the HCS08 family of MCUs do not allow erasing and programming flash memory operations, executing the program for controlling these modes also from flash memory. Be sure to first rewrite the program code responsible for erasing and programming operations into RAM, and then run this code for execution. During the erasing and programming process, the flash memory module will be increased voltage. However, this will not lead to disruption of the program, since at a given moment in time it will be executed from RAM.

NXP has developed a set of assembly language utilities that make it easy to create custom code to program flash memory under the control of the device operating program. These utilities are located in the file doonstack.asm. This file should be included in the project, as shown in Fig. 12.3.

Rice. 12.3. Project window with included file doonstack.asm.

File Contents doonstack.asm presented below. The original text of the program code used is given, so the comments cannot be translated.


;* This stationery is meant to serve as the framework for a *
;* user application. For a more comprehensive program that *
;* demonstrates the more advanced functionality of this *
;* processor, please see the demonstration applications *
;* located in the examples subdirectory of the *
;* Metrowerks Codewarrior for the HC08 Program directory *
;**************************************************************
; export symbols
XDEF DoOnStack
XDEF FlashErase
XDEF FlashProg
; we use export "Entry" as symbol. This allows us to
; reference "Entry" either in the linker .prm file
; or from C/C++ later on

; include derivative specific macros
Include "MC9S08GB60.inc"

The next two lines should be uncommented and assigned the desired values.

;mPageErase equ $40
;mByteProg equ $20
mFACCERR equ $10
mFPVIOL equ $20
mFCBEF equ $80
; variable/data section
MY_ZEROPAGE: SECTION SHORT
; Insert here your data definition. For demonstration, temp_byte is used.
; temp_byte ds.b 1
; code section
MyCode: SECTION
;**************************************************************
; this assembly routine is called the C/C++ application
DoOnStack: pshx
pshh ;save pointer to flash
psha ;save command on stack
ldhx #SpSubEnd ;point at last byte to move to stack;
SpMoveLoop: lda ,x ;read from flash
psha ;move onto stack
aix #-1 ;next byte to move
cphx #SpSub-1 ;past end?
bne SpMoveLoop ;loop till whole sub on stack
tsx ;point to sub on stack
tpa ;move CCR to A for testing
and #$08 ;check the I mask
bne I_set ;skip if I already set
sei ;block interrupts while FLASH busy
lda SpSubSize+6,sp ;preload data for command
cli ;ok to clear I mask now
bra I_cont ;continue to stack de-allocation
I_set: lda SpSubSize+6,sp ;preload data for command
jsr ,x ;execute the sub on the stack
I_cont: ais #SpSubSize+3 ;deallocate sub body + H:X + command
;H:X flash pointer OK from SpSub
lsla ;A=00 & Z=1 unless PVIOL or ACCERR
rts ;to flash where DoOnStack was called
;**************************************************************
SpSub: ldhx LOW(SpSubSize+4),sp ;get flash address from stack
sta 0,x ;write to flash; latch addr and data
lda SpSubSize+3,sp ;get flash command
sta FCMD ;write the flash command
lda #mFCBEF ;mask to initiate command
sta FSTAT ; register command
nop ;[p] want min 4~ from w cycle to r
ChkDone: lda FSTAT ; so FCCF is valid
lsla ;FCCF now in MSB
bpl ChkDone ;loop if FCCF = 0
SpSubEnd: rts ;back into DoOnStack in flash
SpSubSize: equ (*-SpSub)
;**************************************************************
FlashErase: psha ;adjust sp for DoOnStack entry

lda #mPageErase ;mask pattern for page erase command
bsr DoOnStack ;finish command from stack-based sub
rts
;**************************************************************
FlashProg: psha ;temporarily save entry data
lda #(mFPVIOL+mFACCERR) ;mask
sta FSTAT ;abort any command and clear errors
lda #mByteProg ;mask pattern for byte prog command
bsr DoOnStack ;execute prog code from stack RAM
ais #1 ;deallocate data location from stack
rts
;**************************************************************

Also in the text of the program code in C it is necessary to have a directive #include connect file doonstack.h, the text of which is presented below.


/* */
/* Project Name: doonstack.h */
/* Last modified: 04/11/2004 */
/* By: r60817 */
/* */
/* */
/**********************************************************************/
/* */
/* Description: MC9S08GB60_FLASH_DOONSTACK - demo */
/* */
/* */
/* Documentation: MC9S08GB60/D Rev. 2.2 */
/* HCS08RMv1/D Rev. 1(4.8FLASH Application Examples) */
/* */
/* This software is classified as Engineering Sample Software. */
/* */
/**********************************************************************/
/* */
/* Services performed by FREESCALE in this matter are performed AS IS */
/* and without any warranty. CUSTOMER retains the final decision */
/* relative to the total design and functionality of the end product. */
/* FREESCALE neither guarantees nor will be held liable by CUSTOMER */
/* for the success of this project. FREESCALE DISCLAIMS ALL */
/* WARRANTIES, EXPRESSED, IMPLIED OR STATUTORY INCLUDING, BUT NOT */
/* LIMITED TO, IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR PURPOSE ON ANY HARDWARE, SOFTWARE ORE ADVISE SUPPLIED */
/* TO THE PROJECT BY FREESCALE, AND OR NAY PRODUCT RESULTING FROM */
/* FREESCALE SERVICES . IN NO EVENT SHALL FREESCALE BE LIABLE FOR */
/* INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT. */
/* */
/* CUSTOMER agrees to hold FREESCALE harmless against any and all */
/* claims demands or actions by anyone on account of any damage, or */
/* injury, whether commercial, contractual, or tortuous, rising */
/* directly or indirectly as a result of the advise or assistance */
/* supplied CUSTOMER in connection with product, services or goods */
/* supplied under this Agreement. */
/* */
/**********************************************************************/
/*
- this file API between main.c and doonstack.asm
*/
#ifndef _doonstack
#define_doonstack
#ifdef __cplusplus
extern "C" ( /* our assembly functions have C calling convention */
#endif
void DoOnStack(void); /* prototype for DoOnStack routine */
void FlashErase( unsigned char*); /* prototype for FlashErase routine */
/* Page Erase command */
void FlashProg(unsigned char *, unsigned char); /* prototype for FlashProg routine */
/* Byte Program command */
#ifdef __cplusplus
}
#endif

#endif /* _doonstack */
/**********************************************************************/

In our example, a block of 512 bytes is reserved for recording non-volatile data. This block size was chosen because it is the minimum amount of flash memory cells allowed for erasing in the MC9S08QG8 microcontroller. The selected block will be located at the beginning of the address space of the MK's resident flash memory: from 0xE000 to 0xE1FF. The program code will start at address 0xE200 and can occupy address space up to 0xFFFF.

In order to implement the intended placement of data and program codes, you should change the linker settings in the file project.prm.

In the standard project there was an entry:


ROM = READ_ONLY 0xE000 TO 0xFFAD;

It should be replaced:

SEGMENTS /* Here all RAM/ROM areas of the device are listed */
ROM = READ_ONLY 0xE200 TO 0xFFAD;

In our example, the write protection mode of the program code area is also used, i.e. address space from 0xF200 to 0xFFFF. In Fig. 12.4 shows the process of generating code for the FPROT register, which protects the address space 0xF200...0xFFFF from accidental erasure/write. The most significant seven bits of the last address 0xF1FF of the unprotected address space must be written to the FPROT register.

Address A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1 A0
0xE1FF 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1
FPROT FPS7 FPS6 FPS5 FPS4 FPS3 FPS2 FPS1 FPDIS
0xE0 1 1 1 0 0 0 0 0

Rice. 12.4. Generating a security code entry for the FPROT register.

Example 12.1. Operations with non-volatile data in flash memory

// Demo board DEMO9S08QG8
// erase/write/read resident flash memory
#include /* for EnableInterrupts macro */
#include "derivative.h" /* include peripheral declarations */
#include "hcs08.h" /* This is our declaration file! */
#include "doonstack.h"
#define BUSCLK 8000000
#define vFCDIV (BUSCLK/200000-1)
char fdata, operation;
unsigned int faddress;
// Assign a write-protected address area: 0xE200 to 0xFFFF
const byte NVPROT_INIT @0x0000FFBD = 0xE0;
// Initialization of MK
void mcu_init(void)
{
SOPT1 = bBKGDPE; // Enable BKGD debug line function
ICSSC = NV_FTRIM; // Write the FTRIM trim value
ICSTRM = NV_ICSTRM; // Write the TRIM trim value
ICSC2 = 0; // ICSOUT = DCOOUT / 1
// BUSCLK = 8 MHz
FCDIV = vFCDIV; // Write the value of the divider code for the frequency FCLK
// (FCLK = 200 kHz)
}
#pragma inline
// Function for reading a byte from a memory cell with a given address
char flash_read(unsigned int address)
{
unsigned char *pointer;
pointer = (char*) address;
return (*pointer);
}
// Function for writing a byte to a memory cell with a given address
char flash_write(unsigned int address, unsigned char data)
{
unsigned char *pointer;
pointer = (char*) address;
FlashProg(pointer,data); // Call the flash programming function
if (FSTAT_FACCERR) data=1; else data=0;
if (FSTAT_FPVIOL) data|=2;
return(data);
}
// Function for erasing a specified block in the flash memory area
unsigned char flash_sector_erase(unsigned int address)
{
unsigned char *pointer, res;
pointer = (char*) address;
FlashErase(pointer);
if (FSTAT_FACCERR) res=1; else res=0;
if (FSTAT_FPVIOL) res|=2;
return(res);
}
void main(void)
{
mcu_init();
fdata = 0;
faddress = 0xE000;
operation = 0;
while (1)
{
switch (operation)
{
case 1: // Erase block
fdata = flash_sector_erase(faddress);
operation = 0;
break;
case 2: // Write a byte
fdata = flash_write(faddress,fdata);
operation = 0;
break;
case 3: // Read byte
fdata = flash_read(faddress);
operation = 0;
break;
}
}
}

Let's consider the methodology for testing the program code of Example 12.1. To do this, in the debugger window Data let's add three variables: faddress, fdata, operation. We will also set the window to periodic update mode, for example, every 200 ms.

Before running the program code, write it to a variable faddress address for writing, and into a variable fdata— byte of data to be written. Next to the variable operation write down the code 0x02. After running the example code, it will begin writing a byte of data to the selected flash memory cell. Please note that the selected cell must be in an erased state, i.e. it should contain the code 0xFF.

To erase memory block 0xE00...0xE1FF, write to faddress any address from the specified range and set the variable operation in 1. Next, run the code again for execution.

Reading data from flash memory is also easy. To do this, write to the variable faddress address code, into a variable operation- code 0x03. The contents of the selected flash memory cell will be displayed in the variable fdata after the program code is executed.

Please note that the functions flash_write() And flash_sector_erase() return a variable of type chare with an error code when performing the action: 0 - there was no error, 0x02 - there was an access error, 0x04 - there was an attempt to erase/write the protected address space. Both functions mentioned above require about 35 bytes of stack memory to execute. If the actual stack area is smaller, then fatal error. It will be possible to restore the functionality of the program only by resetting the MK.

In order to view flash memory changes in the debugger, you need to make some changes to the debugger configuration. Following the default settings, the debugger reads the MCU flash memory area only once after starting a debugging session. To change the configuration, select the option in the main debugger menu MultilinkCyclonPro > Debug Memory Map. The window shown in Fig. will open. 12.5, a. Select in this window memory block 3 and press the button Modify/Details. In the new window shown in Fig. 12.5, b, select the marked option. This will allow the debugger to periodically update the memory window.

Rice. 12.5. Change the debugger configuration to periodically update the contents of the memory window.