How to rotate an image in C#

  1. Calculate SIN and COS once
  2. Apply these in a formula to all pixels
  3. Do this in reverse to avoid gaps in the final image

Rotation-matrix

To rotate a pixel around an axis, we need to do some sinus and co-sinus calculation to it because, in short, rotation follows a circular path.

The good part is that the sinus and co-sinus part of the calculation remains the same for every pixel, because they all rotate the same amount.

The next code sets up the values needed later in the main loop. And C#’s math functions want to see Radians, not degrees.

double rotationRadians = userRotate * (Math.PI / 180);

float sin = (float) Math.Cos(rotationRadians);
float cos = (float) Math.Sin(rotationRadians);

In reverse

If we where to go over every pixel in the original image and calculate it’s new position, then there would be gaps in the destination image.

Therefore, we go over every pixel in the destination image, and calculate back where its original position is, that way we always have a pixel color when within the image’s border.

for (x=rectangleLeft; x<rectangleRight; x++)
{
    for (y=rectangleTop; y<rectangleBottom; y++)
    {
        // Rotate
        xx = x * cos - y * sin;
        yy = x * sin + y * cos;

        // Check if we are within the original image
        if (xx > 0 && xx < imageWidth && yy>0 && yy < imageHeight)
        {
	    c = lockBitmap.GetPixel((int) xx, (int) yy);
	    c.A = 255;
	    destination.SetPixel(x, y, c);
        }
        else
        {
	    destination.SetPixel(x, y, MyColor.Black);
        }
    }
}

As you can see in the code, we loop over every pixel, apply the same sin and co-sinus values to it and end up with a source pixel-coordinate xx and yy.

Then we get the color of the pixel or assign a background color if not within the bounds of the original.

An image rotated with C# using a rotation matrix. Resulting image has no gaps.

Explaining op-amps and comparators

They both compare two input voltages and drive their output high or low depending on which voltage is higher. An op-amp however also has a third mode when voltages are equal, holding the voltage level.

Comparators compare input voltages

Short explanation; if the positive input voltage is greater than the negative, the output goes high, otherwise low.

The two images above show the two states a comparator can be in, either drive the output high, or low, depending on the which of the input voltages is higher.

Op-amps can deal with equal inputs

If we feed the output to the negative input, it will follow the positive input

Consider the circuit above, when the op-amp starts, its output is at 0V, and because the negative input is connected to the output, the negative input is also at 0V.

Now the op-amps does what its made for, positive input is greater than the negative, so drive the output to high. I put a graph next to the circuit to show you the output voltage.

As soon as the output voltage hits the +2V level, both inputs are in balance, and so the output voltage holds at that level. If the positive input would change, the output would again follow it. This is a voltage-follower.

How to scale any voltage into the analogRead range of your microcontroller

You want to measure a voltage? But it’s outside the range of your microcontroller’s 0 to 3.3v or 5v? We can achieve this with resistors.

There are three distinct problems, each with its own solution.

Table of Contents

The positive voltage is above 3.3v or 5v

If we apply double our maximum voltage over two identical resistors in series, we expect to measure half our voltage at the midpoint. It is this midpoint we are going to measure.

Simple resistor divider, voltage at midpoint if half the voltage at the top
Simulation of the voltages in a resistor network, all the voltages are evenly scaled

The voltage at the top can be calculated by multiplying the analog-read-voltage by 2. In this example I will assume a 5V microcontroller.

If we add another identical resistor, we add another 5V to the maximum voltage we can read, we can extend this as many times as we like.

With three identical resistors, we can now measure three times the maximum voltage of our microcontroller

We do only intend to measure after the first resistor, and then multiply the measured voltage by three to get the correct voltage. This means we can group the other resistors together by adding them up.

Final solution, measure three times the voltage on your analogRead pin

The voltage is below ground/negative

If we want to measure below ground, we have to set this resistor network upside down. This example assumes a 3.3V microcontroller.

Reading a negative voltage can be done with an up-side-down resistor network

Instead of connecting the bottom end to the ground, we now connect the top to the maximum of our controller. And it is now after the top resistor where we read our voltage.

Once again, we simplify the network to only use two resistors by adding them up.

Final solution for reading a negative voltage on a microcontroller

Calculating the actual voltage is not that complicated. First we multiply the voltage on the analog input by three and then add the lowest voltage we can read on the network, which is -6.6V. On the positive network we did not do this because that value was 0V.

So if we read +3.3V the actual value = (3.3 x 3) – 6.6 = +3.3V.

And if we read 0V the actual value = (0 x 3) – 6.6 = – 6.6V.

Both voltages are out of range

When the input can be below ground as well as above the controller’s maximum, we can’t tie one end of the network to ground or max-voltage. We need to tie it in the middle, using another resistor divider. This example assumes a 5V controller.

Using a three way resistor divider network, we can measure positive and negative voltages

The standing resistors on the left are equal, and without any voltage to measure would produce +2.5V at the middle for the analog pin to read.

The to-measure-voltage applied to the right will then pull that voltage up or down through the third resistor.

Then how to calculate that third resistor? And how to translate the value read at the analog pin back to the real world value? I could not figure this out in a simple way so I wrote a tool for the Windows platform to do this for me.

