Laboratorul 0xC2: PWM, Counters and External Interrupts

This lab covers the topics of PWM, H-bridge drivers and reading encoders using external interrupts. For more in-depth knowledge about the capabilities and the timing peripherals and how to program them you can find more information in the ATmega324 datasheet (Datasheet ATmega324).

PWM (Pulse Width Modulation)

PWM (Pulse Width Modulation) or PDM (Pulse Duration Modulation) is a modulation technique used to reduce the average power delivered by an electrical signal to a load by chopping it into discrete parts. The average value of a signal is dependent on the maximum and minimum amplitude and on the duration of the pulses of minimum and maximum amplitude.

PWM - Electronics and average voltage

In order to use PWM and prior to program our microcontroller to generate PWM signals, we first need to understand the basics of PWM and how to use it in different circuits.

Understanding PWM signals

The output signal (or the Pulse Width Modulated signal) will be generated by using electronic switches (such as Bipolar Transistors, MOSFET Transistors, IGBT) that connects a positive voltage power supply (e.g. a battery or a fixed voltage output) for a precise amount of time (T1) to the output, afterwards it connects a negative voltage (or the GND for unipolar PWM) the output from the power supply for another amount of time (T2), and than, the cycle repeats.

In the following schematic, we can see that Q1 connects the output to the positive voltage supply (Vmax) and Q2 connects the ouput to the negative voltage supply (Vmin). Q1 and Q2 are controlled by a more complex circuit (transistor driving circuit), based on the signals given by the microcontroller (MCU).

NPN and N-MOS transistors and NPN IGBT transistors are preferred to be used both on the high side and on the low side (to connect Vmax and Vmin) because of the mobility of electrons, compared to the mobility of holes in P-channel solid state components. Furthermore, besides the main argument regarding mobility of electronics, design techniques and drivers are in favor of N-channel transistors. N-channel Mosfets, NPN IGBT transistors, to be turned on, need a positive impulse in their control pin (gate or base). Direct logic control is easier to manage and to follow in schematic. For a more details please study specialized documents related to power electronics, inverters and drivers. From the bill of materials viewpoint, it is always cheaper to increase the number of one component than to increase the number of component types.

The transistor driving circuit is sometimes necessary because of the different voltage levels of the MCU and the voltages of the power supplies.

Control Q1 and Control Q2 signals in the push-pull totem-pole topology DOES NOT come directly from the microcontroller. These signals should be generated with a driving circuit, through impulse transformers or driving optocouplers. Because the voltages of Vmax and Vlow are way different than the operating voltage of the microcontroller, connecting ControlQ1 and ControlQ2 directly to the microcontroller will result in a short circuit and the destruction of the microcontroller and the transistors.

All the voltages are measured with respect to GND, unless otherwise is explicitly noted.

The output signal delivered to the load will look similar to the one showed in the next figure:

As we can observe, in one cycle (of duration T=T1+T2) the signal is switched between Vmax and Vmin.

  • Q1 is turned ON (and Q2 is OFF) for an interval of T1, and the output is forced to Vmax
  • Q2 is turned ON (and Q1 is turned OFF) for an interval T2, and the output is forced to Vmin
  • The cycle duration is T=T1+T2;

The average voltage of the signal (measured with respect to GND) can be calculated by computing the integral over time. V_1

\begin{equation} V_{avg}=\frac{1}{T}\int_{0}^{T} Vout(t) dt \end{equation}

Considering for one cycle, that from 0 to T1 the output is Vmax and from T1 to T (interval equal to T2) the output is Vmin than the average voltage will be computes as follows:

\begin{equation} V_{avg}=\frac{T1}{T}V_{max} + \frac{T2}{T} V_{min} \end{equation}

In electronics, the ratio between T1 (the duration of the positive pulse) and the period T is called the duty cycle. The duty cycles tells us how much time, compared to the total period, the positive pulse duration is.

\begin{equation} d=\frac{T1}{T} \end{equation}

The duty cycle can be measured as a (percentage) \% and it resembles the fraction of the positive pulse (T1) compared the total period (T).

\begin{equation} d_{\%}=\frac{T1}{T}100 \end{equation}

