Bresenham's algorithm power control arduino. Power regulator for soldering iron on AtMega48 and AtMega8 - Measuring equipment - Tools

The Bresenham algorithm is one of the oldest algorithms in computer graphics. It would seem, how can one apply the algorithm for constructing raster lines when creating a home soldering oven? It turns out that it is possible, and with a very worthy result. Looking ahead, I will say that this algorithm is very well fed to a low-power 8-bit microcontroller. But first things first.

Bresenham's algorithm is an algorithm that determines which points in a two-dimensional raster should be shaded in order to get a close approximation of a straight line between two given points. The essence of the algorithm is that for each column X(see figure) determine which line Y closest to the line, and draw a dot.

Now let's see how such an algorithm will help us when controlling heating elements in an electric furnace.

The heating element is powered by mains voltage 220V/50Hz. Let's take a look at the chart.


When such a voltage is applied in its pure form to the input of the electric heater, we will get 100% heating power at the output. Everything is simple.



What will happen if only a positive half-wave of mains voltage is applied to the input of the heating element? That's right, we get 50% heating output.



If we apply every third half-wave, we will get 33% of the power.

As an example, let's take a 10% output power gradation and a time interval of 100ms, which is equivalent to 10 half-waves of mains voltage. Let's draw a 10x10 grid and imagine that the axis Y this is the output power axis. Let's draw a straight line from 0 to the required power value.

Are you following an addiction?
By increasing the time interval to 1 second, you can get a 1% output power gradation. You will get a 100x100 grid with all the consequences.

And now about the pleasant:
Bresenham's algorithm can be built in a loop in such a way that at each step along the axis X just keep track of the error value which means - the vertical distance between the current value y and exact value y for current x. Whenever we increase x, we increase the error value by the amount of slope. If the error exceeded 0.5, the line got closer to the next y, so we increase y per unit (read - we skip one half-wave of voltage), while reducing the error value by 1.

This approach can easily be reduced to a cyclic integer addition(more on this later, when describing the MK operation algorithm in the next article), which is a definite plus for microcontrollers.

I deliberately did not load you with formulas. The algorithm is elementary, easy to google. I just want to show its applicability in circuitry. To control the load, a typical connection scheme for a MOC3063 triac optocoupler with a zero detector will be used.

There are a number of advantages to this approach.

  • Minimal network interference due to frequent switching heavy load, switching on / off will occur at the moments of voltage transition through zero.
  • A very simple algorithm - all calculations come down to working with integers, which is good for a microcontroller.
  • There is no need to fence the voltage zero crossing detector (hello MOC3063). Even if the MK simply pulls its foot on the timer, opening the optocoupler, the error will not be critical.

To be continued.

The Bresenham algorithm is one of the oldest algorithms in computer graphics. It would seem, how can one apply the algorithm for constructing raster lines when creating a home soldering oven? It turns out that it is possible, and with a very worthy result. Looking ahead, I will say that this algorithm is very well fed to a low-power 8-bit microcontroller. But first things first.

Bresenham's algorithm is an algorithm that determines which points in a two-dimensional raster should be shaded in order to get a close approximation of a straight line between two given points. The essence of the algorithm is that for each column X(see figure) determine which line Y closest to the line, and draw a dot.

Now let's see how such an algorithm will help us when controlling heating elements in an electric furnace.

The heating element is powered by mains voltage 220V/50Hz. Let's take a look at the chart.


When such a voltage is applied in its pure form to the input of the electric heater, we will get 100% heating power at the output. Everything is simple.



What will happen if only a positive half-wave of mains voltage is applied to the input of the heating element? That's right, we get 50% heating output.



If we apply every third half-wave, we will get 33% of the power.

As an example, let's take a 10% output power gradation and a time interval of 100ms, which is equivalent to 10 half-waves of mains voltage. Let's draw a 10x10 grid and imagine that the axis Y this is the output power axis. Let's draw a straight line from 0 to the required power value.

