This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
en:programming:c:crashcourse [2012/05/31 11:45] – eero.valjaots | en:programming:c:crashcourse [2020/07/20 09:00] (current) – external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Crash course ====== | + | ====== |
- | <note important> | + | |
===== Program structure ===== | ===== Program structure ===== | ||
Line 39: | Line 39: | ||
<code c> | <code c> | ||
- | // Üherealine kommentaar. | + | // Line comment is on one line. |
- | // Kommentaariks loetakse kahe kaldkriipsu järel olevat teksti | + | // Text after two slash signs is considered as comment. |
/* | /* | ||
- | Mitmerealine kommentaar | + | Block comment can be used to include more than one line. |
- | Kommentaari algus ja lõpp määratakse kaldkriipsude ja tärnidega | + | The beginning and the end of a comment is assigned with slash and asterisk signs. |
*/ | */ | ||
</ | </ | ||
- | ~~PB~~ | ||
- | ===== Andmed | + | ===== Data ===== |
- | ==== Andmetüübid | + | ==== Data types ==== |
- | C-keele baasandmetüübid: | + | C-language basic data types: |
- | ^ Tüüp | + | ^ Type ^ Minimum |
| (signed) char | -128 | 127 | 8 | 1 | | | (signed) char | -128 | 127 | 8 | 1 | | ||
| unsigned char | 0 | 255 | 8 | 1 | | | unsigned char | 0 | 255 | 8 | 1 | | ||
Line 66: | Line 65: | ||
| double | | double | ||
- | Sulgudes olevat sõna " | + | The word " |
- | AVR mikrokontrolleril | + | AVR microcontroller has //int// = //short// \\ |
- | PC arvutil | + | PC has //int// = //long// \\ |
- | C-keeles puudub spetsiaalne teksti-andmetüüp. Selle asemel kasutatakse | + | There is no special string data type in C-language. Instead |
- | ==== Muutujad | + | ==== Variables |
- | Programmis saab kasutada kindlat andmetüüpi mälupesasid | + | Program can use defined type of memory slots - variables. Variable names can include latin aplhabet characters, numbers and underdashes. Beginning with a number is not allowed. When declarations to variables are being made, data type is written in front of it. Value is given to variable by using equal sign (=). Example about using variables: |
<code c> | <code c> | ||
- | // char tüüpi muutuja | + | // char type variable |
char c; | char c; | ||
- | // Muutujale | + | // Value is given to variable |
c = 65; | c = 65; | ||
- | c = ' | + | c = ' |
- | // int tüüpi muutuja | + | // int type variable |
int i20 = 55; | int i20 = 55; | ||
- | // Mitme unsigned short tüüpi muutuja deklareerimine | + | // Declaration of several |
unsigned short x, y, test_variable; | unsigned short x, y, test_variable; | ||
</ | </ | ||
- | ==== Konstandid | + | ==== Constants |
- | Konstante deklareeritakse samamoodi nagu muutujaid, kuid ette lisatakse | + | Constants are declarated in the same way as variables, exept // |
<code c> | <code c> | ||
- | // int tüüpi konstandi määramine | + | // int type constant declaration |
const int x_factor = 100; | const int x_factor = 100; | ||
</ | </ | ||
- | ==== Struktuurid | + | ==== Structures |
- | Baasandmetüüpidest saab // | + | Basic data types can be arranged into structures by using // |
<code c> | <code c> | ||
- | // Uue punkti andmetüübi deklareerimine | + | // Declaration of a new data type " |
typedef struct | typedef struct | ||
{ | { | ||
- | // x ja y koordinaat ning värvikood | + | // x and y coordinates and color code |
int x, y; | int x, y; | ||
char color; | char color; | ||
Line 115: | Line 114: | ||
point; | point; | ||
- | // Punkti muutuja deklareerimine | + | // declaration of a variable as data type of point |
point p; | point p; | ||
- | // Punkti koordinaatide määramine | + | // Assigning values for point variable |
p.x = 3; | p.x = 3; | ||
p.y = 14; | p.y = 14; | ||
</ | </ | ||
- | ==== Massiivid | + | ==== Arrays |
- | Andmetüüpidest võib koostada massiive (jadasid). Massiiv võib olla ka mitmemõõtmeline | + | Data types can be arranged into arrays. Array can have more than one dimensions |
<code c> | <code c> | ||
- | // Ühe- ja kahemõõtmelise massiivi deklareerimine | + | // Declaration of one- and two-dimensional arrays |
char text[3]; | char text[3]; | ||
int table[10][10]; | int table[10][10]; | ||
- | // Teksti moodustamine tähemassiivist | + | // Creating a string from char array |
- | text[0] = ' | + | text[0] = ' |
- | text[1] = ' | + | text[1] = ' |
- | text[2] = 0; // Teksti lõpetamise tunnus | + | text[2] = 0; // Text terminator |
- | // Tabeli ühe elemendi muutmine | + | // Assigning new value for one element. |
table[4][3] = 1; | table[4][3] = 1; | ||
</ | </ | ||
- | ~~PB~~ | + | < |
- | ===== Avaldised | + | ===== Operations |
- | Muutujate, konstantide ja väärtust tagastavate funktsioonidega saab koostada avaldisi (tehteid). Avaldise väärtusi saab omistada muutujatele, neid saab kasutada funktsiooni parameetritena ja erinevates tingimuslausetes. | + | Variables, constants and value returning functions can be used for composing operations. The result of and operation can be assigned to a variable, it can be used as a function parameter and in different control structures. |
- | ==== Aritmeetilised | + | ==== Arithmetic operators |
- | C-keeles toetatud aritmeetilised tehted on liitmine | + | C-language supported artithmetic operations are addition |
<code c> | <code c> | ||
int x, y; | int x, y; | ||
- | // Mooduli võtmine, korrutamine ja väärtuse omistamine | + | // Modulo, multiplication and assigning value |
- | // x saab väärtuse | + | // x gets value of 9 |
x = (13 % 5) * 3; | x = (13 % 5) * 3; | ||
- | // Liitev-omistav operaator | + | // Adding-assigning operator |
- | // x väärtuseks saab 14 | + | // x gets value of 14 |
x += 5; | x += 5; | ||
- | // Ühe lahutamise kiirmeetod | + | // Quick style method for subtracting 1 |
- | // x väärtuseks saab 13 | + | // x gets value of 13 |
x--; | x--; | ||
</ | </ | ||
- | ==== Loogilised | + | ==== Logical operators |
- | Loogilised tehted on eitus (!), loogiline korrutamine | + | Logical operators are negation NOT (!), logic multiplication AND (&& |
<code c> | <code c> | ||
bool a, b, c; | bool a, b, c; | ||
- | // Algväärtustamine | + | // Initialization |
a = true; | a = true; | ||
b = false; | b = false; | ||
- | // Eitus | + | // Negation |
- | // c väärtus tuleb väär sest tõest eitati | + | // c will get a value of false because a is true |
c = !a; | c = !a; | ||
- | // Loogiline korrutamine | + | // Logic multiplication |
- | // c väärtuseks tuleb väär, sest üks operandidest on väär | + | // c will get a value of false because one of the operators is false |
c = a && b; | c = a && b; | ||
- | // Loogiline liitmine | + | // Logic addition |
- | // c väärtus tuleb tõene, sest üks operandidest on tõene | + | // c will get a value of true because one of the operators is true |
c = a || b; | c = a || b; | ||
</ | </ | ||
- | **NB!** // | + | **NB!** // |
- | ==== Võrdlused ==== | ||
- | Arvude väärtuste võrdlemisel saadakse loogilised väärtused. Võrdlustehted on samaväärsus | + | ==== Relational and equality operators ==== |
+ | |||
+ | Logical values are a result of comparison of variable values. Equality operators are equal to (==), not equal to (!=), greater than (> | ||
<code c> | <code c> | ||
int x = 10, y = 1; | int x = 10, y = 1; | ||
- | // Suurem-kui võrdlustehe, | + | // greater than operation which is true |
- | // Tehte ümber on sulud vaid selguse pärast | + | // brackets around the operation are only for clarity |
bool b = (5 > 4); | bool b = (5 > 4); | ||
- | // Erinevuse tehe | + | // Not equal to operation |
- | // Tehte tulemus on väär | + | // The result is false |
b = (4 != 4); | b = (4 != 4); | ||
- | // Aritmeetiline, võrdlus ja loogiline tehe üheskoos | + | // Arithmetic, equality and logic operations alltogether |
- | // b tuleb väär, sest esimene loogilise korrutise operand on väär | + | // b is false because the first operator of logic multiplication is false |
b = (x + 4 > 15) && (y < 4); | b = (x + 4 > 15) && (y < 4); | ||
</ | </ | ||
- | ==== Bititehted | + | ==== Bit operations |
- | Bititehted on andmetega binaarses arvusüsteemis tegelemiseks. Neid saab rakendada kõigi täisarv-tüüpi andmetega. Bititehted sarnanevad loogiliste tehetega, kuid erinevad selle poolest, et tehe teostatakse iga bitiga eraldi, mitte kogu arvuga. C keeles on bititeheteks inversioon | + | Bit operations are for data manipulation in binary numeral system. These can be applied only to integer type data. Bit operations are quite similar to logic operations but differ from them because operation is carried out with every single bit not the whole number. Bit operations in C-language are inversion |
<code c> | <code c> | ||
- | // Märgita | + | // Declaration of unsigned |
- | // Muutuja väärtus on kümnendsüsteemis | + | // Variable value is 5 in decimal system, 101 in binary system |
unsigned char c = 5; | unsigned char c = 5; | ||
- | // Muutuja | + | // Disjunction of c with a digit 2 (010 in binary) |
- | // c väätuseks saab 7 (kahendsüsteemis | + | // c value will become |
c = c | 2; | c = c | 2; | ||
- | // Bitinihe vasakule | + | // Bit left shift by 2 |
- | // c väärtuseks saab 28 (kahendsüsteemis | + | // c value will become |
c = c << 2; | c = c << 2; | ||
</ | </ | ||
- | Bititehted on hädavajalikud mikrokontrollerite registrite kasutamisel. Täpsemalt tutvustab neid AVR registrite peatükk. | + | Bit operations are essential when using the registers of microcontroller. These are described in AVR register chapter. |
- | ~~PB~~ | + | < |
- | ===== Funktsioonid | + | ===== Functions |
- | Funktsioon on programmilõik, | + | Functions are part of a program that can be called by its name. Function can include parameters as input and can return one output. If the function is not returning a parameter, it has type // |
<code c> | <code c> | ||
- | // Kahe int tüüpi parameetriga funktsiooni deklareerimine | + | // Declaration of 2 int type parameter function |
- | // Funktsioon tagastab | + | // The function returns |
int sum(int a, int b) | int sum(int a, int b) | ||
{ | { | ||
- | // Kahe arvu liitmine ja summa tagastamine | + | // Addition of 2 variables and returning of their sum |
return a + b; | return a + b; | ||
} | } | ||
- | // Ilma parameetrite ja tagastatava väärtuseta funktsioon | + | // Function without parameters and no return output |
void power_off(void) | void power_off(void) | ||
{ | { | ||
Line 254: | Line 254: | ||
</ | </ | ||
- | Funktsiooni kasutamiseks tuleb see välja kutsuda. Funktsioon peab programmikoodis olema deklareeritud enne välja kutsumise kohta. Näide liitmisfunktsiooni väljakutsumisest. | + | To use a function, it must be called. It is required that a function is declared before call. Example about calling addition function: |
<code c> | <code c> | ||
Line 260: | Line 260: | ||
int y = 3; | int y = 3; | ||
- | // Liitmisfunktsiooni väljakutsumine | + | // Calling an addition function |
// Parameetriteks on muutuja ja konstandi väärtus | // Parameetriteks on muutuja ja konstandi väärtus | ||
+ | // The parameters are variable and constant | ||
x = sum(y, 5); | x = sum(y, 5); | ||
- | // Väljalülitamise funktsiooni väljakutsumine | + | // The call of a power off function |
- | // Parameetrid puuduvad | + | // No parameters |
power_off(); | power_off(); | ||
</ | </ | ||
- | C-keele programmi täitmist alustatakse | + | The execution of a C-language program is started from // |
- | ~~PB~~ | + | < |
- | ===== Laused | + | ===== Statements |
- | ==== Tingimuslause | + | ==== If/Else statement |
- | Tingimuslause võimaldab vastavalt sulgudes oleva avaldise tõesusele täita või mitte täita tingimusele järgnevat lauset või programmilõiku. Tingimuslause võtmesõna | + | Conditional statements enable to execute or skip program code based on based on logic and relational operations. Conditional statement uses a keyword |
<code c> | <code c> | ||
- | // Avaldis on tõene ja lause x = 5 täidetakse, | + | // Statement is true and operation |
- | // sest 2 + 1 on suurem kui 2 | + | // because |
if ((2 + 1) > 2) x = 5; | if ((2 + 1) > 2) x = 5; | ||
- | // Kui x on 5 ja y on 3, siis täidetakse järgnev programmilõik | + | // If x equals |
if ((x == 5) && (y == 3)) | if ((x == 5) && (y == 3)) | ||
{ | { | ||
- | // Suvaline tegevus | + | // Random action |
y = 4; | y = 4; | ||
my_function(); | my_function(); | ||
Line 293: | Line 294: | ||
</ | </ | ||
- | Tingimuslause võib olla pikem ja sisaldada ka lauset või programmilõiku, | + | //If// statement can be longer and include code which will be executed in case the statement is false. For this, after // |
<code c> | <code c> | ||
- | // Kas x on 5 ? | + | // Is x equal with 5 ? |
if (x == 5) | if (x == 5) | ||
{ | { | ||
- | // Suvaline tegevus | + | // Random action |
z = 3; | z = 3; | ||
} | } | ||
- | // Kui x ei olnud 5, kas siis x on 6 ? | + | // If this is false then x might be equal with 6 |
else if (x == 6) | else if (x == 6) | ||
{ | { | ||
- | // Suvaline tegevus | + | // Random action |
q = 3; | q = 3; | ||
} | } | ||
- | // Kui x ei olnud 5 ega 6... | + | // If x was not 5 nor 6 ... |
else | else | ||
{ | { | ||
- | // Suvaline tegevus | + | // Random action |
y = 0; | y = 0; | ||
} | } | ||
</ | </ | ||
- | ~~PB~~ | + | < |
- | ==== Valikulause | + | ==== Switch statement |
- | Kui on vaja võrrelda avaldist mitme erineva väärtusega, on mõistlik kasutada valikulauset | + | When required to compare operations and variables with many different values, it is reasonable to use comparison statement with // |
<code c> | <code c> | ||
int y; | int y; | ||
- | // Tingimuslause | + | // Switch statement for comparing |
switch (y) | switch (y) | ||
{ | { | ||
- | // y on 1 ? | + | // is y equal to 1 ? |
case 1: | case 1: | ||
- | // Suvaline tegevus | + | // Random action |
function1(); | function1(); | ||
break; | break; | ||
- | // y on 2 ? | + | // is y equal to 2 ? |
case 2: | case 2: | ||
- | // Suvaline tegevus | + | // Random action |
function2(); | function2(); | ||
break; | break; | ||
- | // Kõik muud juhtumid | + | // All other cases |
default: | default: | ||
- | // Suvaline tegevus | + | // Random action |
functionX(); | functionX(); | ||
- | // break lauset pole vaja, | + | // break operation not needed, |
- | // kuna võrdlemine lõppeb nagunii | + | // because the comparison ends anyway |
} | } | ||
</ | </ | ||
- | ===== Tsüklid | + | ===== Loops ===== |
- | Tsüklitega saab programmilõiku täita mitmeid kordi. | + | Loops can be used for executing code several times. |
- | ==== while ==== | + | ==== while loop ==== |
- | // | + | Code marked with // |
<code c> | <code c> | ||
int x = 0; | int x = 0; | ||
- | // Tsükkel kestab seni, kuni x on väiksem kui 5 | + | // Loop will execute until x is smaller than 5 |
while (x < 5) | while (x < 5) | ||
{ | { | ||
- | // x suurendamine ühe võrra | + | // x incrementation |
x++; | x++; | ||
} | } | ||
</ | </ | ||
- | ~~PB~~ | + | < |
- | ==== for ==== | + | ==== for loop ==== |
- | // | + | // |
- | Näide: | ||
<code c> | <code c> | ||
int i, x = 0; | int i, x = 0; | ||
- | // Algul määratakse | + | // i is equal to 1 at the beginning of the loop. |
- | // i on vähem kui 5. Iga tsükli lõpus suurendatakse | + | // Loop will be executed until i is smaller than 5. |
+ | // i will be incremented in the end of every loop cycle. | ||
for (i = 0; i < 5; i++) | for (i = 0; i < 5; i++) | ||
{ | { | ||
- | // x suurendamine | + | // x addition by 2 |
x += 2; | x += 2; | ||
} | } | ||
- | // Siinkohal tuleb x väärtuseks | + | // here x value is 10 |
</ | </ | ||
- | ==== Tsüklis liikumine | + | ==== Halting loops ==== |
- | // | + | As and exception exit from // |
<code c> | <code c> | ||
int x = 0, y = 0; | int x = 0, y = 0; | ||
- | // Lõputu tsükkel, kuna 1 on loogiline tõesus | + | // Infinite loop because |
while (1) | while (1) | ||
{ | { | ||
- | // Tsüklist väljutakse, | + | // Exit the the loop cycle if x becomes |
if (x >= 100) break; | if (x >= 100) break; | ||
- | // x suurendamine, | + | // x incrementation to end loop at some time |
x++; | x++; | ||
- | // Kui x on 10 või vähem, siis alustatakse järgmist tsüklit | + | // If x is 10 or less then the next cycle is started |
if (x <= 10) continue; | if (x <= 10) continue; | ||
- | // y suurendamine | + | // y incrementation |
y++; | y++; | ||
} | } | ||
- | // Siinkohal on y väärtus | + | // Here y value is 90 |
</ | </ | ||
- | ==== Tekstitöötlus | + | ==== Text operations |
- | Tekstitöötlusfunktsioone | + | Text operations are needed for microcontrollers foremost for displaying characters and text on LCD. |
==== sprintf ==== | ==== sprintf ==== | ||
- | sprintf | + | //sprintf// function is similar to ordinary //printf// function commonly used in C-language. The difference is that the result of this function is loaded into variable not standard |
- | tagastus | + | return |
- | + | Example: | |
- | Näide: | + | |
<code c> | <code c> | ||
int r = sprintf(buffer, | int r = sprintf(buffer, | ||
</ | </ | ||
- | Väärtustab muutuja vormindatud tekstiga, mis on antud funktsiooni | ||
- | teisest kuni n parameetrini. Sprintf funktsioon lihtsustab keerulisemate | ||
- | fraaside või lausete koostamist. Mugavam on kasutada tekstis muutujaid, mis | ||
- | asendatakse väärtustega. Funktsioon tagastab muutujasse salvestatud teksti pikkuse. Vea korral tagastatakse negatiivne arv. | ||
- | Näide: | + | It will load formated text into variable which is given from the function second to n parameter. //sprintf// will simplify composing more sophisticated statements. Easier is to use variables in text that will be replaced by values. Function returns the length of text loaded into variable. In case of error occurrence, negative value is returned. |
+ | |||
+ | Example: | ||
<code c> | <code c> | ||
- | sprintf(x, " | + | sprintf(x, " |
- | // sama tulemuse saaksime ka nii: | + | // the same result can be achieved also: |
- | x = " | + | x = " |
- | sprintf(x, " | + | sprintf(x, " |
- | // sama tulemuse saaksime ka nii: | + | // the same result can be achieved also: |
- | x = " | + | x = " |
</ | </ | ||
- | %s ja %d on antud juhul parameetrid, | + | %s and %d are in this case parameters that will be repalaced accordingly by variable values which are the last parameters to function. The number of parameters must be the same as variables. |
- | väärtustega, | + | In the first example, the parameter was %d which was replaced by variable value 1. In the second example parameters were %s and %d which were replaced by variable values |
- | parameetreid, peab olema ka muutujaid. | + | |
- | Esimese näite puhul oli meil parameetriks | + | |
- | väärtusega | + | |
- | vastavalt muutuja väärtustega | + | |
- | Just nimelt sellises järjekorras, | + | |
- | %d numbrilist väärtust. Erinevate andmetüüpide jaoks on olemas vastavad | + | |
- | muutujate kirjeldused: | + | |
- | ^ Parameeter | + | ^ Parameter |
- | | %c | Tähemärk | + | | %c | Char | a | |
- | | %i või %d | Täisarv| 123 | | + | | %i or %d | Integer| 123 | |
- | | %f | Murdarv | + | | %f | Real number |
- | | %s | Tekst | näide| | + | | %s | Text | example| |
- | | %X | Heksadetsimaalarv| 3F | | + | | %X | Hexadecimal number| 3F | |
<code c> | <code c> | ||
Line 470: | Line 461: | ||
char buffer [50]; | char buffer [50]; | ||
int n, a=5, b=3; | int n, a=5, b=3; | ||
- | n=sprintf (buffer, " | + | n=sprintf (buffer, " |
- | printf (" | + | printf (" |
return 0; | return 0; | ||
} | } | ||
</ | </ | ||
- | ==== Üldised utiliidid | + | ==== General utilities |
- | Teegi standard | + | Standard functions |
- | ==== random | + | ==== Random function |
- | Juhuarvude genereerimine ei olegi AVR kontrolleril väga lihtne. | + | Generating a random number is not so simple for AVR microcontroller. |
- | Esmalt tuleb juhunumbrigeneraator seemendada arvuga, mille järgi genereeritakse suvaliste numbrite jada. | + | At first the random number generator must be inputed with a number to be the basis of random number array generation. The array based on one number is always the same. To make the result more random, the function can be inputed with a values taken from free floating |
- | Sama numbri järgi genereeritakse alati sama jada. Suvalisema tulemuse saamiseks võib seemendamiseks kasutada näiteks tühjast | + | |
- | Näide: | + | Example: |
<code c> | <code c> | ||
srand(100); | srand(100); | ||
Line 493: | Line 483: | ||
</ | </ | ||
- | Näide, juhuarvu genereerimiseks vahemikus | + | Example about generating a random number in range of 16: |
<code c> | <code c> | ||
#include < | #include < | ||
Line 502: | Line 492: | ||
- | Põhjalikuma inglisekeelse kirjelduse | + | The more in-depth english description about C-language functions is in: |
[[http:// | [[http:// | ||
- | ~~DISCUSSION~~ |