Considering the definition of the duty cycle, the average voltage is:

\begin{equation} V_{avg}=d\cdot V_{max} + (1-d)\cdot V_{min} \end{equation}

For the signal showed in the previous figure, we can observe that T1 is 7.5ms and T2 is 2.5ms (T=10ms), Vmax=10V, Vmin= -10V. That leads us to $d=0.75$ or $d\%=75\%$

Thus, our output average voltage will be:

\begin{equation} V_{avg}=0.75\cdot 10 + 0.25\cdot (-10)= 5V \end{equation} For an unipolar signal (the signal is switched between Vmax and 0 (GND) ) the average voltage will be computed as:

\begin{equation} V_{avg}=\frac{T1}{T}V_{max}=d\cdot V_{max} \end{equation}

For example, the following signal is switched ON to 10V for 7.5ms and OFF (to 0V) for another 2.5ms (T=10ms, d=0.75).

\begin{equation} V_{avg}=\frac{7.5ms}{10ms} \cdot 10=0.75 \cdot 10 = 7.5V \end{equation}

PWM is used in many applications where with a digital control different elements are controlled. For example, PWM can be used to control the speed of DC motors, to control the brightness of LEDs, to generate different colors using RGB LEDs (by controlling the intensity of each color), to generate analog signals (generating AC from DC), reducing the power and voltage from a power source, in MPTT solar battery chargers/controllers, in D-Class audio amplifiers, etc.

Example of PWM used to generate a sinusoidal waveform:

PWM on LEDs

Driving LEDs is done the same way as for simple digital outputs, as explained in our previous labs. If the LED is a high power device (more than 25mW LED), we will need a controllable LED driver (usually based on a switchable current supply).

The LED can be connected from the output of the MCU to GND with a resistor and it will light up when the MCU pin is driven HIGH. The resistor is used to limit the current through the LED.

The LED can be connected from the power supply to the MCU pin and it will light up when the MCU pin is driven LOW (the current will flow from Vcc to the MCU pin).

If we need to power a high power load or a higher power LED we can use a transistor to switch on and off the load. R1 can be replaced with a constant current supply

Delivering PWM for DC brushed motors and other loads

We have to take in consideration that in our applications we might encounter inductive loads such as relays, motors, inductors, chokes, electro-valves, etc. For these types of loads we need to provide a protection to the switching element (transistor) for transients. This is done by using a flyback (snubber) diode that is used to clamp the reverse inductive currents (more details Wikipedia Flyback diode)

Unidirectional motor/general load driver circuit

In the next schematic, L1 is our load that might have an inductive characteristics. In order to protect the transistor, we use the flyback diode D1. The PWM will be generated by the microcontroller and will control the base of Q1.

H Bridge principles and examples

When using motors, we sometimes need to reverse the polarity in order to make it spin in the opposite direction. Sometimes we need to short-circuit the terminals in order to slow the motor down. To obtain such functionalities, H-bridge circuits are used. An H-bridge circuit, at conceptual level is constructed using 4 switches (2 pairs of 2 switches organized in a totem-pole). The load will be connected between the outputs of the totem-pole. Using H-bridge circuits:

  • By Activating S1 and S4 the motor will be polarized in one way - pathway of the current is represented with green (S2 and S3 are turned OFF)
  • By activating S2 and S3 the motor will be reversely polarized, and it will rotate in the opposite way - pathway of the current is represented in red (S1 and S4 are turned OFF)

  • By activating S1 and S3 (pathway of the current is purple) OR S2 and S4 (pathway of the current is dark blue) the motor will be short-circuited and will brake.

When designing and building H-bridge circuits be sure that there is no way that two transistors in the same totem-pole can activate in the same time. If, by any chance S1 and S2 or S3 and S4 will conduct electricity simultaneously they will short circuit the power supply and the circuit will cease to work. In some cases this situation can cause short-circuits that might generate a fire hazard or excessive heating

For more information on H-bridge circuits you can check out H-bridge Wikipedia Page

Usually S1-S4 are in fact transistors (BJT, IGBT, MOSFETS) that are controlled through a specialized circuit that does not allow, in any circumstances, two adjacent transistors to open simultaneously.