Are you following an addiction?
By increasing the time interval to 1 second, you can get a 1% output power gradation. You will get a 100x100 grid with all the consequences.

And now about the pleasant:
Bresenham's algorithm can be built in a loop in such a way that at each step along the axis X just keep track of the error value which means - the vertical distance between the current value y and exact value y for current x. Whenever we increase x, we increase the error value by the amount of slope. If the error exceeded 0.5, the line got closer to the next y, so we increase y per unit (read - we skip one half-wave of voltage), while reducing the error value by 1.

This approach can easily be reduced to a cyclic integer addition(more on this later, when describing the MK operation algorithm in the next article), which is a definite plus for microcontrollers.

I deliberately did not load you with formulas. The algorithm is elementary, easy to google. I just want to show its applicability in circuitry. To control the load, a typical connection scheme for a MOC3063 triac optocoupler with a zero detector will be used.

There are a number of advantages to this approach.

  • Minimal interference in the network due to frequent switching of a large load, switching on / off will occur at the moments of voltage transition through zero.
  • A very simple algorithm - all calculations come down to working with integers, which is good for a microcontroller.
  • There is no need to fence the voltage zero crossing detector (hello MOC3063). Even if the MK simply pulls its foot on the timer, opening the optocoupler, the error will not be critical.

To be continued.

Thanks to the idea and participation of Yuri Zinchenko (ZenitSoft), a device was developed and built that regulates the power of a kitchen electric stove by skipping periods. It was taken as a basis (see also the block of links in the footer). The developed version is currently working for him, and he is quite satisfied with his work.

After the manufacture of the first version of the device, single failures during operation and a relatively difficult adjustment of the mains voltage zero crossing detector were noticed due to a phase shift when a transition pulse was received.

In the new version, the circuit and program have been redesigned so that accurate zero detection with the highest interrupt priority can be obtained. A phase power control mode has also been added.

Specifications of the electric cooker controller

The triac controller allows you to adjust the power in the active load from zero to 100% in 1% increments. The amount of adjustable power is determined by the type of thyristor and the properties of the cooling radiator.
For quick warm-up, 100% power is supplied for a predetermined time, from zero to 9 minutes
There is a countdown timer for the heating time, from zero to 999 minutes.
It is possible to choose the method of regulation by skipping periods or controlling the duration of a half-cycle (phase method). Allows you to change the control mode during operation.
Remembering all settings in the event of a planned or accidental disconnection of the device from the network.
Device dimensions 125×70 x 62 mm.

Brief description of control modes

Skip periods

Skipping periods allows you to solve the problem of electromagnetic compatibility, since the triac turns on at the moment the mains voltage passes through zero.

It is known that the output power of a device operating on alternating voltage can be adjusted by passing into it not all periods of the mains voltage. If we take a network with a frequency of 50 Hz, then 100 periods pass in 2 s, which means that if we skip, say, 10 periods in 2 s, we will get 10% of the power, and the control accuracy will be 1%. At the same time, it is very desirable that the periods do not go in batches, but would be evenly distributed.
This is achieved using the Bresenham algorithm, which distributes a given percentage of power evenly over time. Moreover, this is achieved by using only integer arithmetic in the program, without division and multiplication, which greatly simplifies and speeds up calculations. Calculations and control according to the Bresenham algorithm are started immediately after the receipt of an external interrupt.
Period Skip Mode is applicable for driving resistive loads, but is not applicable for lighting fixtures as it causes incandescent lamps to flicker.

Phase regulation

An alternative power control method is the phase control method.
To change the power supplied to the load through the triac, phase control can be used. The essence of the method is to unlock the triac on each half-cycle of alternating current with a constant delay relative to the zero crossing point. Thus, a "slice" is cut off from each half-cycle. This will be the so-called pulse-width modulation, which allows you to control the current in (or, less often, the voltage on) the load with maximum efficiency.

