Software PWM on the microcontroller algorithm. Rich channel software PWM AVR. Newly needed software PWM

Golovna / Main functionality

Digital attachments, for example, a microcontroller can work with two signals equal to that. zero and one, or omitted and omitted. In this rank, you can easily turn yoga to control the state of vanity, for example, turn it off or turn off the light. So you can vikoristovuvat yoga for keruvannya, be it an electrical accessory, vikoristovuyuchi indpovidni drivers (transistor, triac, relay, etc.). Because you want to control the brightness of the light source (or the lamp) or the speed of the engine fast strumu, then digital signals I just can't work it out. This situation is often discussed in digital technology and is called Pulse Width Modulation (PWM).

May all modern microcontrollers have special hardware for matching the PWM signal. At this level, we need to learn the basics of the SHIM technique and it’s better to implement the SHIM for the help of AVR microcontrollers.

Digital add-ons, like a microcontroller can generate more than two levels on output lines, high = 5V and low = 0V. Ale sho, yakscho mi want to take 2.5 chi 3.1 chi whether it’s a voltage in the range of 0-5V? For this purpose of creating a constant voltage of a constant stream at the exit, we will generate a meander, which is high = 5V and low = 0V equal (div. baby 1).

Fig.1

From the little one it can be seen that the signal for a certain hour is overwhelmed on the low and high level. T0 - low rіven, T1 - high rіven. Signal period T = T0+T1. Period of impulses- tse interval between two characteristic points of two susidnіh іpulsіv. Sound the period between two fronts, or two with recessions of vascular impulses and signify the great Latin letter T.

The period of passage of impulses without intermediary overlaps with the frequency of the impulse sequence, and it can be calculated using the formula: T = 1/F

As long as the T1 pulse is exactly equal to half of the period T, such a signal is often called a "meander".

The stability of the impulses is called the period of passage of the impulses to their trivality and is denoted by the letter S: S=T/T1

Kindness is an unfathomable value and cannot be alone in the world, but it can also be expressed in hundreds of women. The term is often used in English texts duty cycle, Tse so ranks the coefficient of completion or the value of the working cycle of the PWM. The filling coefficient D is the value of the scalding sparing.

Filling coefficient chirp appear at the vіdsotkah and be calculated according to the following formula: D=1/S or so D = T1/T * 100%

On the little one (Fig. 1) you can spit, T1 \u003d T0, for half an hour. So the value of the PWM work cycle becomes 50%. Since the frequency of such impulses is high (say, 5000 Hz), we will take half as much as 5V tobto. 2.5V. In such a rank, as a result, the controller's removal from the engine (for the help of additional drivers) is due to 50% of the total speed. Technique ShІM vikoristovuє tsey fact for the creation of whether or not the voltage between two equals (for example, between 0-12V). The whole focus is on the fact that when changing the value of the working cycle between 0-100%, we take away the very same input voltage at the output. Below it is pointed out, apply the PWM signal to a different sparing signal.

If you put an R / C filter on the output, you can take a pure DC equal to the signal, and not a square wave. But it is not necessary for collector engines, but for the control of light-emitting diodes. For which it is possible to apply a PWM signal directly to the driver (for example, a bipolar transistor, MOSFET too).


Under the robotic mode 16-rozr. the timer is learned by the algorithm of the operation and the behavior associated with it to the output of the pulse generator, which is determined by the combination of bits, which sets the timer operation mode (WGMn3-0) and the mode of generating the output signal (COMnx1:0). In order to specify the mode of forming the output signal, add the rahunka algorithm, because Algorithm of the rahunka to lie down in the future will be set to the mode of the robotic timer. In modes with PWM bit COMnx1:0, you can enable/disable inversion on the PWM output that is generated (to select PWM with inversion or PWM without inversion). For modes without PWM bits, COMnx1:0 is assigned, which is necessary to disable in case of faulty output: discard, insert, or invert output (div. also “Output signal shaping block” and “Timer clock diagrams of 16-dimensional timer-stops”).

Normal operation mode

Himself simple mode The robot is in normal mode (WGMn3-0 = 0b0000). AT this mode the lichnik works as a sum (incremental), with which the lichnik is not discounted. The changeover of the lichnik is required for an hour when the transition through the maximum 16-bit. value (0xFFFF) to the lower range (0x0000). In normal operation, the timer reset flag TOVn will be set on the same clock cycle if TCNTn takes a zero value.

In fact, the TOVn reordering flag is the 17th bit of the timer-list for a wink, that the vins are only restored and not thrown off. However, the software power can be changed to increase the timer's distribution, so that the timer can be changed according to the timer's reordering, at which time the TOVn ensign is dropped automatically. For the normal mode of work, there are no special situations, so the entry of a new lichilnik can be vickonano be-such a mit.

In normal mode, it is possible to override the capture block. However, if you follow the trail, so that the maximum interval between the vinifications of the equal pods does not exceed the period of the reordering of the lichnik. If such a mind is not reached, it is necessary to win over the resetting of the lichilnik or the timer.

The break block can be hacked to generate breaks. It is not recommended to turn off OCnx for signal generation in normal operation, because at this point, a significant part of the processor's hour will be traced.

Timer skip mode pіd h zbіgu (STS)

In STS mode (WGM01, WGM00 = 0b10), the OCR0 register is checked for setting the renter's rent. Every time the CTC mode is set and the qualifier value (TCNT0) is set to the value of the OCR0 register, the qualifier is reset to zero (TCNT0=0). In this order, OCR0 sets the top of the rahunka of the lichnik, and, also, the second division of the building. In this mode, a wider range of regulation of the frequency of rectilinear pulses that are generated is ensured. Vіn also makes it easier for the work of the lichnik of the ovnishnіh podіy.

In the timer reset mode when starting (WGMn3-0 = 0b0100 or 0b1100), the timer setting is set by the OCRnA or ICRn registers. In the CTC mode, a chime reset (TCNTn) is required, which means that either value will fall into the OCRnA register (WGMn3-0 = 0b0100) or ICRn (WGMn3-0 = 0b1100). The value of the register OCRnA or ICRn determines the upper boundary of the window, and, also, the other timer setting. In this mode, a wider range of regulation of the frequency of rectilinear pulses that are generated is ensured. Vіn also makes it easier for the work of the lichnik of the ovnishnіh podіy. The hourly diagram of the timer operation in the CTC mode is shown in small 1. The clock (TCNTn) increments its stat, the clock does not increase over the values ​​of OCRnA or ICRn, and then the clock (TCNTn) is discarded.

Figure 1 - Timing diagram for STS mode

If you reach the upper boundary of the chamber, you can generate a change for additional ensigns OCFnA or ICFn, the latter victorious registers for the administration of the upper boundary of the chamber. Even though a resurfacing is allowed, a resurfacing procedure can be performed to update the upper border of the chest. However, the value of the top of the rahunka is close to the value of the lower one between the rahunka, if the lichnik works without a difference or with a small value of the difference, it is necessary to win with special care, i.e. STS mode has no subway buffering. If the value written in OCRnA or ICRn is less than the current value of TCNTn, then the discount of the lichilika for the mental sum is set, if the value reaches the maximum value (0xFFFF), then go to holiday camp 0x0000 and reach the new value of OCRnA or ICRn. In rich situations, such a situation cannot be blamed. As an alternative, you can enter the PWM mode, deregister OCRnA sets the upper interrange (WGMn3-0 = 0b1111), because this type of OCRnA may have undercurrent buffering.

To generate a signal in the CTC mode, the OCnA output can be switched to change the logical level in skin tone, for which it is necessary to set the muting mode (COMnA1, COMnA0 = 0b01). The OCnA value will be present on the displayed port, only for which way the jobs are output directly. The maximum frequency of the signal to be generated is fOC0 = fclk_I/O/2, so OCRnA = 0x0000. For other values ​​of OCRn, the frequency of the signal to be generated can be determined by the formula:

de change N sets the coefficient of the subdivision of the predivisor (1, 8, 32, 64, 128, 256 or 1024).

