Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
en:examples:timer:software_delay [2010/02/08 12:58] mikk.leinien:examples:timer:software_delay [2020/07/20 09:00] (current) – external edit 127.0.0.1
Line 1: Line 1:
 +<pagebreak>
 ====== Software delay ====== ====== Software delay ======
  
-//Vajalikud teadmised: [HW] [[en:hardware:homelab:controller]], [AVR] [[en:avr:architecture]], [LIB] [[en:software:homelab:library:pin]], [LIB] [[en:software:homelab:library:delay]]//+//Necessary knowledge: [HW] [[en:hardware:homelab:controller]], [AVR] [[en:avr:architecture]], [LIB] [[en:software:homelab:library:pin]], [LIB] [[en:software:homelab:library:delay]]//
  
-===== Teooria =====+===== Theory =====
  
-Tihti on mikrokontrollerite programmis vaja tekitada viiteidet tegevusi ajastada või nende lõppu oodataÜks idee poolest lihtsamaid meetodeid mikrokontrolleri tegevuses paus tekitada on selle protsessor mingi muu tegevusega üle koormata näiteks panna see lugema suuri arveProtsessori taktsagedusest saab välja arvutadamitmeni see arve loendama peaks, et kindlat ajalist viidet tekitadaTeoreetiliselt tekitaks siis mingi arvu loendamine nullist protsessori taktsageduse väärtuseni hertsides viite üks sekundPraktikas see päris nii lihtne ei ole ning põhjuseid on mitmed.+There is often a need to create delays in programs of microcontrollersit is necessary to time the actions or wait them to endBy its concept one of the easiest methods for creating a break in the work of a microcontroller is overloading its processor with some alternative action – for example order it to count big numbers. From the stroke frequency of the processor can be calculated to which number it should count in order to get a certain time delay. Counting a number from zero up to the value of the stroke frequency of the processor in hertz-s, should theoretically create a delay for one secondFor number of reasons this is not as simple in practice. 
 +     
 +If the processor of the microcontroller calculates using numbers which’s binary form is as wide as its inner bus (AVR has 8 bits)then it takes one firing stroke of the processor to perform one arithmetical operation for example adding 1 to any valueIn order to operate with thousands or millions the number has to be 16 or 32 bit and for an 8 bit processor it takes more than one firing stroke to calculate themHence when dealing with large numbers, one has to be familiar with the inside of the processor – exactly its commands  
  
-Kui mikrokontrolleri protsessor arvutab arvudega, mille kahendkuju on sama lai kui selle sisemine siin (AVR puhul 8-bitti), siis protsessoritel võtab üks aritmeetiline tehenäiteks arvu liitmine ühegaaega 1 protsessori töötaktSelleks et arvutada tuhandete või miljonitegapeab arv olema 16- või 32-bitine ja nende arvutamiseks kulub 8-bitistel protsessoritel rohkem kui 1 töötaktNiisiis, suurte arvude puhul peab tundma protsessori sisemust - täpsemalt selle käsustikku.+When programming in advanced languages (C-language for example), the programs are not written directly on the basis of the commandin order to create a software delayone needs to know also its compiler which converts the program to the machine codeFrom this depends how many instructions (and phases therefore) it takes to perform one arithmetical operation. Complexity is added by compilers ability to convert the program into the machine code in several ways – for exampleby making the machine code as memory saving as possible or easily executableSuch compiler’s actions are called optimization. With different modes of optimization the software delay’s machine codes and their duration come out different   
  
-Kuna kõrgtaseme keeles (näiteks C-keeles) programmeerides ei kirjutata programmi otse käsustiku baasil, peab tarkvaralise viite tekitamiseks tundma ka kompilaatorit, mis programmi masinkoodi teisendab. Just sellest sõltub, mitu instruktsiooni (ja sellest tulenevalt mitu takti) kulub aritmeetilisteks arvutusteks. Keerukust lisab veel asjaolu, et kompilaator võib programmi masinkoodi teisendada mitut moodi - näiteks tehes masinkoodi võimalikult mälusäästlikuks või võimalikult kiiresti täidetavaks. Neid kompilaatori tegevusi nimetatakse optimeerimiseks. Erinevate optimeerimise režiimidega tuleb ka tarkvaralise viite masinkood ja selle ajaline kestus erinev. 
  
-===== Teooria praktikas ======+===== Practice ======
  
-Järgnevalt on toodud näide tarkvaralise viite tekitamisest AVR mikrokontrollerigaKirjutatud on C-keele programmilõikmis loendab //for//-tsüklis muutujat //x// nullist sajaniIga tsükli sees toimub ühe mittemidagitegeva tühiinstruktsiooni täitmineSeda on seal vajakuna tsükli sisu tühjaks jättes optimeerib kompilaator  tsükli programmist üldse väljasest see on tema arvates kasutu.+The following is an example of generating software delay with AVR microcontrollerA part of a program in C-language is writtenwhich counts the variable x of for-cycle from 0 to 100Inside each cycle a no-action empty instruction is completedIt is neededbecause if the content of the cycle is emptythe compiler optimizes it out of the program as it considers this to be useless.
  
 <code c> <code c>
 unsigned char x; unsigned char x;
  