The advantage of this method is that the ripple frequency at the load remains equal to the mains. This is important for controlling lighting fixtures, as lowering the frequency can cause flicker to be visible to the eye. But when regulating by this method, a feature of the uneven characteristic of regulation appears.


The direct solution of this equation requires finding the roots of the quadratic equation and calculating the inverse cosine of the resulting root. This is a rather difficult task for the microcontroller, both in time and in terms of resources. Therefore, it turned out to be much simpler to use the method of piecewise linear approximation, without a significant loss of accuracy, which is clearly seen from the graph.


The x-axis shows the value of the installed power in percent, and the y-axis shows the value of the triac opening angle in the values ​​of Π/100. The blue graph is calculated by formulas, and the brown one is created using approximation. As can be seen from the figure, the discrepancies between the real and calculated values ​​are very small.
An unpleasant feature of the phase method is interference that may appear due to a sharp switching of the triac, so it is desirable to use filters at the input.

For both power control methods, it is necessary to know when the mains voltage crosses zero and therefore the main program loop is to monitor the mains voltage zero crossing and feed it to the external interrupt input of the microcontroller as the input with the highest priority.

Scheme and description of the power part of the power regulator


The power unit generates a voltage of + 5V, generates zero-crossing network pulses and contains a load control circuit using a triac.
Mains voltage zero crossing detector taken from the magazine "Radiolotsman". It outputs transition pulses at 10 ms intervals.
Capacitor C6 is charged up to 25 volts - the limiting level of the zener diode D12. The input current is limited by resistor R2. When the rectified input voltage drops below the voltage across capacitor C6, transistor Q3 turns on and generates a pulse with a duration of several hundred microseconds. Optocoupler U2 sharpens the edges and makes the output pulse more square.

+5 Volt source circuit described in detail in the magazine "Radio" No. 11 for 2007, p. 30, in the article "Refining the memory of a cell phone." Added stabilizer on 78L05 to reduce interference and for additional stabilization.
Operation of the circuit: The mains voltage through the resistor R1, which acts as a fuse, is fed to a bridge rectifier on diodes D1-D4 and is smoothed by capacitor C1. Stabilization of the output voltage is carried out by an indirect method. To do this, the voltage from the second winding of the transformer is rectified by the diode D5, smoothed by the capacitor C2, and through the zener diode D6 enters the base of the transistor. To protect the source at the time of connection to the network, as well as during sharp fluctuations in the voltage in the network, current protection Q2 is set on the elements Q1, R7 at the level of 60 ... 70 mA.

Triac connection made according to the scheme from the datasheet for the MOC3052 optosimistor.
When the power block was designed, it was assumed that it would only be used in the skip period mode, so there are no filters in the circuit to protect against interference. To work in the phase regulation mode, it is desirable to add them, at least the simplest LC filter in front of the triac.

Scheme of the control part of the power regulator


NB! On the circuit diagram the values ​​​​of resistors R2 - R6 are incorrectly indicated. The correct rating is 680 ohms.
A common cathode indicator is used.


The control unit circuit turned out to be quite simple. Three control buttons, a 3-digit indicator and two LEDs allow you to control and monitor all device functions.
Block boards are connected by a 4-wire loop.

Software

The program is written in C language for the mikroC for PIC compiler. Comments located in the program contribute to the understanding of its work.
To control operating modes applied control with a single button with counting the number of clicks. The algorithm and part of the code are taken from .
The button can be pressed briefly (several times), long, or different combinations of presses. How many in two seconds we have time to “stumble” is all ours. Next, the procedure for analyzing the collected data will start and put everything in order.
It is no longer necessary to deal with chatter here, since time delays are organized automatically. See article for details.