So just like for the normal operation mode, the TOV0 ensign is set to the same timer cycle, if its value changes from 0xFFFF to 0x0000.

Fast PWM mode (FAST PWM)

Manual Pulse Width Modulation (PWM) mode (WGMn3-0 = 0b0101, 0b0110, 0b0111, 0b1110, 0b1111) assignments for generating PWM pulses in the driven frequency. On the basis of other modes of work, which one wins, the work of the lichnik is single-directed. Rakhunok vykonuєtsya at a straight line from the lower to the upper boundary of the rakhunka.

Even if the output mode is set, if it is not inverted, then when TCNTn and OCRnx are activated, the OCnx signal is restored, and is dropped at the upper boundary. If the job mode is inverted, then the OCnx output is dropped when it is run and is installed on the upper boundary of the window. For the single-direction rahunka, the operating frequency for this dual-width mode is more equal to the PWM mode and phase correction, de-vicorating the double-straight rahunok. Possibility of generation of high-frequency PWM signals to rob this regime is similar to the tasks of stabilization of life, rectification and digital-analog conversion. High frequency, at which it is possible to beat foreign elements physically small expansions (inductances, capacitors), sim lowering the overall varst of the system.

Razdіlnі zdatnіst SHІM can be fixed 8, 9 or 10 digits or set by register ICRn or OCRnA, but not less than 2 digits (ICRn or OCRnA = 0x0003) and not more than 16 digits (ICRn or OCRnA = 0x0FFFF). Razdіlna zdatnіst ShІM at a given value of the upper boundary (VP) is calculated as follows:

Schwidko's mode Schim L_chika іnkromentuzuzu to Zbiga ya zombina z one of the philosovynaya value 0x00ff, 0x01FF Abo 0x03FF (Yakscho WGMN3: 0 = 0B0101, 0B0110 ABO 0B0111, VІDPOVII), meaning in ICRN (0: 0 (Yakscho WGMN3: 0 = 0B1111) , and Potimm Skidovaty Timkat Synchronizatsa Timer. Timchonova D_Agram Schwidko regime Schima is represented by Malyunka 2. On Malunka Indications Schwidko Mode Schim, Kolya for Verdanza Verkhnai ABI Wick Studying Register OcRNA Abo Icrn. Valled TCNTN on Watch Dіagramі The diagram shows both inverted and non-inverted PWM outputs.A short horizontal line shows a point on the TCNTn graph, deviating the OCRnx and TCNTnx values.

Figure 2 - Timing diagram for PWM mode

The timer reset flag (TOVn) is reset as soon as the timer reaches the upper boundary. Additionally, with the same clock pulse at the same time with the flag TOVn, you can install the flags OCnA or ICFn, so for setting the upper boundary, register OCRnA or ICRn is obvious. If only one of the crossings is allowed, then the procedures for processing the crossing can also be done by updating the upper boundary and the crossing thresholds.

If the value of the upper boundary is changed, it is necessary to think carefully so that the new value of the upper boundary is greater or more important in all registers of the threshold. In another case, TCNTn and OCRnx did not winkle in any way. To pay attention, that when the value of the upper limit is fixed, the entry in the OCRnx register is masked up to 0 discharges, which are not vicorated.

The mechanism for modifying the ICRn register is modified in the case of OCRnA in that case, as it is written for setting the upper boundary. Registry ICRn cannot be buffered. This means that if ICRn is written to a small value for the hour of work of the clerk with a small value, or without it, then it is not safe to write a value to the ICRn register, as it appears to be less than the current value of TCNTn. As a result, in such a situation, a zbіg will be missed at the top of the rahunka. In this case, the lichnik will go up to the maximum value (0xFFFF), restart with the value 0x0000, and then winkne zbig. Register OCRnA to replace the slave buffering scheme, so it can be modified at any time.

class="eliadunit">

As soon as the record is signed for the OCRnA address, the value is actually placed in the OCRnA buffer register. As a result of zbіg mizh TCNTn and the top of the rahunka, then the next cycle of timer synchronization will copy the buffer register to the threshold register OCRnA. Updating the register is done in the same way as dropping TCNTn and setting the flag TOVn.

It is recommended to use the ICRn register for setting the upper boundary, as the upper boundary of the rahunka is a constant. In this case, the OCRnA register is set to generate a PWM signal at the OCnA output. However, since the PWM frequency is dynamically changing (due to changing the upper boundary), then in which case it is necessary to change the OCRnA register for setting the upper boundary, because Vіn pіdtrimuє subvіynu buffering.

In PWM mode, the PWM blocks allow you to generate PWM signals on the OCnx switches. If COMnx1:0 =0b10, then PWM is set without output inversion, and if COMnx1:0 = 0b11, then PWM mode is set with output inversion (div. table 59). The actual OCnx value can be monitored on the specified port, as it is set to outbound direct (DDR_OCnx). The PWM signal is generated by the way of setting (setting) the OCnx register when the fault occurs between OCRnx and TCNTn, as well as by the way of dropping (setting) the OCnx register at the same time with the reset of the lichnik (transition from the upper boundary to the lower boundary).

The frequency of the PWM output signal for a given value of the upper limit (VP) is determined by the scale:

de N - change, as you set the value of the coefficient of distribution (1, 8, 32, 64, 128, 256 or 1024).

The entry of the boundary values ​​of the OCRnx register is associated with special fluctuations in the generation of PWM pulses. If OCRnx is set equal to the lower limit (0x0000), then a short pulse of the skin (VP + 1) cycle of the timer synchronization is used as the output. Recording at OCRnx the value of equal to the upper boundary of the beam before the installation of a constant equal to the beam. 1 or 0 on the output (deposit in the form of an additional bit COMnx1:0 of ​​the polarity of the output signal).

As usual, meander generation is required (direct impulses for sparing 2 or 50% refills) high frequency, then it is necessary to override the swidkoy SHIM mode with the setting of the COMnA1 bit: 0 = 0b01, so that the logical level is switched (inverted) on the OCnA output during skin zbіgu. This should be stopped, it's less likely that OCRnA will win for setting the upper boundary (WGMn3-0 = 0b1111). The maximum square wave frequency that is generated for this waveform fOCnA = fclk_I/O/2, i.e. OCRnA =0x0000. What is special similar to switching OCnA in STS mode with a little bit of floating buffering, like in PWM mode.

Pulse-width modulation mode with phase correction (Phase Correct)

Pulse width modulation mode with phase correction (PWM FC) (WGMn3-0 = 0b0001, 0b010, 0b0011, 0b1010 or 0b1011) assignments for generating a PWM signal with phase correction and high bandwidth. PWM mode for setting up a bidirectional robotic timer-lichilnik. The lichnik cyclically winks at the straight line from the lower boundary (0x0000) to the upper boundary, and then back from the upper boundary to the lower boundary. In addition to setting the output mode of the pulse shaping machine, which is not inverted, then the output of OCnx is reset / reset when the value of TCNTn and OCRnx is adjusted for the direct / reverse waveform. As soon as the output mode is set, then, on the other hand, the installation is installed at the direct hour of the day, and the OCnx exit is canceled at the hour of the return. With bidirectional robots maximum frequency The PWM signal is smaller, lower with single-directed robots, however, due to such a feature, such as symmetry in PWM modes with bidirectional robot, qi modes are important for better spinning when the drive control is reversed.

Razdіlna zdatnіst ShІM in this mode can be fixed (8, 9 or 10 discharges) or ask for additional register ICRn or OCRnA. The minimum capacity is more than 2 digits (ICRn or OCRnA = 0x0003), and the maximum is 16 digits (ICRn or OCRnA = 0xFFFF). If the upper boundary is set, then the separation of the building of the SHIM in this mode is determined by the coming rank:

In PWM mode, the lichil is incremented until it reaches one of the fixed values ​​0x00FF, 0x01FF or 0x03FF (valid for WGMn3-0 = 0b0001, 0b0010 or 0b0011), as well as equal ICRn value (00b:01). Farther, at the reach of the upper boundary, the lichnik changes the rahunka directly. The value of TCNTn is overridden by the equal upper interval of one cycle of the timer synchronization. The timing diagram for the PWM FC mode is shown in the small 3. In the small indications, the PWM FC mode with an additional register OCRnA and ICRn for setting the upper edge. The TCNTn mill is presented as a function graph to illustrate the bidirectionality of the rahunka. On a small scale, there are both non-inverting and inverting PWM outputs. Short horizontal lines indicate points on the graph for changing TCNTn, deviating from the values ​​of OCRnx. The OCnx flag is being restored at the time of the launch.

Figure 3 - Timing diagram for the PWM FC mode

The timer reset flag (TOVn) is reset whenever the timer reaches the bottom boundary. As for setting the upper boundary, the register OCRnA or ICRn is set, the flag OCnA or ICFn is usually set with the same clock pulse, to which the OCRnx register is updated from the buffer register (at the top of the frame). Prapori pererivannya can vikoristovuvatisya for the generation pererivannia after reaching the lower or upper boundary by the lichnik.

When changing the value of the upper inter-registration, it is necessary to keep a check, so that it will be greater or more equal to the values ​​​​of all registers. In another case, TCNTn and OCRnx did not winkle in any way. To pay attention, that when victorious fixing the value of the upper inter-rahunka for an hour, the record in the OCRnx register will be discharged, which are not victorious, reset to zero. The third period of the little one is 53 illustrative fluctuations, if the dynamic change of the upper interfluve is brought to the generation of an asymmetric impulse. This particularity is based on the hour of updating the OCRnx register. Shards of the OCRnx renewal appear at the top of the rahunka, then the PWM period begins and ends at the top of the rahunka. Tse may be on the verge, that the trivality of the inverted rahunka is assigned to the forward values ​​of the upper boundary, and of the direct one - to the new values ​​of the upper boundary. As for the significance of the difference, then the trivality of the direct and the return of the rahunka will also be revisited. Vidminnist trevalosity to produce asymmetry of output impulses.

As it costs to change the upper boundary with a working idler, it is recommended to change the mode to switch to the PWM PFC mode (phase and frequency correction). Although the static value of the upper boundary is victorious, there are practically no differences between these modes.

In PWM FC mode, the pairing blocks allow you to generate PWM signals on the OCnx circuits. If you set COMnx1:0 = 0b10, then PWM output will be without inversion, and if COMnx1:0=0b11, then with inversion. In fact, the OCnx value can be monitored on the output port, as in the registry directly data for output to the port direct output jobs (DDR_OCnx). The PWM signal is generated by the way of setting (setting) the OCnx register when the value of OCRnx and TCNTn is changed for the hour of the direct wave, and also by the way of the drop (setting) to the OCnx register when the number of OCRnx and TCNTn is set to the hour of the turn-by-turn. The resulting frequency of the PWM signal in the PWM FC mode with a specified upper limit (VP) can be calculated using the following method:

The writing of the boundary values ​​in the OCRnx register is associated with special fluctuations in the generation of PWM signals in the PWM FK mode. If you set the PWM mode without inversion and OCRnx set the lower limit equal, then the log will be permanently set at the output. 0, and as equal to the upper boundary, then a permanently present beam emerges. 1. For PWM with inversion, the designation of the equals must be replaced by the lengths.

If you set OCnA as the upper boundary (WGMn3:0 = 0b1011) and set COMnA1:0 =0b01, then a square wave will be generated at the output of OCnA.

Pulse-width modulation mode with phase and frequency correction (Phase and Frequency Correct)

Pulse-width modulation mode with phase and frequency correction (PWM PFC) (WGMn3-0 = 0b1000 or 0b1001) assignments for the generation of PWM pulses in a high power distribution with phase and frequency correction. Yak i mode PWM FK mode PWM FChK of foundations on a bidirectional robotic lighter. The numeral cyclically moves up from the lower boundary (0x0000) to the upper boundary, and then back from the upper boundary to the lower boundary. If the tasks are non-inverting PWM mode, the OCnx output will be dropped, which will cause the TCNTn and OCRnx to decrease between TCNTn and OCRnx for an hour of the direct wave, and will be restored, which will result in the decrease of the hour of the return wave. In invert mode, the robot is inverted. The robot is double-straight, in pairs with a single-straight one, it is connected with the generation of more low frequencies. However, the problems of symmetry in the PWM modes with a bidirectional beam, their blockage is more important in drive control tasks.

The main difference between PWM and PFC modes affects the OCRnx register from the OCRnx buffer register at the moment of updating (div. fig. 3 and fig. 4).

Razdіlna zdatnіst SHІM in this mode can be asked for additional register ICRn or OCRnA. The minimum capacity is up to 2 ranks (ICRn or OCRnA = 0x0003), and the maximum capacity is 16 digits (ICRn or OCRnA = 0xFFFF). Razdіlna zdatnіst ShІM in ranks can be charged for such a viraz:

In the PWM FCH mode, the lichnik is incremented up to the largest ICRn value (WGMn3:0 = 0b1000) or in OCRnA (WGMn3:0 = 0b1001). Tse means reaching the top of the rahunka, after which the rahunka changes directly. The value of TCNTn is filled with the equal top of the chart by one clock cycle of the timer synchronization. The timing diagram for the PWM PFC mode is shown on the thumbnail 54. On the thumbnail of the readings, the PWM PFC mode, if the vertex of the chart is set by the register OCRnA or ICRn. The value of TCNTn is shown as a function graph to illustrate the bidirectionality of the display. On the diagram of indications, both non-inverting and inverting PWM appear. Short horizontal lines point to the points of the TCNTn graph, deviating between OCRnx and TCNTn. The OCnx reset flag will be restored after the failure.

Figure 4 - Timing diagram for the PWM mode with phase and frequency correction

The timer reset flag (TOVn) is set by the same cycle, if the register has been updated with values ​​from the buffer register (on the lower line). If the register OCRnA or ICRn is registered for the upper boundary, then after reaching the upper boundary, the ensign OCnA or ICFn is established. Prapori pererivannya can be victorious for generation of pererivannia when the upper or lower boundary is reached by the lichnik.

When changing the upper boundary, it is necessary to step, so that the new value will be greater or more equal to the values ​​in all registers of the threshold. In another case, even if the value of the upper limit is set to less than the value of the register threshold, the difference between TCNTn and OCRnx will never come.

On the little 4 it is shown that in the mode of PWM FC, the output signal that is generated is symmetrical for all periods. Oskіlki register OCRnx novlyuyutsya on the lower mezhі rachunka, then the trevalosity of the direct and svorotnogo rachunkіv zavzhdi equal. As a result, the output pulses have a symmetrical shape, and also, a variable frequency.

It is recommended to use the ICRn register for setting the upper limit, as the value of the upper limit is a constant. In this case, the OCRnA register is set for pulse-width modulation of pulses on the displayed OCnA. However, as it is necessary to dynamically change the SHIM frequency for the change of the upper boundary, then for setting the upper boundary it is recommended to win the OCRnA register for the visibility of the new subwindow buffering.

In the PWM FCH mode, the PFC blocks allow generating PWM pulses on the OCnx output. If COMnx1:0 = 0b10, then a non-inverting PWM output is displayed, and if COMnx1:0=0b11, then it is inverting (div. table 60). The OCnx value will be present on the outbound port only in the opposite direction, as it is set to outbound direct. The PWM signal is generated by the way to set (skid) the OCnx register when zbіgu mіzh OCRnx and TCNTn pіd hour of the direct wave and the drop (installation) to the OCnx register when zbіgu mіzh OCRnx and TCNTn pіd the hour of the return wave. The frequency of the PWM in this mode, when the upper limit (VP) is set, is indicated by the offensive rank:

de N - Coefficient of division of the predeterminer (1, 8, 32, 64, 128, 256 or 1024).