-// Tsükkel seni kuni on 100+// Cycle until is 100
 for (x = 0; x < 100; x++) for (x = 0; x < 100; x++)
 { {
- // Tühiinstruktsiooniga nop+ // With empty instruction nop
  asm volatile ("nop");  asm volatile ("nop");
 } }
 </code> </code>
  
-Siinkohal on aga toodud sama C-keele programmilõik pärast kompileerimistVasakpoolsed heksadetsimaalarvu on masinkood ja paremal on assemblerkeeles käsk koos operandi(de)gaMasinkood ja assemblerkeel on üks-üheselt seotud, assembler on lihtsalt masinkoodi inimesele loetaval kujul esitamiseksKompileerimisel on kasutatud programmi pikkuse optimeerimist (kompilaatori parameeter -Os).+This is the same part of a program after compiling. 2 hexadecimal numbers on the left is machine code and on the right is the command with operand(sin assembler languageThe machine code and the assembler language are conformal; the assembler is just for presenting the machine code for humans in a readable formIn compiling, the optimization of the length of the program is used (compiler’s parameter –Os).
  
 <code asm> <code asm>
-80 e0     ldi  r24, 0x00   ; r24 registrisse arvu laadimine +80 e0     ldi  r24, 0x00 ; r24 loading number to the index 
-00 00     nop              Tühioperatsioon +00 00     nop            Empty operation 
-8f 5f     subi r24, 0xFF   r24 registrist 255 lahutamineehk +1 liitmine +8f 5f     subi r24, 0xFF ; subtracting 255 form the r24 indexthat means adding +1 
-84 36     cpi  r24, 0x64   ; r24 registri võrdlemine arvuga 100 +84 36     cpi  r24, 0x64 ; comparing r24 index with number 100 
-e1 f7     brne .-8         Kui võrdlus oli väärsiis siire baiti tagasi+e1 f7     brne .-8       If the comparison was wrongthen transfer 8-baits back
 </code> </code>
  
-Kompileeritud kujul on nähamis tegelikult C-keele tsüklist saab, ja selle järgi saab arvutada, mitu takti ühe tsükli perioodi puhul kulubInfot instruktsioonide toime ja tööaja kohta leiab AVR käsustiku andmelehestAntud näites kulub ühes tsükli perioodis instruktsiooni täitmiseks taktisest kõik instruktsioonid võtavad ühe töötaktiLisaks kulub enne tsüklit 1 takt laadimisinstruktsiooni jaoks ja tsüklist väljudes 1 lisataktOletadeset kontrolleri töötakt on 14,7456 MHz, võib välja arvutada kogu programmilõigu tekitatud ajalise viite:+ 
 +In the compiled form can be seenwhat is actually happening with the cycle of the C-language and it can be used to calculate how many clock sycles is needed to complete a cycle of one periodThe information about the effect of the instructions and operating time can be found from AVR’s instructions datasheetIn the given example, it takes clock cycles to complete instructions in one cycle periodbecause all instructions demand one clock rateIn addition, one clock rate is used before the cycle for loading instruction and afterwards one extra clock rate for exiting the cycleBy assumingthat the working clock rate of the controller is 14,7456 MHz, the whole delay produced by the program can be calculated. 
  
 (1 + 100 ⋅ 4 + 1) / 14745600 = 27,26 μs (1 + 100 ⋅ 4 + 1) / 14745600 = 27,26 μs
  
-Näites tekitatud viide on mikrosekundites ja kasutav muutuja  on 8-bitineseega on ka masinkood üsna lihtneSellekset tekitada pausi millisekunditeson vaja loendada palju suuremaid arve  ja siis läheb ka masinkood pikemaksVõib kasutada ka üksteise sees töötavaid tsükleid, kuid selle meetodi puhul pole kogu viide lineaarses sõltuvuses tsüklite arvust, sest iga tsükli tasemega tekivad pisikesed lisaviited.+The delay produced in the example, is in microseconds and the variable used is 8-bit so the machine code is fairly simple. In order to produce a break in millisecondwe need to count much larger numbers and thus the machine code gets longerCycles working inside each other may also be usedbut with this method the delay is not in linear relation with the number of the cycles because with each level of cycle a small extra delay occurs. 
 +       
 +The goal of this exercise is not creating precise software delay on the level of machine codebecause it is quite an accurate work and we already have the functions necessary to produce delays in the avr-libc and in the library of the HomeLabThose are used also in the following examples.
  
-Käesoleva harjutuse eesmärk ei ole siiski masinkoodi tasandil täpset tarkvaralist viidet tekitadasest see on üsna peen töö ja pealegi on viite tekitamiseks avr-libc ja Kodulabori teegis juba funktsioonid olemasNeed tulevad ka näites kasutusele.+When dealing with the software delay it is important to knowthat regardless its basic simplicity; it is extremely inefficient method from the power consumption point of view.  During all of these clock rates when the microcontroller is counting the useless, energy is consumed. So if using applications operating on batteries, it is not wise to write long software delaysWiser is to use hardware timers, which are working independently and wake the processor from hibernating when it is time to continue the work   
  
-Tarkvaralise viite puhul on aga oluline teada, et hoolimata oma põhimõttelisest lihtsusest on see äärmiselt ebaefektiivne meetod energiatarbe seisukohast. Kõigil neil taktidel, mil mikrokontroller tegeleb kasutu loendamisega, kulub energiat. Patareidega rakenduses ei ole seega soovitatav pikki tarkvaralisi viiteid teha, vaid tuleks kasutada raudvaralisi taimereid, mis töötavad iseseisvalt ning äratavad protsessori uneolekust üles, kui on vaja midagi teha. 
  
-===== Praktika ======+===== Practice ======
  
-Järgnev programmikood käib tarkvaralise viite funktsiooni //sw_delay_ms// kohtamis tekitab parameetriga //count// etteantud viite millisekunditesFunktsioon kasutab omakorda avr-libc teegi poolenisti assemblerkeeles kirjutatud funktsiooni //_delay_ms//Põhjus, miks harjutuses pole kohe //_delay_ms// kasutatud, on selles, et //_delay_ms// puhul võivad pikkade viidetega probleemid tekkida. //sw_delay_ms// funktsioon võimaldab aga probleemideta kuni 65535 ms viidet.+The following code of a program is about software delay function //sw_delay_ms//which makes a given delay in milliseconds using the parameter //count//The function uses avr-libc library’s function //_delay_ms// which is partly written in assembler languageThe reason why the //_delay_ms// is not used in this exercise immediately is that when using the //_delay_ms// problems may occur when the delays are longThe //sw_delay_ms// enables creating 65535 ms long delays without any complications
  
 <code c> <code c>
 // //
-// Tarkvaraline viide millisekundites+// Software delay in milliseconds.
 // //
 void sw_delay_ms(unsigned short count) void sw_delay_ms(unsigned short count)
 { {
- // Viite muutuja nullini loendamine+ // Counting the variable of the delay to 0
  while (count-- > 0)  while (count-- > 0)
  {  {
- // 1ms viide spetsiaalse funktsiooniga+ // 1ms delay with a special function.
  _delay_ms(1);  _delay_ms(1);
  }  }
Line 65: Line 69:
 </code> </code>
  
-Toodud funktsiooni kasutamiseks on järgnev programmmis tekitab lõputus tsüklis kaks viidet: 100 ms ja 900 ms. Lühema viite jooksul LED põleb ja pikema ajal on kustunud - tulemusena LED perioodiliselt vilgatab.+The following program is for using the given functionthis creates two delays in the endless loop: 100 ms and 900 ms. During the shorter delay LED is lit and during the longer it is switched off, the result – the LED is blinking periodically
  
 <code c> <code c>
 // //
-// Kodulabori tarkvaralise viite demonstratsioonprogramm+// The demonstration program of the software delay of the HomeLab
-// Programm vilgutab ~1 sekundi järel hetkeks LED-i.+// The program is blinking a LED for a moment after ~1 second.
 // //
 #include <homelab/pin.h> #include <homelab/pin.h>
Line 76: Line 80:
    
 // //
-// Test LED-i viigu määramine+// Determining the pin of the test LED
 // //
 pin debug_led = PIN(B, 7); pin debug_led = PIN(B, 7);
    
 // //
-// Põhiprogramm+// Main program
 // //
 int main(void) int main(void)
 { {
- // LED-i viigu väljundiks seadmine+ // Setting the pin of the LED as output.
  pin_setup_output(debug_led);  pin_setup_output(debug_led);
    
- // Lõputu tsükkel + // Endless loop
  while (true)  while (true)
  {  {
- // LED-i süütamine+ // Lighting the LED
  pin_clear(debug_led);  pin_clear(debug_led);
    
- // Tarkvaraline paus 100 millisekundit+ // Software delay for 100 ms
  sw_delay_ms(100);  sw_delay_ms(100);
    
- // LED kustutamine+ // Switching off the LED
  pin_set(debug_led);  pin_set(debug_led);
  
- // Tarkvaraline paus 900 millisekundit+ // Software delay for 900 milliseconds.
  sw_delay_ms(900);  sw_delay_ms(900);
  }  }
Line 106: Line 110:
 </code> </code>
  
-Kuigi näib, et LED vilgatab tõesti sekundi järelon aeg tegelikult siiski natuke pikemsest LED-i ja viite funktsioonide väljakutsumine võtavad ka mõned mikrokontrolleri taktid aega.+Although it seems that the LED blinks in every secondthe time is actually a little bit longerbecause the callouts of LED’s and delay functions are taking a couple of clock rates of the microcontroller
en/examples/timer/software_delay.1265633882.txt.gz · Last modified: 2020/07/20 09:00 (external edit)
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0