Interrupts are involved in the program by external input INT, by timer 1 and timer 2.
The INT input receives pulses from the zero crossing detector with a period of 10 ms. Pulses with such a period are used to obtain phase adjustment, and to control the skipping of periods, a period of 20 ms is required, which is obtained programmatically by skipping one of the pulses. Bresenham's algorithm successfully fit into the program of external interrupts.
From the TMR1 timer, we receive 5 ms pulses, which are used for dynamic indication, operation of the "Select" button and counting the system time.
Timer TMR0 is set to about 100 µs and is only used in phase control mode.

EEPROM memory used to save all modes when power is turned off or suddenly lost. Writing to memory occurs after the disappearance of the external interrupt pulses. Restoration of data from memory occurs when the controller is connected to the network. With this use of EEPROM, the number of write operations and the time it takes are dramatically reduced.

Assembly and device device

The device is assembled on two boards interconnected by racks.


The radiator for the triac must have sufficient area for heat dissipation.


The transformer and some parts for the +5 Volt power source are from an old phone charger. Optosimistor U1 can be replaced with an analog, but it should be noted that it must be without zero detector. The boards are interconnected by a 4-wire cable. The printed circuit board for the control unit was not created, but was taken from the previous version. Extra parts were removed from it and the necessary improvements were made. Both boards and the socket for turning on the load are enclosed in a metal and plastic case.

First power-up and operation check

Considering that the power part of the device is galvanically connected to the network, it is advisable to exercise maximum caution or use an isolating transformer when switching on for the first time and checking the signals.
1. Turn on the power section of the device.
2. Check the source voltage +5 Volts at the output of the 78L05 microcircuit.
3. Check for zero crossing pulses - there should be pulses with a period of 10 ms.
4. Connect the board with a cable, connect an incandescent lamp 15 - 100 W as a load and plug it into the network. When turned on, the lamp will light up with full heat and the red LED will also light up. After some time, the red LED goes out and the lamp starts flashing, depending on the power set. If you switch to phase mode, the lamp will burn without blinking, and the brightness will change depending on the installed power. The yellow PWM LED almost completely repeats the lamp glow mode.
5. Check the regulator in all modes of operation, according to the instructions for controlling the device.

Instrument control

Power control mode - one short press of the "Select" button. The indicator shows the power value in percent.
Sleep timer mode - two short presses of the "Select" button. The indicator shows the time remaining until the heating is turned off in minutes. In this mode, the time is counted down in minutes. You can set the timer off time in minutes from 0 to 999. The dot in the last digit flashes when counting down.
Fast heating time setting mode - three short presses of the "Select" button. The indicator shows the time for supplying 100% heating power in minutes and seconds. In this case, the dot in the first digit does not blink.
The mode of changing the adjustment option with a period skip or phase - one long press of the button. The indicator displays the PUL mode - with a skip period or F - phase.

In any of the modes, you can change the values ​​\u200b\u200bwith the "+" and "-" buttons. Pressing the button briefly - adding or decreasing, holding fast iteration. In this case, using the "Select" button, you can switch to any mode and view the parameters of any mode, if you do not press the "+" and "-" buttons.

If it becomes necessary to return to the initial settings, this can be done by holding the "Select" button for about a second while turning on the device.

Since the screen of a cathode ray tube (CRT) bitmap display can be viewed as a matrix of discrete elements (pixels), each of which can be illuminated, it is not possible to directly draw a segment from one point to another. The process of determining the pixels that best approximate a given segment is called rasterization. When combined with the process of progressively rendering an image, it is known as raster scan conversion. For horizontal, vertical and 45° inclined. segments, the choice of raster elements is obvious. For any other orientation, it is more difficult to select the desired pixels, as shown in Fig. 1.

Fig.1.1. Decomposition into a raster of line segments.

The general requirements for algorithms for drawing segments are as follows: The segments must look straight, start and end at given points, the brightness along the segment must be constant and not depend on length and slope, you need to draw quickly.

Constant brightness along the entire segment is achieved only when drawing horizontal, vertical and inclined at an angle of 45 ° straight lines. For all other orientations, rasterization will result in uneven brightness, as shown in Fig. one.