Writing the boundary values ​​of the OCRnx register is associated with special fluctuations in the generation of PWM signals in this mode. If you set the OCRnx equal to the lower limit (0x0000), then in non-inverting mode, the output will always have a low logical level, and when recording the value of the equal upper limit, the output will always have a high logical level. In the invert mode, the lines will be reversed.

If OCRnA is cycled for setting the upper boundary (WGMn3:0 = 0b1001) and COMnA1:0 = 0b01, then a square wave will be generated at the output of OCnA.


The hardware implementation of PWM gives insane advantages over the software, the shards of rozvantazhu the processor, as we will load it with a bulky code, so it takes an hour to service it, and it also gives more opportunities to work with PWM. Dostatno spend іnіtsіalіzatsіyu timer / lіchilnika (bring neobhіdnі value in regіstri vikoristovuvanі timer / lіchilnikom) yak timer / lіchilnik Mauger pratsyuvati Square od CPU cycles, vіdpovіdno CPU cycles Mauger zaymatisya іnshimi zavdannyami, tіlki іnodі zvertayuchis in neobhіdny moment for koriguvannya abo zmіni regime abo otrimannya rezultatіv od timer /person.

Description of entitlements

T1 can generate a respawn when it hits:

  1. rewriting of the rachunk register TCNT1;
  2. if the LCNT1 and OCR1A and OCR1B drug registers are equal (okremo for the skin registry);
  3. for saving the rachunk register in the burying register ICR1.

T2 can generate a respawn when it hits:

  1. rewriting of the rachunk register TCNT2;
  2. with the sameness of the TCNT2 medical registry and the OCR2 registry.

The flags of all the changes are listed in the TIFR registry, and the permission/fences are listed in the TIMSK registry.

Discharge register TIMSK
Registry7 6 5 4 3 2 1 0
TIMSK OCIE2 TOIE2 TICIE1 OCIE1A OCIE1B TOIE1 OCIE0* TOIE0
  • OCIE2- Entitlement to allow a reprieve for the "zbіg" timer/timer T2
  • TOIE2- Entitlement to reset the timer/timer T2
  • TICIE1- Entitlement to allow a reset after the "clogging" of the timer / lighter T1
  • OCIE1A- Entitlement to allow a break for the sub "zbіg A" of the timer/timer T1
  • OCIE1B- Entitlement to restart after the "start B" of the timer/timer T1
  • TOIE1- Ensign permission to reset the timer/timer T1
  • OCIE0*- Entitlement to restart after the "start" of the T0 timer/caller (* - every day in ATmega8)
  • TOIE0- Entitlement to reset the timer/timer T0
  • OCF2- Prapor reprieve for the "zbіg" timer/caller T2
  • TOV2- Flag of resetting the timer/timer T2
  • ICF1- Flag of the resurrection for the "swallowing" of the timer/timer T1
  • OCF1A- Flag of the reprieve for the sub "zbіg A" of the timer/timer T1
  • OCF1B- Flag of the reprieve for the "start B" of the timer/timer T1
  • TOV1- Flag for resetting the timer/timer T1
  • OCF0- Flag of the reprieve for the "zbіg" timer/timer T0
  • TOV0- Flag for resetting the timer/timer T0

Description of robotic tayter/lighter T1 for controller ATmega8/16

A sixteen-digit timer/timer T1 can be used for forming hourly intervals, counting the number of ringing signals, and for generating signals with WIM different sparing and trivality on OC1A and OC1B windings. In addition, for the call signal from the ICP1 or from the analog comparator, T1 can save its flow mill in the ICR1 wet register.

Discharge registers TCCR1A:TCC1B:TCNT1:OCR1A:OCR1B:ICR1
Registry7 6 5 4 3 2 1 0
TCCR1A COM1A1 COM1A0 COM1B1 COM1BO FOC1A FOC1B WGM11 WGM10
TCCR1B ICNC1 ICES1 * WGM13 WGM12 CS12 CS11 CS10
TCNT1:H R/W R/W R/W R/W R/W R/W R/W R/W
TCNT1:L R/W R/W R/W R/W R/W R/W R/W R/W
OCR1A:H R/W R/W R/W R/W R/W R/W R/W R/W
OCR1A:L R/W R/W R/W R/W R/W R/W R/W R/W
OCR1B:H R/W R/W R/W R/W R/W R/W R/W R/W
OCR1B:L R/W R/W R/W R/W R/W R/W R/W R/W
ICR1:H R/W R/W R/W R/W R/W R/W R/W R/W
ICR1:L R/W R/W R/W R/W R/W R/W R/W R/W

The leather 16-bit register is physically spaced in two 8-bit registers to that hour of reading the record in which it is necessary to have two operations. When writing first, the older byte is read first, then the younger one, when read backwards, the younger one is read then the older one.

TCCR1A:TCCR1B- 8-bit registers for monitoring by the timer/timer T1

TCNT1- 16-bit personal register of timer/timer T1. In the fallow mode, the robot in the local register is reset, incremented (value increases by 1), or decremented (value changes by 1) according to the skin pulse of the clock signal of the timer / antler.

OCR1A:OCR1B- 16-digit port registers

ICR1- 16-bit holdover register, which saves the value of TCNT1 when an active edge is applied to the ICP1 output signal or to the comparator output signal.

Appointment of battles

COM1A1:COM1A0:COM1B1:COM1B0- Qi discharges determine the behavior of the OC1A:OC1B display when the value of the rachunk register TCNT1 and the order register OCR1A:OCR1B are changed

FOC1A:FOC1B- Qi discharge to serve for the primus change I will see OC1A:OC1B

ICNC1- The order of the control scheme of the jump code, so that the bit more "0" will be buried on the first active front, so "1" will be buried after the fourth identical selection of the signal of the sinking.

ICES1- Discharging the choice of the active edge of the signal, as long as the value is "0", saving the TCNT1 rachunk register in the OCR1 sinking register will be on the front of the signal, which falls, like "1" on the rising.

WGM13:WGM12:WGM11:WGM10- Discharging cycles to select the timer/lighter operation mode T1

CS22:CS21:C20- Discharge, which is assigned to the clock signal of the timer / clock T1.

Select the operating mode of the timer/chiller T1
WGM13WGM12WGM11WGM10Robot modeRahunku module (TOP)
0 0 0 0 Normal $FFFF
0 0 0 1 Phase Correct PWM

8-bit

$00FF
0 0 1 0 Phase Correct PWM

9-bit

$01FF
0 0 1 1 Phase Correct PWM

10-bit

$03FF
0 1 0 0 CTC OCR1A
0 1 0 1 Fast PWM

8-bit

$00FF
0 1 1 0 Fast PWM

9-bit

$01FF
0 1 1 1 Fast PWM

10-bit

$03FF
1 0 0 0 ICR1
1 0 0 1 Phase and Freguensy Correct PWM OCR1A
1 0 1 0 Phase Correct PWM ICR1
1 0 1 1 Phase Correct PWM OCR1A
1 1 0 0 CTC ICR1
1 1 0 1 reserved *
1 1 1 0 Fast PWM ICR1
1 1 1 1 Fast PWM OCR1A

Vibir dzherela clock signal

Normal Mode

The simplest mode of operation is T1. According to the skin pulse of the clock signal, the increment of the TCNT1 personal register is entered (the higher value is 1). When passing through the $FFFF value of the TIFR module, a reflow is caused and the oncoming clock cycle starts with the value of $0000, at the same moment the flag TOV1=1 is set in the TIFR register, and a reorder can be generated, as well as setting the flags TOIE1=1 in the register . In order to generate signals of a given frequency in this mode, it is necessary to write in the discharge COM1A1=0:COM1A0=1 to see OC1A or COM1B1=0:COM1B0=1 to see OC1B controller.

In addition, according to the skin tact, the order of the TCNT1 rachunka register and the OCR1A:OCR1B order are registered, when the order is changed, the order of the order OCF1A=1:OCF1B=1 is set and the order OCIE1A=1:OCIE1B=1 is also generated. At that very moment, the status of OC1A:OC1B may be changed depending on the settings of the battles COM1A1:COM1A0:COM1B1:COM1B0.