One of the most known full H-bridge circuits used by many are L298 (dual full H bridge) and L293 (quad half H-bridge) integrated circuits, that contains 2 full H bridge circuits that can be paralleled for a higher output current. (source L298 Datasheet)

The internal structure consists of 4 transistors, and some combinatoric logic gates that assure us that the transistors can be controlled in such a way that they will not cause overloads on the power supply. Also, the control circuits does the level shifting, allowing us to control from a 5V microcontroller, a motor that will be powered up from higher voltages.

Taking in consideration our previous mentions, since the motor is an inductive load, we need to provide the circuit with protection diodes.

As we can see from the L298 Datasheet, we need 2 diodes/totemic pole, 4 diodes in total for a Full H Bridge circuit.

(source L298 Datasheet) Also, we can observe a shunt resistor placed between the SENSE pin and ground, used for the microcontroller to measure the current through the motor. On the right hand side of the figure we can see a table showing us how different input states affect the functionality of the H bridge.

Using H-bridge circuits and more complex programming we can control three-phase motors and generate 3-phased AC voltage from DC (as in PV solar power plants) Controlling 3-phase motors with PWM

Generating PWM using ATmega Timers

PWM can be generated software, in code, by bit-banging the MCU output PIN high and LOW by repeating continuously

  • Set Pin High
  • Wait for T1
  • Set Pin Low
  • Wait For T2

The issue here would be that we need to determine how much time does the code before this sequence or after it take to execute. Another solution would be to use timer interrupts and in the ISR to change the state of the pin. In this manner, we will at least have a precise timing, but we will generate many interrupts that might affect our code in some situations.

Timers available in ATmega324 and other AVR core based microcontrollers can be used to generate PWM signals. As you remember from the previous lab, the timers are units that can count up and when they overflow or when their value (in TCNTn register) is equal with a compare value (stored in OCRnA and OCRnB registers) they generate an event (e.g. interrupt, pin-change, etc.). Besides the interrupts that these timers can generate, we have the possibility to program them to change the state of a pin (pins named OCnA and OCnB) when the timer overflows or when TCNTn is equal to ICRn OCRnA or OCRnB.

The ATmega timers have two possibilities to generate PWM:

  • Fast PWM, a method that uses a comparator and an overflow event
  • Phase Correct PWM, a method with twice the accuracy, and when using multiple PWM outputs, the pulses will be centered.
  • Phase Correct and Frequency Correct PWM, similar to Phase Correct PWM, but with a more precise frequency controlled.

First, we need to identify the PWM capable pins. We can identify by looking for the alternative functionality OCnX

Fast PWM mode

Fast PWM is the most simple way to generate a PWM signals on AVR core based microcontrollers. It uses the counters as described in ATmega324 Datasheet

The counter counts from BOTTOM to TOP then restarts from BOTTOM. In non-inverting Compare Output mode, the Output Compare (OCnx) is cleared on the compare match between TCNTn and OCRnx, and set at BOTTOM. In inverting Compare Output mode output is set on compare match and cleared at BOTTOM. Due to the single-slope operation, the operating frequency of the fast PWM mode can be twice as high as the phase correct and phase and frequency correct PWM modes that use dual-slope operation. This high frequency makes the fast PWM mode well suited for power regulation, rectification, and DAC applications. High frequency allows physically small sized external components (coils, capacitors), hence reduces total system cost.

(source ATmega324 Datasheet)

From ATmega324 Datasheet in Chapte 15-17 you can read more about timers. Configuration bits are found in TCCRnA, TCCRnB and TCCRnC (configuration is dependent on the timer specs).

The PWM resolution for fast PWM can be fixed to 8-, 9-, or 10-bit, or defined by either ICRn or OCRnA. The minimum resolution allowed is 2-bit (ICRn or OCRnA set to 0x0003), and the maximum resolution is 16-bit (ICRn or OCRnA set to MAX).

We can configure the timers in different ways, so that the timers count up to overflow, to ICRn or to OCRnA.

Configuring/selecting different modes can be done using the Waveform Generation Mode bits (WGM) Let's see the WGM config bits for Timer 1. (source ATmega324 Datasheet))