Most line drawing algorithms use a step-by-step algorithm to simplify calculations. Here is an example of such an algorithm:

A simple step by step algorithm

position = start

step = increment

1. if position - end< точность then 4

if position > end then 2

if position< конец then 3

2. position = position - step

3. position = position + step

4. finish

Bresenham's algorithm.

Although Bresenham's algorithm was originally developed for digital plotters, it is equally suitable for use with CRT raster devices. The algorithm selects the optimal raster coordinates to represent the segment. During operation, one of the coordinates - either x or y (depending on the slope) - changes by one. Changing another coordinate (by 0 or 1) depends on the distance between the actual position of the segment and the nearest grid coordinates. We will call such a distance an error.

The algorithm is constructed in such a way that it is required to check only the sign of this error. In Fig. 3.1, this is illustrated for the segment in the first octant, i.e. for a segment with a slope ranging from 0 to 1. From the figure, you can see that if the slope of the segment from the point (0,0) is greater than 1/2, then the intersection with the line x = 1 will be located closer to the line y = 1 than to the straight line y = 0. Therefore, the raster point (1,1) better approximates the course of the segment than the point (1,0). If the slope is less than 1/2, then the opposite is true. for an angle factor of 1/2, there is no preferred choice. In this case, the algorithm selects the point (1,1).

Fig.3.2. Graph of the error in Bresenham's algorithm.

Since it is desirable to check only the sign of the error, it is initially set to -1/2. Thus, if the segment slope is greater than or equal to 1/2, then the error value at the next raster point with coordinates (1,0) can be calculated as

e= e + m

where m- angular coefficient. In our case, with an initial error value of -1/2

e = 1/2 + 3/8 = -1/8

Because e negative, the segment will pass below the middle of the pixel. Therefore, a pixel at the same horizontal level better approximates the position of the segment, so at does not increase. Similarly, we calculate the error

e= -1/8 + 3/8 = 1/4

at the next pixel (2,0). Now e positive, then the segment will pass above the midpoint. The (2,1) raster element with the next largest coordinate at better approximates the position of the segment. Consequently at increases by 1. Before considering the next pixel, it is necessary to correct the error by subtracting 1 from it. We have

e = 1/4 - 1 = -3/4

Note that the intersection of the vertical line x= 2 with a given segment lies 1/4 below the line at= 1. If we move the segment 1/2 down, we get exactly the value -3/4. Continuing the calculation for the next pixel gives

e = -3/4 + 3/8 = -3/8

Because e is negative, then y does not increase. From what has been said, it follows that the error is the interval cut off along the axis at considered segment in each raster element (relative to -1/2).

Here is Bresenham's algorithm for the first octant, i.e. for the case 0 =< y =< x.

Algorithm of Bresenham decomposition into a raster of a segment for the first octant

it is assumed that the ends of the segment (x1,y1) and (x2,y2) do not coincide

Integer- function to convert to integer

x, y, x, y - integers

e - real

variable initialization

Half Pixel Initialization

e \u003d y / x - 1/2

start of the main loop

for i = 1 to x

while (e => 0)

e = e + y/x

The block diagram of the algorithm is shown in Figure 3.3. An example is shown below.

Rice. 3.3. Flowchart of Bresenham's algorithm.

Example 3.1. Bresenham's algorithm.

Consider a segment drawn from the point (0,0) to the point (5,5). Decomposing a segment into a raster using the Bresenham algorithm leads to the following result:

initial settings

e = 1 - 1/2 = 1/2

the results of the step loop

The result is shown in Figure 3.4 and is as expected. Note that the raster point with coordinates (5,5) is not activated. This point can be activated by changing the for-next loop to 0 to x. The activation of the point (0,0) can be eliminated by placing the Plot statement immediately before the row next i.

Rice. 3.4. The result of Bresenham's algorithm in the first octant.

AT next section the general Bresenham algorithm is described.