STS mode (skid when running)

In this mode, T1 follows the same principle as in Normal mode. The difference lies in the fact that the maximum possible value of the TCNT1 timer is intermixed with the value of the timer register OCR1A or ICR1 (look at the timer / timer mode selection table). When TCNT1 reaches the value of OCR1A or ICR1, the value of TCNT1 is reset to TCNT1=$0000 At this moment, the flag TOV1=1 is set COM1A1:COM1A0:COM1B1:COM1B0 Determine the behavior of OS1A:OC1B on startup.

Fast PWM mode (Swedcode PWM)

For an additional mode, you can generate a high-frequency PWM signal. The principle and order of operation is not considered in the Normal mode, except for the presence of the slave buffering register OCR1A:OCR1B, the appearance of asymmetric pulses in the signal is turned off, and it is also considered by the behavior of the OS1A:OC1B (div. table).


Phase Correct PWM mode

Enforcement of this regime is similar to that of the former in that the lichilny register works as a reverse lichilnik. Since this mode is recommended by Atmel as the most suitable for regulating engines, we will look at the report. When the value of the value of the value of the value of the value of the value of the value of the value of the value of the ICR1 register or the value of the OCR1A register is reached by the TCNT1 register TCNT1 (or the value of the ICR1 register or the value of the OCR1A register, look at the table for selecting the timer / chil mode), the value of the value of the value of the value of the value of the value of the value of the value of the value of the ICR1 register is changed directly. When the minimum value ($0000) is reached by the TCNT1 personal register, it will also change the account directly, and at that very hour, the flag of the TOV1 transfer to the TIFR register will be restored. Also, if you are equal in place of the TCNT1 check register and the OCR1A:OCR1B check register, the flag OCF1A:OCF1B will be set to the TIFR register and the checklist OC1A:OC1B will be changed, valid to the table.

In order to hide non-symmetric wikis at the hour of writing the value of the OCR1A:OCR1B register, this mode has a floating record buffering. The reason for changing the value of the register is changed at the moment when the TCNT1 rachunk register reaches the value of the rahunku module (TOR) (or the value of the ICR1 register or the value of the OCR1A register is to look at the table for selecting the timer / timer mode). To that, on the cob itself, when initializing the timer / counter of visnovka OS1A: OC1B, I will not change my position when the doti is increased, the dock register is not reachable (TOR).


Manager: We can expand the program for controlling the lighting of the heating lamp at 12 Volts for the help of PWM. When pressing on the "More" button, the brightness of the lamp increases, when pressing on the "Less" button, the brightness changes. The scheme of our future outbuilding is shown as a little one. How does the Atmega8 microcontroller sound, which is clocked like an internal generator with a frequency of 4MHz. Vlasne, we have a dimmer switch, and these attachments are designed for adjusting the brightness of lighting fixtures. Light dimmers were placed on the widest width.

For simplicity, before our scheme, you can also connect a light, but with a light bulb it will be better. Buttons connected to visnovkiv PD0, PD1. Navantage is connected to the visnovka PB1(OC1A) through a resistor and a MOSFET pole transistor, which is the most practical for us as a key (in key mode). A polar transistor is better than the fact that its isolation gate is in the power circuit and the control is vibrated by an electric field, and the control stream reaches microamperes. Tse allows, vikoristovuyuchi one or two transistors, cheruvati majestic intensities (up to tens of amperes and tens of hundreds of volts), not navantazhyuchi microcontroller. Vrahovyuchi also the fact that field transistors it is possible to connect in parallel (to the input of bipolar ones), it is possible to take off a larger exhaust cascade for hundreds of amperes.

Now let's figure out how the microcontroller implements WIM and write a program. As it was already mentioned before, our MK has 3 timers, and all stinks can work in PWM mode. We will use a sixteen-digit timer / chime. Bitami WGM13-10 we have adjusted our timer for the FastPWM robot with the upper boundary of the rahunka ICR1. The principle of the program is this, our timer rahuє vіd 0 to 65535 (0xFFFF), in register ICR1 enter the number 255, if the upper timer interval (TOP) is set, the frequency of the PWM signal will be constant. Also, our timer is adjusted to those that, when the account register is created, the controller will be switched to the register (TCNT1 = OCR1A) OC1A. You can change the PWM coefficient by writing to the offset register OCR1A the higher the number is from 0 to 255, the higher the number, the higher the filling coefficient, the brighter the lamp. In the same way, the button is changed i, and then it will be recorded in the register OCR1A.

The new text of the program is shown below. The comments of the report describe the robot program.

/*** Activity #8. Shaping PWM signals ***/ #include #include int main(void) ( unsigned int i=0; //signed to change i /***Fixed input port***/ PORTB = 0x00; DDRB |= (1<< PB1); PORTD |= (1 << PD1)|(1 << PD0); // подключаем внутренние нагрузочные резисторы DDRD = 0x00; /***Настройка таймера***/ TCCR1A |= (1 << COM1A1)|(0 << COM1A0) // Установим биты COM1A1-COM1A0:0b10, означает сброс вывода канала A при сравнении |(1 << WGM11)|(0 << WGM10); // Установим биты WGM13-10:0b1110, согласно таблице это TCCR1B |= (1 << WGM13)|(1 << WGM12) // будет режим - FAST PWM, где верхний предел счета задается битом ICR1 |(0 << CS12)|(0 << CS11)|(1 << CS10); // Битами CS12-10:0b001 задаем источник тактового сигнала для таймера МК, включен без делителя TCNT1 = 0x00; // начальная установка счетчика ICR1 = 0xFF; // задаем период ШИМ, здесь у нас число 255, // по формуле fPWM=fclk_I/O/N*(1+ICR1)// вычисляем частоту ШИМ, она будет равна 15625 Hz OCR1A = 0x00; // начальный коэффициент заполнения ШИМ /***Основной цикл программы***/ while(1) { if((PIND&(1 << PD0)) == 0) //если кнопка "больше" нажата { if (i < 254) { // коэффициент заполнения ШИМ изменяется от 0 до 255 i=i+1; // увеличиваем i на единицу OCR1A = i; // записываем переменную в регистр сравнения _delay_ms(30); // задержка 30ms } } if((PIND&(1 << PD1)) == 0) //если кнопка "меньше" нажата { if (i >0) // delay coefficient SHIM is changed from 255 to 0 ( i--; // change i by one (so you can write it) OCR1A = i; // write change to delay register _delay_ms(30); // delay 30ms) ) ) )

Respect! First, I feed food to the microcontroller, then we need to switch it up, so that the transistor comes to the MK, and then we don’t need to feed it to the lancet with a lamp and a half transistor. Otherwise, you can burn the transistor. On the right, in the fact that the "lows" of the MK "stay at the window" at the closed camp - the stench is not connected to anything, and the aim is blamed on them. Tsikh weak induce enough, schob often vіdkriti already sensitive polovy transistor. Todi yogo opir between the drain and the turn of the confluence in the vіd kіlkoh MOhm to the kіlkoh Om or the chasm Om і through the new flow a great strum to the lamp. But the transistor does not work properly, so for which it is necessary to apply not 1-3 guidance to the shutter, but stable 5, and this operation will be richer than the minimum. Tse brought to the sight of the new great kіlkosі heat, and vіn suffocate, or maybe burn.

We stumbled upon those ATtiny13 lighter/timer switches in the normal mode and the impulse control (CTC). In this article, I continue the theme of the timer, but now let's take a look at it for the implementation of pulse-width modulation (PWM).