After we choose the WGM bits for 8-bit FAST PWM we need to choose a normal port operation: OCn set when timer rolls from TOP to BOTTOM and OCn is cleared on compare match with OCRn. The selection of this functionality is done using the COM bits for Fast PWM mode.

(source ATmega324 Datasheet) Last but not least, remember:

a timer, in order to do it's job, needs a clock source. Thus, we need to select the proper clock source.

The Clock Source bits for timer 1 need to be set in TCCR1B. For other timers check the datasheet. (source ATmega324 Datasheet)

The output frequency of a fast PWM pin is dependent on the prescaller and the clock frequency of the MCU. According to Section 17.7.3 \begin{equation} f_{OCnX}=\frac{f_{clk\_IO}}{2 \cdot N \cdot 256} \end{equation}

Let now try a simple example with OC1A as output (PD5) set to fast PWM (8 bit) with a top at 0xFF.

//Set PD5 as output
DDRD |= _BV(PD5);//_BV(X) is equivalent to (1<<X)

//According to table 16-5 , for Fast PWM 8-bit mode, we have to set WGMn0 and WGMn2 
TCCR1A |= _BV(WGM10); //Just WGM10 is in TCCR1A

//WGM12 will be set in TCCR1B
TCCR1B |= _BV(WGM12);

//According to 16-3 , for a non-inverting mode we have to set COM1A1 = 1 and COM1A0 = 0
TCCR1A |= _BV(COM1A1);

//now we have to enable the timer by setting the Clock Source 
//According to 16-6 for a prescaler of 1024 we set CS12 and CS10
TCCR1B |= _BV(CS12) | _BV(CS10);
 
//we want to set a duty cycle of 50\%. Taking in consideration that the counter is an 8-bit one, and will count up to 255, we need to set OCR1A to 0xFF/2

OCR1A = 255 / 2;

Phase Correct PWM mode

The Phase Correct PWM and Phase and Frequency Correct PWM can be activated/controlled by using the dedicated bits in the control registers.

The phase correct PWM mode as described in Datasheet ATmega324 provides a high resolution phase correct PWM waveform generation option. The phase correct PWM mode works on a dual slope method. The counter counts repeatedly from BOTTOM to TOP and then back from TOP to BOTTOM. In non-inverting Compare Output mode, the OCnx is cleared (forced to 0) on the compare match between TCNTn and OCRnx while upcounting, and set (forced to HIGH) on the compare match while downcounting. The dual-slope operation has lower maximum operation frequency than single slope method. Due to symmetry feature of the dual-slope PWM modes, these modes are preferred for motor control applications when using more than one PWM signals.

These two types of PWMs are relevant just when using PWMs on more than one channel and they help reducing interference, glitches, minimizing electromagnetic emissions (EMI) and for other complex systems and electronics. For more details consult 16.9.4 - Phase Correct PWM mode and 16.9.5 Phase and Frequency Correct PWM mode in the (ATmega324 Datasheet). Dead-time PWM control, and other applications can be found and are good examples of why we need phase-correct and frequency correct PWM. 3 Phase Motor control

Reading quadrature encoders using external interrupts (INT0/INT1/INT2)

Quadrature encoders - principles of operation

Encoders are electronic or electro-mechanic devices used to codify the relative movement (rotation) of a shaft. They generate two pulses (A and B) that are shifted 90 degrees apart that codify the speed of the movement and the direction of the movement.

  • The rotation speed of the shaft will be deduced from the frequency of the pulses
  • The number of revolutions will be calculated from the number of pulses
  • The direction of rotation (clockwise or anticlockwise) will be deduced from the order of the pulses.

The encoders are usually characterized by the number of pulses/complete revolution and the type of circuitry for the output signals (PNP, NPN, PUSH-PULL stage).