A resistor network solver

This tool gives you the resistor values you need and a map function to translate the value back to real-world-voltage. At the right side you can see the simulation results.

The resistor values are very high, to use as little power as possible, but you can lower them as long as you divide all of them with the same value.

Download link to the tool

How to drive a relay from a digital pin, two solutions

The first is by using an NPN-transistor, and the second a N-channel-MOSFET. Both circuits are pretty much the same otherwise.

NPN transistor

Using a transistor is the cheapest and fail proof way of doing this. Setting a output pin high on your CPU sends a resistor limited current to the base of the transistor.

A multiple of that current is allowed through through the transistor and therefore the relay-coil, powered from the same voltage source as the CPU, but not through it.

Use a NPN transistor to drive a relay from the low side with little current going though the IO pin

N-Channel MOSFET

We can use a N-channel MOSFET as a bottom-side-switch. But not all MOSFETs are created equal. A lot of them do not even switch on partially with only 3.3v on their gate.

According to the datasheet, the FB4410Z from IRF (which I have) can supply more than 1 amp with only 3.3v on its gate.

Use a proper mosfet to switch a relay from the low side

Can’t do this without a diode

A voltage spike would kill our MOSFET or transistor. When we turn the relay of the coil remains charged, because it also is an inductor, it will produce a spike on the bottom side.

The diode provides a path back into the coil. The voltage drop over the diode will bleed of the excess energy.

Prototype

With the help of a NPN transistor, a digital pin from a Raspberry Pi can drive a relay

Conclusion

With the help of a transistor or MOSFET, we are now free to drive any relay we want directly from a digital IO pin. We can even switch some really big relays capable of 80 amps or more.

Big-boy-relay

Home Energy Automation: Save money on electricity

With price-aware-switches you can use power when its cheapest. Like charge your car at night if you have flexible rates or night tariff, for example.

Charging your car at cheaper times can save money

A power-limiter on the other hand, can keep the electricity meter still for most of the day, if you have batteries or solar panels.

You need options, lots of them

Because no electric situation is the same, I am developing a range of generic solutions, both hard- and software, so you can create your own personal solution with them.

Open source and highly serviceable

With proper documentation, you can do your own installation, if you feel like it. And with that same documentation, and a well designed circuit board, most people will also be able to repair these devices themselves.

Current status: prototyping

I have two working prototypes with schematics and software. So if you like, you can start building yourselves. Otherwise you will have to wait for the finished product.

Examples

[link]

Devices

[link]

How to create a power limiter to get zero-on-the-meter to save taxes

If you are one of the many people exporting electricity to the grid, chances are you are familiar with the following…

When you export electricity you also get to pay energy taxes and or other grid fees. So even if your net-consumption is zero, you still own taxes. This might not be the case in your country or your specific utilities provider, but it will be the future for most of us.

With solar you are either importing or exporting power

The graph above is a simplification of typical grid usage for a solar house over the course of 24 hours. At night we consume power from the grid, and at daytime we are exporting. Either way there is power crossing the meter which can potentially cost us money as taxes.

Continue reading “How to create a power limiter to get zero-on-the-meter to save taxes”

How to create a smart switch for an electric boiler to save money

My electric water heater consumes a lot of electricity, and it does so at times when it is most expensive. This is because I have dynamic prices which change every hour and I shower at an expensive time. And even if a had a high&low tariff, the problem would still exist.

Most people shower at an expensive moment!

There is more than one way to solve this problem, and I prefer one that is technological in nature.

Continue reading “How to create a smart switch for an electric boiler to save money”

Welcome to Energy automation

Hi there and welcome to my site. I am developing a range of products to help with steering electricity consumption in your home.

At present time (Nov 2022) I have a lot of the software done and are already implementing systems into my house, like the smart switch for my electric water heater and car. They only switch on when electricity prices are low.

A smart electricity steering system for my own house

At the picture above you can see how I intend to use computers and hardware switches to steer electricity around.

Right now I am working on a programmable buck boost converter. This will control the charging of the batteries and releasing of energy to the grid when needed.

Prototype of the programmable buck-boost converter is being assembled

Goals

There are a couple of goals I want to keep in sight.

  • Use electricity when it is cheap
  • Zero grid consumption
  • Serviceable
  • Open source

Use electricity when it is cheap

With solar and wind power getting a bigger share of energy production, I can image a growing part of energy consumption being charged by the hour. I myself have such an energy contract called dynamic prices.

Every day I can see the prices for tomorrows 24 hours

This means, that if you switch off your heavy electricity consumers in your house at expensive time, your money savings can be in the 10s of percents.

Zero grid consumption

In my own country (and most others) we love to tax everything. If I produce 100 kWh of power and consume 100 kWh, then I have to pay for 0 kWh and get taxed for 200 kWh. Might not be 100% accurate but we are heading in that direction fast.

With the use of batteries and smart switching, we can keep the meter at near zero net consumption most of the time. Allowing us to keep a lot of tax money that where otherwise lost.

Serviceable

These devices will using through hole components and circuit boards with some room to work with so that most people should be able to repair these devices themselves.

Open source

I realize that most energy situations are unique, everyone should therefore be able to customize the workings to suit their own needs.