All microprocessors work with digital signals, tobto. with a logical zero (0 V), and a logical one (5 V or 3.3 V). Ale, what work, how do we want to take on the exit as an intermediate value? Such vipadkas get stuck Pulse Width Modulation(PWM, eng. pulse-width modulation (PWM)) - the process of controlling the intensity, which is brought to the saturation, by changing the spacing of the pulses, at a constant frequency.
Pulse width modulation - periodic pulse signal. Use digital and analog PWM, unipolar and bipolar, etc. Ale, the principle of their work remains the same independently in the presence of viconnance and field in the paired two types of signals: reference (pilk-like or tri-current impulses) and input (permanent, or changed by the necessary order, fallow in the specific tasks of the PWM). Qi signals are equalized and when they change, the value of the signal at the PWM output is changed. The output voltage of the PWM can look like straight-cut pulses, changing their trivality, we can regulate the average value of the voltage at the output of the PWM.

* If you want to integrate the RC-lance at the output of the PWM, then you can replace the impulse voltage and take the constant voltage of the required value. But in our butt with light diodes, you can do without it, because the human eye still cannot see the measure of light at the clock frequency.

PWM parameters

  • T is the period of clocking (of the reference signal);
  • t - tivality to the impulse;
  • S - sparing;
  • D - filling coefficient.

The goodness depends on the setting of the period until the momentum is torn. The coefficient of filling is the value of the return of spalling (may vary in widths):

S=T/t=1/D

Let's take a look at the report, how PWM is used in AVR microcontrollers, on the ATtiny13 butt.
As already suggested in the front buttstock, ATtiny13 implements two different types of PWM: the so-called "Shvidka PWM" (Fast PWM) and "PWM with phase correction" (Phase correct PWM). Obidva variant of foundation on vikoristan vbudovannoy MK eight-bit lichilnik/timer T0. The timer overrides the reference signal. The clock speed of the timer is set by the processor clock front end, or the external clock generator. The clocking mode is set by bits CS02 (2), CS01 (1), CS00(0) register TCCR0B:

  • 000 - timer/timer T0 zupineno
  • 001 - clock generator CLK
  • 010-CLK/8
  • 011-CLK/64
  • 100-CLK/256
  • 101-CLK/1024
  • 110 - sight of the ovnishny dzherel on the visualized T0 (lower 7, PB2) on the decline of the signal
  • 111 - sight of ovnishny dzherel on sight T0 (lower 7, PB2) according to signal growth

Setting the timer for PWM

Timer operation mode is set by bits WGM01(1) that WGM00(0) register TCCR0A:

  • 00 - normal mode
  • 01 - PWM phase correction mode
  • 10 - booster mode
  • 11 - PWM mode

Here we are ticked by options "01" and "11".

Beaty COM0A1(7) that COM0A0(6) register TCCR0A set what signal to appear on the OC0A display (5 lower, PB0) when the lichnik is selected (registry TCNT0) with register A ( OCR0A).

For "Shvidka ShIM" mode:

  • 10 - setting 0 on OC0A sighting when starting from A, setting 1 on OC0A sighting when resetting the counter (non-inverse mode)
  • 11 - setting 1 on the view of OC0A when starting from A, setting 0 on the view of OC0A when the counter is reset to zero (inverse mode)
  • 00 - OC0A not working
  • 01 - if the WGM02 bit of the TCCR0B register is set to 0, the OC0A switch is not functional
  • 01 - also the WGM02 bit of the TCCR0B register is set to 1, OC0A will be displayed on the length when A is entered
  • 10 - setting 0 on the view of OC0A when increasing from A the hour of the increase in the value of the clock, setting 1 on the view of OC0A when the increase of the A is the hour of the change in the value of the clock (non-inverse mode)
  • 11 - setting 1 on the view of OC0A when increasing from A the hour of the increase in the value of the clock, setting 0 on the view of OC0A when the increase of the A is the hour of the change in the value of the clock (inverse mode)

Beaty COM0B1(5) that COM0B0(4) register TCCR0A set what signal to appear on the OC0B (6 lower, PB1) when the lichnik is selected (registry TCNT0) with register B ( OCR0B).

For "Shvidka ShIM" mode:

  • 01 - reserve
  • 10 - setting 0 on the OC0B output when the B is running, setting 1 on the OC0B output when the counter is reset to zero (non-inverse mode)
  • 11 - setting 1 on the OC0B output when the B is running, setting 0 on the OC0B output when the counter is reset to zero (inverse mode)

For the "PWM out of phase correction" mode:

  • 00 - OC0B not working
  • 01 - reserve
  • 10 - set to 0 on the OC0B view when the time of the change in the time of B is changed, the setting is 1 on the view of the OC0B when the time of the change in the time of the day is changed (non-inverse mode)
  • 11 - set to 1 on the OC0B view when the time value is increasing, the time of the change in the time value is set to 0, the setting is 0 on the OC0B view when the time value is decreasing (inverse mode)

Shvidka PWM (Fast PWM)

In this mode, the lichilnik fluctuates from zero to the maximum. When the zero value of the lichnik is set, an impulse appears at the output (a logical unit is set). When zbіgu z pіvnyannya register - the pulse is thrown off (logic zero is set). In the inverse mode, in reverse, on the contrary.

PWM from phase correction (Phase correct PWM)

In this mode, the lichilnik vvazhє vіd zero to the maximum, and then in the gate directly, to zero. When zbіgu z register pіvnyannja pid hour of the increase in the value of the lichnik - the impulse is thrown off (a logical zero is set). When zbіgu pіd h falls - an impulse appears (a logical unit is restored). In the inverse mode, in reverse, on the contrary. Short of this mode, the double clock frequency was changed against the Fast PWM mode. Then, when changing the sparing, the centers of the impulses do not move. The main feature of this mode is the stability of the rich-phase PWM signals, for example, the three-phase sinusoid, so that when changing the spacing, the phase transition between the two PWM signals is not lost.

Sobachit in person, as a practice of WIM, we will write a small program (all the rest I will spend on my tax payment, I’m sure the code will be put a hundred and fifty times):

/* * tiny13_board_pwm * ATtiny13 custom juggle board demo firmware. * Demonstration of PWM work on two channels: * non-inverse signal at the OC0A output, inverse - at the OC0B output. */ #define F_CPU 1200000UL #include #include #define LED0 PB0 // OC0A #define LED1 PB1 // OC0B int main(void) ( // Light: DDRB |= (1<< LED0)|(1 << LED1); // выходы = 1 PORTB &= ~((1 << LED0)|(1 << LED1)); // по умолчанию отключены = 0 // Таймер для ШИМ: TCCR0A = 0xB3; // режим ШИМ, неинверсный сигнал на выходе OC0A, инверсный - на выходе OC0B TCCR0B = 0x02; // предделитель тактовой частоты CLK/8 TCNT0=0; // начальное значение счётчика OCR0A=0; // регистр совпадения A OCR0B=0; // регистр совпадения B while(1) { do // Нарастание яркости { OCR0A++; OCR0B = OCR0A; _delay_ms(5); } while(OCR0A!=255); _delay_ms(1000); // Пауза 1 сек. do // Затухание { OCR0A--; OCR0B = OCR0A; _delay_ms(5); } while(OCR0A!=0); _delay_ms(1000); // Пауза 1 сек. } }

Here Bachimo, that from the start of the MK in the register A and B is set to 0, and the counter is started as Fast PWM, with the generation of a non-inverse PWM signal at the output OC0A and inverse - at the output OC0B. In the main cycle, the values ​​of the registers are gradually changing from 0 to the maximum and back. As a result, the light, connected to the OC0A and OC0B visnovk, will gradually light up and go out, as if in antiphase.
And yet, if you are more respectful, it’s better that one of the lights does not go out until the end, but continues to glow in the dark. What is special about Fast PWM mode. On the right, in what is in this mode, you should write it down as a record in the register 0 when the lichnik is reset to zero at the exit, all the same, a logical unit is restored, as if it is thrown off in the offensive tact (increase with the register of the difference). In this way, in the skin period, skip one short pulse of trivality 1 cycle, a little enough to light up the light. This effect is not possible in the inverse mode of forming the outer impulses, because at times, when the lichilnik is reset to zero, not a short pulse occurs, but instead - a short dip for the hour of the maximum PWM load. This failure can be traced on an oscilloscope, but such a merekhtinnya of the light of the human dawn simply cannot be remembered. To that, another light was spalah and extinguished over and over. In the PWM mode with phase correction, the effect is independent during the day, the inverse signal is formed at the output. Remember the value of the bit WGM01(1) register TCCR0A from 1 to 0.