For example, let's say that we have an encoder with a Push-Pull stage of 5V (it can pull the output to 5V and GND and generate both states - HIGH and LOW) that generates a 4 pulses per complete revolution.

  • We can observe that there are a number of 6 pulses, that means that the rotor has executed 1.5 revolutions (6/4)
  • We can see that the period of signal A is 2s (from rising edge to the next rising edge), thus we can say that a complete revolution will be finished in 8 seconds. So, the speed of rotation is 7.5 (60 seconds /8 seconds per revolution) revolutions/minute
  • We can observe that on a rising edge for signal A, signal B is on a LOW state, meaning that the rotation is in counter-clockwise direction

Another way of explaining the functionality of quadrature encoders is saying that their output is in Grey Code. if A and B are our digital signals they will change one at a time (when A changes, B does not change - on the rising or falling edge of A, B is constant, and when B changes, A is constant). If we consider their inputs we will see that they will be similar to:

  • AB
  • 00
  • 10
  • 11
  • 01
  • 00

By measuring how fast the signals are changing their values, we can measure the speed. Measuring the order of change (eg. from 00 to 10 or from 00 to 01) we can sense the direction.

Example of using external interrupts to read quadrature encoders

For our demonstration we have wired the output signals of the encoder to the pins PD2 and PD3 that can handle external interrupts INT0 and INT1

We would need to implement the following functionality:

  • On rising edge for signal A
  • Verify the state of B. If it is LOW, it's one direction, if it's HIGH, the motor is rotating in the other way

Detecting a rising edge or a falling edge using interrupts can be configured in EICRA using the ISC bits (as described in the datasheet).

In the end, to enable the interrupts don't forget to set the bits for the interrupt you wish to activate in the EIMSK register.

In the Datasheet ATmega324 you can find in Chapter 13 - External interrupts more details and descriptions.

Testing the rising edge can be done through external interrupts or through continuous polling.

Setup

For this lab we will have the following schematic

We can see that we have a full H bridge made with discrete components connected to PD4 and PD5. PD5 will be the pin that generates the PWM and PD4 will set the direction.

On the PWM pin you will see on the right a filter made with R7 and C4 and a voltmeter attached to it. This filter is used to average the voltage.

When we need to change the direction and keep the same absolute speed, we need to change the duty cycle to d' = 1 - d where d' is the new duty cycle, and d is the previous one.

Tasks

Sketch is available here: lab2_0xc2.zip

1. Compile the code sketch in the archive and run it. a. Watch the signals on the oscilloscope (Right click the oscilloscope when the instrument is running and click on Digital Scope). (1p) b. Let the voltage showed by the voltmeter settle and read the voltage displayed. How is this value related to the PWM duty cycle and power rail? (0.5p) c. Open the serial virtual terminal and watch for messages when you press PB2. Analyze the code and see where these messages are sent from (0.5p).

2. Using external interrupts or continuous polling technique, implement the following functionality: When PB2 is pressed change the direction of revolution of the motor and send a message to the serial terminal using UART0 that the direction has been changed.

To change the revolution direction toggle pin PD4

(3p)

3. At this moment the H bridge is controlled through a bit-banging PWM. You will see in the sketch that there are 2 ISR:

  • TIMER1_COMPA_vect sets PD5 to HIGH (when counter is cleared on compare match with OCR1A)
  • TIMER1_COMPB_vect clears PD5 to LOW (when counter reaches OCR1B)

a. Modify TIMER1 config to a 8-bit Fast PWM mode with a frequency between 1kHz and 20kHz (using CS12 CS11 and CS10) (2p) b. Modify the code so that the duty cycle is incremeted by 10\% (the dutycycle is computed as: 100 * OCR1A/255) every 2 seconds (a delay in main loop between increments of OCR1A is enough for that). Incrementing OCR1A with 25 is considered accurate enough to simulate the increase of 10%.

Do not set OCR1A to 255. When the duty cycle would reach more than 100%, reset it to 1%

(1p)

4. At this moment we have motor that can spin in both directions and it has a little bit on inertia in the simulated model. Identify, using external interrupt INT0 ( or continuous polling on digital inputs) on rising edge or using continuous polling (verifying in main loop), what is the direction of revolution and send the information to the virtual terminal. (2p)

pm/lab/lab0xc0-3.txt · Last modified: 2020/03/31 17:01 by constantin.ghilinta
CC Attribution-Share Alike 3.0 Unported
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