PWM (PWM) - pulse-width modulation. It is not required to slander that term. This is the only way to regulate the voltage. It is permissible for the monitor to light up brightly over it, and you change the brightness. And what does it look like really?

It should be noted that the monitoring of the monitor is a little bit of light. To live all right in the light of constant stress. But we needed to change the brightness of the monitor. It is logical to say that it is possible to work with a change resistor. On small streams it is possible. Ale on the great ones, the resistor gets very hot. Significantly increase in size, waste, energy supply.

That's why people came up with a circuit on transistors, like to rob from a constant voltage pulsing. It appears, pulsating voltage, fallow during the period, it will be equivalent to the constant voltage. Tobto. If for a long period the voltage is 50% turned on, 50% is switched off, then the equivalent constant voltage is equal to 50% of the nominal voltage.

The numbers are simple - they drove 5V of constant voltage through the PWM - they took 2.5V. If the impulse is equal to 75%, then the constant voltage will be equivalent to 3.75V. I think the idea made sense.

Now let's get down to practical implementation. With the help of the microcontroller, we will change the level from 0 to 100%, then from 100% to zero. The end result might look like this:

Sob it was on the spot, turn on the light. As a result, we will smoothly switch on and turn on the light.

Let's launch our favorite CodeVision. We create a project for the assistance of the master. At the timer distribution (Timers), choose Timer 2 and install it like a baby.

If you try to generate a project, then the program can be welded. Let's wait, even if we have a leg 3 porti In May, buti is sewn like a wind.

We direct the code to the offensive form:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include void main (void) (PORTB = 0x00; DDRB = 0x08; // Timer/Counter 2 initialization ASSR = 0x00; TCCR2 = 0x6C; TCNT2 = 0x00; OCR2 = 0x00; TIMSK = 0x00; while(1)(); )

#include void main(void) ( PORTB=0x00; DDRB=0x08; // Timer/Counter 2 initialization ASSR=0x00; TCCR2=0x6C; TCNT2=0x00; OCR2=0x00; TIMSK=0x00; while (1) ( );

Let's pay attention to the row OCR2 = 0x00; Qia zminna still depends on the magnitude of the filling of the impulse. The value is changed from 0 to 255(0хFF), then. 255 proving 100% restocking (permanent strum). Also, it needs 30% restocking (255/100)*30=77. Dalі 77 is translated into hexadecimal system OCR2 = 0x4D;

TCCR2=0x6C; By changing the value, we can adjust the PWM frequency. The value of the frequency of the PWM robot is a multiple of the frequency, on the same working microcontroller. In the project, the frequency of the microcontroller was 8 MHz, the PWM frequency was 125 kHz, also the driver is 8/125 = 64
0x6C in binary number system 1101100, datasheet on Atmega8 and Bachimo description to register TCCR2, so axis 1101 100 the remaining digits 100 and are given for the choice of PWM frequency

Let's get straight to the program:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include #include void main(void ) ( PORTB = 0x00 ; DDRB = 0x08 ; ASSR = 0x00 ; TCCR2 = 0x6C ; TCNT2 = 0x00 ; OCR2 = 0x00 ; TIMSK = 0x00 ; while (1 ) ( wh< 0xff ) { OCR2= OCR2+ 0x01 ; delay_ms(5 ) ; } while (OCR2>0x00) (OCR2 = OCR2-0x01; delay_ms(5);)); )

#include #include void main(void) ( PORTB=0x00; DDRB=0x08; ASSR=0x00; TCCR2=0x6C; TCNT2=0x00; OCR2=0x00; TIMSK=0x00; while (1) ( while(OCR2<0xff) { OCR2=OCR2+0x01; delay_ms(5); } while(OCR2>0x00) ( OCR2=OCR2-0x01; delay_ms(5); ) ); )

The code is simple to the point of dissimilarity: the order of the cycle is increased from 0 to 255(ff), then we change from 255 to 0.
I nasamkinets vidosik, as everything can be practiced. Good luck with the vivchenni)

Updated 12/16/15. Hello everyone. Having sorted out the past record from the EEPROM memory, today we'll talk about those that are PWM (PWM)? It is deciphered as pulse-width modulation, the average value of the voltage, as it changes the sparing of the pulse. Into your hell sverdlovsky ce trivality of the impulse with a certain frequency of repetition. Tobto. In the simplest words, all change the width of the impulse at a constant value. What else do we need?

ШІМ (PWM) works in a transistor circuit for voltage regulation without mechanics, with its own power control. For example, control of brightness of light-emitting diodes, control of brightness of light on LCD-monitors, control of motors, etc. If you look at the little one, then the exit from the microcontroller will be approximately stepping on, like the little one is lower. It can be seen that the sparing is the same as the pulse, since the entire width of the pulse is 5, then at 30% of the pulse, the average output is approximately 1.5V. For microcontrollers AVR PWM control is set for eight-bit timers / clocks T0 / (T2) and sixteen-bit T1 (T3 for some models). And also є Інші models, the debit number of the SHІMU can be set, for example ATmega 128. Let's look at the setting of the sixteen-digit timer / clock T1. Data are taken according to the table or from the document, or from the datasheet (literature - Article No. 1).

For such a lighter in MK, you can select three modes: Fast PWM, Phase Correct PWM, Phase and Frequency Correct PWM ( deposit in model)

Let's look at another mode - PWM with exact phase. Here the personal register functions as a reverse license, change it will change from $0000 to the maximum value, and then back to $0000. There are three registers TCCR1A, TCCR1B, TCCR1C for chirping by a timer/chirker. In order to select the timer/chiller mode, it is necessary to set the WGMn1: WGMn0 and WGMn1: WGMn0 bits . Depending on the setting of the maximum value of the chime (Adjustment of the PWM signal) or fixed values, or it is displayed instead of the first registers of the timer/chiller. Razdіlna zdatnіst signified by viraz :

g = log (TOP + 1) / log2, de TOP - module rahunku, selected from the table depending on the distribution of housing.

After that, as you have chosen the operation mode of the timer, it is necessary to select the operation mode for the synchronous block COMnA1: COMnA0, COMnB1: COMnB0, COMnC1: COMnC0, which determines the behavior of the OCnx output when “Zbіg” is activated.

Well, the rest of the stroke is significant from the frequency. We need to set the CSn2…CSn0 bit to the TCCR1B register, so that the clock signal is assigned to the clock signal. The axis in such a program way looks like the setting of the PWM-curve on the OC1A output. For example:

/*Fixed PWM */
TCCR1A=(1</* OC1A is displayed one, if OCR1A==TCNT1, Drops to 0 when OCR1A==TCNT1 and resets to 1 when the maximum value is reached eight-bit PWM Phase Correct PWM, mode number 1 . Rahunku module TOR $00FF*/
TCCR1B=(1<OCR1A = 50; /* with a modulus of 255 and with a voltage of 5, approx. 1 V is taken at the output OC1A */

It can be seen from the program that for the selection of the WIM it is possible to use the register OCR1A. When the lichnik reaches the maximum value, in this period of 255, the change is directly changed, but the lichnik is left in the same period with a signal for one period. In this case, the frequency of work is more correct in the opposite mode. Ale, in this way, the symmetry of the change of the lichnik is poked. What is the most suitable for keruvannya with a dvigun. In such a tact, there is an update in place of the register of order. When the minimum value is reached by the lichnik, it is also necessary to change the account directly, and the flag of transferring TOV1 to the TIFR register is immediately installed. If equal, instead of the Rakhunkian register, the same register will be replaced by the new ensign OCF1A/OCF1B/OCF1C to the TIFR register. The OCnx block will change overnight. H frequency of the signal to be generated fOCn \u003d f / (2 * N * TOP), de N - coefficient of the representative subdivision, f - frequency of quartz. Also, you can marvel at the butt of the lashing and vikoristannya ShІM, for example.

Everything is good for what. At the next post, we can see CNC amateur layout controller. I will try to highlight the front post of this blog for the set of programs like a constructor. So it will be more sensible, if once they wrote and yogo vikoristali in the upcoming project. All to hell.

In the attachments of microcontrollers, it is sometimes necessary to generate an analog signal. Depending on the frequency of the analog signal, the necessary permission and type of microcontroller, which can be victorious, can be vikonated in dekilkom ways. And for itself: for additional pulse-width modulation, vicorist functionality of hardware timers or software implementation, for the help of a built-in digital-to-analog converter (DAC), for the help of external circuits of digital-to-analog converters on discrete elements or for additional digital-to-microcircuits.

1. The principle of generating an analog signal for auxiliary PWM (PWM)

PWM signal is a digital signal, in which the repetition period is constant, and the duration is changed. The increase in the trivality of the PWM signal until the 1st period is called the saturation coefficient. Having passed such a signal through a low-frequency filter, which, in fact, is equally integrable, we take at the output of the filter a voltage equal to the load factor.


In this way, a smaller coefficient can generate analog signals of a sufficient form. Moreover, like a change, for example, a sinusoid, a file like a human language, so it’s constant (a good amount of pressure).

1.1 Signal characteristics

Maximum amplitude of the output analog signal be determined by the amplitude of the logical unit of the digital PWM signal. If the microcontroller operates at +5, then roughly, the amplitude of the output analog signal will be between 0 and 5 V.

Minimum term for changing the analog signal(dozvіl) signified by viraz:


dUa = Umax/2^n,


de Umax is the maximum amplitude of the analog signal (V), and n is the size of the device that implements the PWM.

For example, a PWM signal is formed behind the help of a software 8-bit lichnik. The number of gradations of the PWM signal, which can be taken as an additional indicator, is good 2^8 = 256.


dUa = 5/256 = 0.0195 st.


PWM signal frequency let's define it like this:


Fpwm = Fcpu/(K*2^n),


de Fcpu – clock frequency of the microcontroller (Hz), K – coefficient of the prescaler of the lichnik, n – digit capacity of the lichnik.

For example, the clock frequency of the microcontroller is 8 MHz. Then the frequency of the output PWM signal is additional:

Fpwm = 8000000/(8*256) = ~3906 Hz


Analog output frequency be denoted by viraz:

Fa = Fpwm/Ns = Fcpu/(K*2^n*Ns),


de Fpwm is the frequency of the PWM signal, and Ns is the frequency of the analogue signal.

For example, a PWM signal is implemented on an 8-bit lichnik with a prescaler coefficient equal to 8 and a microcontroller clock frequency of 8 MHz. The memory of the microcontroller has 32 samples of a sinusoidal signal, i.e. one 10th period. Then the frequency of output sinusoids is more advanced:

Fa = 8000000 / (8 * 2^8 * 32) = ~ 122 Hz

The discharge capacity of the DAC'a crushed on the basis of WIM is equivalent to the discharge capacity of the vicorous lighter.

1.2 Hardware implementation of PWM

All current microcontrollers have timers/chillers at their warehouse. One or more modes of these timers are assigned to generate a PWM signal. As a rule, the whole signal is generated on special windings. For example, Atmel's mega16 microcontroller 8-bit timer/alarm T0 has two modes of generating a PWM signal (switched PWM and PWM with precise phase), and for the signal to be generated, pins to port B - OC0 (PINB3) are used.

The efficiency of the hardware implementation of the PWM signal - the cost of the microcontroller is low (interruption calls once per period of the PWM signal), simplicity and accuracy (there is little interruption in the system). Three small spaces can be considered - the number of lichniks is fenced, the frequency is low, the number of channels is fenced, on which it is possible to generate PWM signals. I want to develop special microcontrollers specially "sharpened" for generating a large number of PWM signals.

1.3 Software implementation of PWM

It is also possible to generate a PWM signal programmatically. For this, it is necessary to simply create a program timer and, after the signal of the hardware timer, increment its value and reach the extreme value of the timer, in which case the signal changes the setting.

The advantage of the software implementation is simplicity, the number of channels is not fenced, and the buildings are not fenced. Zvichayno, mentally unbounded, with improved memory available.Shortfalls in software implementation - the high level of interest in the microcontroller. Reversing the guilt of calling on the skin increment of the lichilnik and it is necessary to reconsider, if the fault does not reach one of the extreme values. Also, the software implementation may have less accuracy (more than three fronts in the signal) and also less frequency (after the first half).

However, regardless of the price, the software implementation of the SHIMu can also be used, as it is necessary to generate a constant analog signal, or a change, but with a low frequency.

Below is an example of a code, which viconizes the function of generating an analog signal for additional hardware and software pulse-width modulation. Writing code for atmega16 microcontroller, clock frequency 8 MHz, IAR compiler. At the outputs PB2 and PB3, two sinusoids (different frequencies) from 32 two signals are generated.


#include
#include
#include

#define SPWM_PIN 2

//sine table
__flash uint8_t tableSin =
{
152,176,198,218,234,245,253,255,
253,245,234,218,198,176,152,128,
103, 79, 57, 37, 21, 10, 2, 0,
2, 10, 21, 37, 57, 79,103,128
};

uint8_t softCount = 0;
uint8_t softComp = 0;

int main(void)
{
//setting up ports
PORTB=0;
DDRB=0xff;

// Allowed a respawn for T0 gain
TIMSK = (1<//FastPWM mode, non-inv. PWM signal, prescaler 8
TCCR0 = (1< (0<

//reset the personal register
TCNT0 = 0;
OCR0 = 0;

enable_interrupt();
while(1);
return 0;
}

// reset timer T0
#pragma vector = TIMER0_COMP_vect
__interrupt void Timer0CompVect(void)
{
static uint8_t i = 0;
static uint8_t j = 0;

OCR0 = tableSin[i];
i = (i + 1) & 31;

// software PWM
softCount++;
if (softCount == 0)(
PORTB |= (1<softComp=tableSin[j];
j = (j + 1) & 31;
}

If (softCount == softComp)(
PORTB &= ~(1< }
}

1.4 Filter for PWM

The frequency of the filter is to blame but between the maximum frequency of the analog signals that are generated and the frequency of the PWM signal. In this case, the frequency of the filter will be selected close to the range of the analog signal, which will result in some attenuation. And if the frequency of the filter will be close to the frequency of the PWM signal, the analog signal simply will not be "seen". The higher the frequency of the PWM signal, the easier it is to implement the external filter.

Let's look at an example. The PWM signal is generated by a hardware 8-bit clock with a prescaler coefficient equal to 8, the clock frequency of the microcontroller is 8 MHz, the number of analogue signals is 32.

The frequency of the PWM signal is additional:

Fpwm = Fcpu/(K*2^n) = 8000000/(8*256) = ~3906 Hz

The frequency of the analog signal is adjusted:

Fa = Fpwm/Ns = 3906/32 = 122 Hz

We select the frequency equal to 200 Hz and the rating of the passive low-frequency RC filter. The frequency of such a filter is determined by the frequency:

Fc = 1/(2*Pi*R*C),

de R is the resistor value (Ohm), and C is the capacity of the capacitor (F).

Given the denomination of one of the components, you can calculate the denomination of the other. For a resistor with a nominal value of 1 kOhm, the capacity of the capacitor is more:


C = 1/(2*Pi*Fc*R) = 1/(6.28*1000*200) = ~0.8uF


We choose the closest value from the E12 series - 0.82 uF. For such ratings of the filter, we take a similar analog signal.

However, as a rule, one side of the passive filter will be enough. Because of this, the analog signal is still worthy of the large number of harmonics.

© 2022 androidas.ru - All about Android