Tuesday, August 30, 2011

Coding Lessons: C and more variables (lesson 3)

So far we've covered that there is a way to print stuff to the screen.
And that you can set up variables, and that there are different types of variable for different types of data. We declared a variable, gave it a value, and wrote that value to the screen.

But so far we only dealt with 1 data type, (because I didn't want to make the lessons too long).

We know how to declare lots of data types, now lets look at using a few more data types

Start
As before set up your workspace (create a new folder d:\coding\lesson3) and open your editor.

Just as before add any comments that you like, and put that header file in that'll let us deal with outputting data to the screen

#include <stdio.h>

And start your main function

int main()
{

This time I'm not going to declare the variables, of course you can if you want to, but what I'm going to do this time is use the variable place holders in the printf statement, then assign them hard coded values at the end.

Now, lets look at characters, (ones that you'd assign to the char variable type).
printf ("looking at characters: %c %c \n\r", 'a', 98);

there are going to be two characters printed on that line (there are two %c's) looking at the end, you can see that one of those characters is going to be a, and the other is going to be 97?

97 isn't a character!, but it is a place on an ASCII Character map!

If you look up the ASCII character values you'll see that this corresponds to the letter b.

the first 127 characters I'd pretty much agree, there is not a lot of point in printing them, but the extended ASCII, that's where it gets more interesting, these don't appear on the keyboard, but you can use them by just writing the number value.

http://www.asciitable.com/

The other thing that was introduced there was \n (new line) and \r (carriage return), and that's because if we just have two statements;
printf("some text");
printf("some more text");
They will appear on the same line as "some textsome more text"

now let's look at some integers (like we used in the first example).

printf ("integers: %d %ld\n\r", 1234, 650890L);
What we've done there is looked at a %d, (signed integer), and also looked at a much bigger number using a long integer %ld, you'll see that at the end of the large number there is a big L that specifies that it's a long.

So we're really getting into the hang of things now!

So let's look at some special formatting,
Say I'm writing a table, and I need to preserve the formatting, it should be easy right, I can just use spaces to pad out the cells of my output? (but how do I know how many spaces to put?) the variable changes? how do I know I'll need 8 blank spaces, what if I need 9, or 7?

Well, there is a way to tell the printf statement to print out that integer, and pad the space with blank spaces.

printf ("Padding with blanks: %10d \n\r", 123);
that 10 in front of the d in the %d place holder tells the program that that data takes up ten spaces. (so seven blank spaces are put into the front of the number 123)

If I wanted data to be displayed in a set number of characters, i could just as easily pad out the blank space with zeros instead I'd do that like this:

printf ("Padding with zeros: %010d \n\r", 1234);

I said at the start that these lessons would be geared towards programming micro controllers, what if I want to get a number to or from the chip, that number is a representation of 8 bits, I don't write 0111 1111 for off on on on on on on on whichis what I want my 8 output pins to read. I want to represent that in as simpler way as possible in my code, I want to use hex. where I can just write 7f, which is a little easier than working back to the base ten number of 127.

printf ("Using different bases: Decimal %d unsigned hex %x unsigned Octal %o formatted Hex %#x Formatted Octal %#o \n\r", 127, 127, 127, 127, 127);

But now what about floating point numbers, dealing with floats is pretty important, just about everything in this world can be expressed as a floating point number.
if I say to you that my chip measures the temperature of 0x4f it means nothing. but if there is the correct maths on my chip to write 23.5 degrees now that's much better!

printf ("floating point numbers: %10.5f %010.5f %2.2f %E \n\r", 23.517, 23.517, 23.517, 3344.1416);

I'm re-using a couple of the tricks from above. the first one %10.5f basically says, take up ten character spaces, use blank space at the start, have five places after the decimal point.

So 23.517 is displayed as [space][space][space]23.51700

The next example uses the same trick to write zeros instead of blank spaces (%010.5f)
so 23.517 appear as 00023.51700

The next is quite useful, I'm not adding any place holders, or extra information, I'm restricting the accuracy.
%2.2f means 2 places before the decimal place, 2 places afterwards.
so 23.517 gets neatly trimmed to 23.51, I gave the example earlier of a temperature probe, you probably don't need to worry about the thousandth of a degree!

And %E means display in scientific format.
so 3344.1416 becomes 3.3441416 x10(3)

That's floats pretty much covered, so lets move on.

I said earlier about setting the width of text by padding with zeros or blank spaces,
but, there is another way.
printf ("setting the width: %*d \n\r", 5, 14);

If you put a star after the % sign, you can then specify the width before the value.

And last but not least, because I know that you'll want to work with strings of characters so that you can send messages!

printf ("%s \n\r", "A silly message goes here");

%s is the place holder for strings, strings can contain numbers, (as in you can write)
printf("%s \n\r", "123");
But you cannot perform maths functions on strings!


Put it all together
The complete example is here:

#include<stdio.h>

int main()
{
printf ("looking at characters: %c %c \n\r", 'a', 98);

printf ("integers: %d %ld\n\r", 1234, 650890L);

printf ("Padding with blanks: %10d \n\r", 123);

printf ("Padding with zeros: %010d \n\r", 1234);

printf ("Using different bases: Dec %d unsigned hex %x unsigned Octal %o formatted Hex %#x Formatted Octal %#o \n\r", 127, 127, 127, 127, 127);

printf ("floating point numbers: %10.5f %010.5f %2.2f %E \n\r", 23.517, 123.517, 23.517, 3344.1416);

printf ("setting the width: %*d \n\r", 5, 14);

printf ("%s \n\r", "A silly message goes here");

}


so you need to save that in D:\coding\lesson3\
as variables.c

then navigate to that directory and type "tcc variables.c" hit return,

Thursday, August 25, 2011

Insulating Jacket for water storage tank.

We're having a nice hot summer, so I'll admit that I did this a while ago, but have only just gotten around to posting it.

It's all this comparing water to electricity that's made me remember this.

The trouble was this,
I live in a shared house, and something was a little wrong with our gas bill.

It seems a bit weird to say that really. the problem went unchecked for quite a while, because being a rented house we had this knackered old boiler (that one day was found to be unsafe and replaced by a new boiler).

But our gas utility bills still stayed really high, this was in January, and it's been snowing, so we'd been inside the house a lot, and had our heating on a fair bit, we'd had hot water that filled up our hot water tank, and the water was set to always be hot.
For January our gas bill came in at £260 for the month.
The fact that there are 4 adults in my house made this bill manageable, but it was not comfortable to be spending that much on utilities especially since the house was always freezing!

That bill was a bit of a wake up call. Honestly, we'd known that the house was full of drafts, (you only had to stand a few feet away from a door to feel the cold air), but being as it was a rented house we didn't really want to be the ones to pay for fitting draft excluders, but that month we realised that we were actually paying more for not fitting draft exclusion strips around the doors.

Solving the problem
So we made a quick trip to the shops, we bought several packs of the very thin brush strips that have self adhesive backing and go round the doors.
These were applied to the frame of the exterior (outside doors) and the next door in from those, (so the strip was applied to the back door that leads into the kitchen, and around the kitchen door that leads into the rest of the house.

We also bought draft excluder brushes to go at the bottom of the doors, we attached these to the front and back (exterior) doors, and the effect was immediate!
Not only did the house feel warmer straight away, but by the time we got a bill for February we'd saved over £100 on our gas bill.

Still, something wasn't quite right though.
Through march the weather actually got warmer so we were able to run the heating off completely, and still our gas bill didn't really change. we'd assumed that because our radiators were pretty old and knackered, that we were running a boiler really hard to try to heat the house and that's what was taking up all the gas and costing us loads each month.

So next we looked up at the hot water tank.
In our bid to reduce energy we'd decided that we didn't need hot water 24x7, we just needed hot water in the morning and evening to shower and to clean dishes etc. so we used the timer on the boiler to tell it to heat the water twice a day.

We were noticing that when the water was set to come on though (when the water in the tank dropped below a certain temperature, and at 4 in the afternoon) that it was always coming on, and the cupboard that the tank was in was always very hot.

It was soon clear that the problem here was that the tank wasn't very well insulated at all.

The Tank
The tank was an old copper tank, that when bought did not have any insulation at all, (unlike modern tanks that are covered in expanded foam) someone had once upon a time tried to insulate the tank a little, wrapping some small red fibreglass filled pads around it and tying them on with string.
The trouble with these were that the fibreglass was only about an inch thick, and the largest pad was 1' x 2' so this patchwork of pads was terribly inefficient.

Another trip to the DIY store and we came home with a large roll of loft insulation, these rolls are about 4ft tall, and 15ft long, the cost of the roll was about £5.

It's not strictly just fibreglass, it's a fibreglass/sheep wool mix.


We unrolled the insulation, (don't be fooled by it's tight packaging when you unravel it it expands and is about 4 - 6" thick!) after unrolling the insulation we placed am old double duvet cover on top and cut to the size of the duvet cover.

Then we put the fibre glass insulation into the duvet cover and wrapped it round the tank, and tied it in place, the very top of the tank was capped off using the little red pads that has previously covered the entire tank.



Sadly, I don't have a before photo (and I'm not going to rip out all that work to get one!
What I do have though is before and after bills.

January - £260
February - £145 (this is the insulation improvements, the weather was still cold and nothing else changed.)
March - £90 (the weather improved and the heating went off leaving only hot water.)
April - £30 (the water tank insulation really made a difference.)

Now we didn't ask the landlords permission to make these changes, not even for the draft excluder strips that are screwed to the door. You may like to do that, we took that rather more risky approach of saying, when you rent a house you're always meant to leave it in the same or better condition as when you moved in, and we've drastically improved this house.

To be honest we're feeling a little stupid that we didn't do this a lot earlier now!
we're burning less gas, we're spending less money, and we're just as warm, if not more warm and comfortable in our house now than we were before.

And all of this took just two trips to the DIY store (though that could have been 1)

Cost

old duvet cover - free
Insulation £5
draft excluder stips (frame ones) x4 £20
draft excluder brushes x2 £10

£35, seriously that's all £35 and an evenings work to fit everything. and we saved far more than that in the first month before we'd even finished the job.

Tuesday, August 23, 2011

Electronics Lessons: The Resistor Standard Values -The E12 Values

In the transistor amplifier lesson I introduced a new concept without talking about it too much. I kind of just shoved it in there and assumed that you'd get to know what I was talking about.

If you found it confusing or didn't have the foggiest what I was talking about, then read on.

Standard Values
Standardising the values allows manufacturers to make a handful of components, in bulk quantities, therefore keeping costs down.

Can you imagine the size of the hobby section in electronics shops if every component value imaginable was actually made? 1oh, 2 ohm, 3 ohm, etc or 1 and 1.1 and 1.2 and 1.3 and 1.4ohms all the way up to millions of ohms?

Instead of making every size imaginable, the manufacturers use standard values instead.

This values are spaced in the same kind of range of values as notes on a piano, (white and black).
in an Octave, there are 7 white keys and 5 black keys.
C, C#, D, D#, E, F, F#, G, G#, A, A#, B then we get back to C
Those notes are all equally spaced apart and the gap between then is called a semitone.

Standard resistor values have the same sort of spacing, the spacing between them is 10^(1/12)
(or ~1.212). (there are, just like on a piano, 12 values in a range, and the ratio of the spacing of these is equal.)

This is why it's called the E12 series (there are 12 values in the series)

The values
This makes values that start a 1,
then (multiply by 1.2 = 1.2), x1.2 = ~1.5

Therefore the actual values are

1, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2 and 10 (the ten is the start of the next range, kinda like how that C was the start of the next scale on the piano.)

Designing
Of course this is a bit of a trouble, when we're designing circuits we often come up with values where there just isn't a standard value.

In the amplifier lab none of the values were standard! all had to have a closest fit.

However, when you look at the range of values, it's not all that bad...

Margins of error/Tolerance
If you look at the values, they are all equally spaced, with not more than 20% between the values.

The gap between 5.6 and 6.8 is 1.2Ohms, so lets hit exactly in the middle, and say that you need a 6.2Ohm resistor.

If you go for a 6.8Ohm, resistor you're 0.6Ohms over,
If you go for a 5.6Ohm resistor you're 0.6Ohms under.

In short, whichever way (up or down) you go, you're only ever going to be 10% or less out of what you want the value to actually be.

I suppose you could say that 10% is a large percentage and does makes a difference.
You would of course be right to say that.

But consider two things, firstly, your designs, are mathematical models, not measured values,
And that even the values on the data sheet, though they are measured values, they are measured from a sample, not the component that you have in front of you, -hence data sheets provide minimum, typical and maximum values, measured from a range of samples.

Whether you chose a higher or lower value depends what you're working with, if you're getting close to the absolute maximum values of current, then choosing a lower value, and possibly exceeding that absolute maximum would not be a good idea. However, if you're well within the absolute maximum, then choosing a slightly lower value of resistor isn't going to cause too much current to flow, nothing is going to fail or melt!

Also, you should remember that if you desperately need an exact non standard value, you can add resistances together.
if you need exactly 45Ohms, no more no less then instead of settling for 47 ohms, use a 12 ohm and 33 ohm resistor in series!

Also remember that on resistors there is a tolerance band.
If you're using a silver tolerance band then your components may be as much as 10% out of their marked values anyway!

Thursday, August 18, 2011

Electronics Lessons: The Transistor Simple Circuits 2 (Lab 3)

Now that we've looked at resistors, transistors, and capacitors. Lets see if we can put them to some use to build another really simple circuit, this will be a bit more complicated than using the transistor as a switch.

Lets start by build an amplifier;

I don't expect that you know how to design the amplifier yourself (that's why you're here?), so I'll hold your hand all the way through the design process, we'll be using at least one of the components in a way that I haven't described that it could be used like that yet, so there will be a little deviation to describe that, but hey, this is only lab3 and you're already building something pretty cool... you know the components from the past 5 lessons, and you're aware of one of the building blocks that we'll be using from a past lab lesson (lab 1).

Perhaps the holly grail of all analogue circuits is the amplifier, I don't know why if I'm honest, but just about everyone seems to want to know how to make amplifiers, and those that do know how to make amplifiers, well, in spite of the maths involved seem to get a kick out of making them, and even those that shy away from the maths have a really good go following reference circuits.

This is the first amplifier circuit I was ever introduced to:

Common Emitter Amplifier
The last amplifier that we looked at was an emitter follower or common collector amplifier, that's a device that amplifies current, whilst leaving voltage unchanged, we used that to boost the amount of current available from a low power source so that we could turn on a light.

The amplifier that we'll be looking at now doesn't amplify current, it amplifies voltage.
The first thing to do is introduce you to the circuit.



Firstly, lets break the circuit down,
The little round thing with the waveform shape in it is a signal source,

For this demonstration we'll set the output of the generator to a sine wave, with a frequency of 1KHz and we'll set the amplitude (size of the signal) to 1v.

This means that the waveform outputted by this generator is:
A nice curvy wave form, that is modelled by the math function sin(x).
It goes between +1v and -1v.
And it does this one thousand times a second (a complete cycle take 1millisecond -1ms.)

The next component we see is a capacitor, in the lesson on capacitors I talked about the capacitor acting like a storage tank for electricity, saying that you could charge a capacitor and discharge a capacitor, here we are using a different property of the capacitor, it's ability to block DC (direct current) signals, and allow AC (alternating current) to pass.

The reason that we want to use this is because we need to set a bias on the transistor so that it's working in a linear region, -don't worry about that for now, I'll explain more later, right now we'll look at the DC blocking capabilities of the capacitor.

When we use a capacitor like this it's called a coupling capacitor.

Coupling capacitors
The problem with the signal source that we have is that it's waveform is centred around 0volts.
fair enough the transistor will turn on then the voltage rises above zero volts, but when it's in it's negative half of the cycle (or anywhere in the cut-off region), the transistor won't be conducting at all. So we need to move the centreline of the wave form up so that it's centred around a positive voltage, that'll let our transistor work in a region where it's on a little right up to on a lot, (remember how we talked about the transistor as a variable switch? now we're going to use it as a variable switch.)

Before we introduce the transistor into the mix we'll look at how we get that wave form to climb up to a more positive voltage using coupling capacitors.

The diagram below shows some things that should be familiar to you from lab 1.


Ignore the capacitors and signal generator for now.
There is a positive voltage source (+9v) and a zero voltage source (0v) (just like the battery terminals.) And there are two resistors set up as a potential divider, followed by two more resistors set up as potential dividers.

Using the maths learned in Lab 1 we can see that the voltage at the blue probe is 6v, and the voltage at the pink probe will be 3v. -remember Vout = (Z2/(Z1+Z2)) * Vin)?

So we know that there is a DC voltage of 6v at the blue probe, and a DC voltage of 3v at the pink probe.

(now we'll include the capacitors and signal source again).

The resistors used are significantly high enough to not interfere with the source when the AC signal is introduced.

Reading from left to right.
The first red probe, measures voltage a +/-1v centred around 0v.

The capacitor then blocks any DC voltage going to, or from that point in the circuit moving onto the next point, (blue probe).

If there were no DC component here we'd measure +/- 1v centred around 0v, however, the potential divider here means that there is a 6v DC voltage at this point, so that +/-1v is superimposed on this 6v source. meaning that the wave form is now alternating between +7v and +5v (+/-1v centred around 6v).

Moving a little further on there is another capacitor that stops this +6v DC component from moving to or from any other part of the circuit. Here we reach the pink probe.

Now the wave form has had all it's DC component removed and is once again 0v +/-1v.
but our potential divider has set a DC voltage of 3v onto this part of the circuit. So once again the AC voltage is superimposed on the DC voltage giving a wave form that's +/- 1v centred around 3v (+4v to +2v).

Here is what the wave forms are looking like at each part of the circuit.


Biasing
I suppose that the first question that needs to be answered is Why do we bias amplifiers. I gave a pretty poor description above about the fact that it doesn't turn on on the negative half cycle of the input wave, (and that is true).
but to answer the question properly again we're going to need to look at the data sheets for the component again.

Lets take a really simple (and now really rather old transistor, the BC108).

http://www.datasheetcatalog.org/datasheet/MicroElectronics/mXuvuyv.pdf

As before there are a couple of important things to look at in the data sheet.

The first is Base - Emitter voltage (Vbe) you can see that this is 0.6v


Next look at the gain value of the transistor, (this is called hfe) this is (for group A components typically 170).
this large hfe value means that we know that the collector current is much much larger than the base current.

so Vbe = 0.6
Gain = large
Ic >> Ib
Ie = Ic + Ib

You'll find a graph in that data sheet called "output characteristics",
The output characteristics these define the voltages that you need across the device to make it work in a region called the linear region, this is the region where the device is going to amplify small and large signals equally without distorting either.
There are several lines on the device, all are in a shape that goes up at the start, and has a sharp knee, then settle into a straight line, the different line correspond to different base currents.


On the graph below I've marked two areas in red, you want to stay out of these regions because either the transistor is off or behaving in a non linear way (very on), (the one closest to the X axis is the cut off region) and the one closest to the Y axis is the saturation region.



The first thing that you're going to need to determine is the Resistor RL, this is the load resistor for the amplifier,

First, you're going to need to extend the graph so that we can see it working inside the voltages that you're working with, (the x axis only goes up to 5v, and we're going to use a 12volt supply).
(I'll assume by now that you've murdered an ATX power supply and therefore have a 12v supply (and are no longer relying on 9v batteries).



Now you need to draw line on the graph between the point the you want to set as ICmax, (on the Y axis, and your supply voltage (Vcc) on the X axis.

Set your ICmax somewhere below the highest marking on the chart, I've chosen 1.75mA



This new red line is called the DC load line, and in the middle of this line is a point that's at the middle of the linear operating region of the amplifier, this is the quiescent point, or Q point.



You can see the green dot in the middle, set at around 5.8v (you might also be realising that this is not an exact science!)

Right... so what we know now is:

Ic(max) = 1.75mA
and Vcc = 12
Vce(q) = 5.8
Ic(q) = 0.9mA

We need to make a decision now as to what we want the voltage of our emitter to sit at, some guides suggest splitting the voltage equally between the Rc, Rb and the transistor itself, however, I think that setting Vre as 1v doesn't seem like a terribly bad thing to do! -you could chose a different value.

To find a value for Rc
We use the forumla

Ic(max) = (Vcc - Vre)/Rl

0.00175 = (12 - 1)/Rl

Which works through to give us the equation
Rl = 11/0.00175 = 6285
The closest standard value is 5.6K or 6.8K

It'll be perfectly fine to use a 5.6K this will increase your IC(max) value, but you're still far below the absolute maximum rating given on the first page of the data sheet. the higher the voltage here the more restrictive you're being on the input signal voltages that could be used before the amplifier clips the signal.



The current gain of the transistor we know from the data sheet is 170

the gain is the value of the collector current, over the base current

hfe = Ic /Ib

hfe = 170 and Ic = 1.75mA
Therefore Ib = 1.75ma / 170 = 10uA


Given that we now know the values of Vre, Vbe and Ib we can start to set the bias of the base leg of the transistor.

To find the value of R2 we use the following formula.

R2 = (Vre + Vbe)/(10 * Ib)

R2 = (1 + 0.6)/10 * 0.00001)
R2 = 1.6/100 * 100^-6 = 16000 -15k is the closest standard value

and we can also figure out the value for R1

R1 = (Vcc -(Vre + Vbe))/(11*Ib)
R1 = (12 - 1.7)/(11*0.00001)
R1 = 10.3/0.00011 = 93636 - 100k is the closest value


Now we need to go about setting that emitter resistor Re.
We calculate this using Ohms law
We know that the emitter current is the sum of the base and collector current
Ie = Ic + Ib
Ie = 1.75ma + 10uA
Ie = 1.76mA

We know that Ohms law says V/I = R

Vre / Ie = Re
1 / 1.76mA
1/0.00176 = 568 Ohms (and the closest standard value is 560Ohms)



Earlier we talked about coupling capacitors,
on that last amp circuit you'll see red and blue probes, this is what the signal looks like at those points.



Input vs. Output
Finally, let's move our probes to measure the input and output signals.




Look closely at that chart.

The red line is the input signal, and the blue line is the output. We see that the blue line is much bigger than the red line, but also notice that as the red line is going up, the blue line is going down.
This amplifier has switched this signal upside down.

This type of amplifier is called an inverting amplifier.

Gain
The gain of am amplifier is its output divided by its input.

remember the current gain of the transistor was the collector current, over the base current.
(actually it's emitter current over the base current, but since the gain factor is so large we assume that Ie is just about equal to Ic)

The voltage gain works the same.
The input voltage is +/-1v, (e.g 2v).
and the output voltage swing is +/- 4v (eg 8v)

So the gain of this amplifier is 8/2 = 4

The signal coming in is made 4 times larger.

Tuesday, August 16, 2011

Logic Level Indicator

To breakup the lessons a little bit more I'm going to publish a write up of a tool that I made whilst I was at university.

When I was at university we used to program Motorola 68HC11s in either Assembly or C. The development boards that we used in class had 4mm connectors on them allowing us to connect boxes containing switches, or lights, or DACs to the chips using simple instrument leads with 4mm plugs on them.

So I made my own logic output board,
The board consists of 16 inputs, and 16 LEDs, to help identify there, these are coded red and green.

The board is powered by a five volt supply, and has an LED to signify that voltage is present, and a Zener diode to help make sure that the supply voltage does not exceed 5V.

In general you cannot rely on a digital output to have enough current to power an LED.

So I'm using a chip output to turn on a transistor, that transistor is then arranged as an emitter follower, that amplifies the current output from the chip, and provides enough current to light the LED.

How and why this circuit works is covered in the entry immediately prior to this.



The circuit is that simple circuit, and it's repeated 16 times


At the bottom of the board there are two ten pin connector, these are 8 logic inputs, and a + 5V supply rail, and a 0v rail.

So I can attach my PSU to this logic indicator board (using the voltage inputs and 4mm plugs), and use the board to power my circuit, with nothing more than a simple ribbon cable carrying the supply and signals.

Here are some more pictures of the board, with a probe attached to one of the inputs, and showing a voltage applied to the pin inputs also.

The board powered up:


Logic high applied to an input:


And showing the pin inputs:



so the complete schematic is as follows, this is only one side, but just repeat on the other side.



Whether you decide to put a 5v zener diode across the supply, or an LED to indicate that the device is on, is up to you.

The actual connectors are attached to the board by a loop or wire attached, and soldered into the board, then to hold them a little more securely they are also hot glued to the board.

Thursday, August 11, 2011

Electronics Lessons: The Transistor Simple Circuits (Lab 2)

So in the last lesson I talked about the transistor, I talked about how you could turn the transistor on to a fully conducting state.

I also mentioned that transistors could be used as current amplifiers.

You'll use a current amplifier when you need a little more power to switch on an output than that output can supply.

We discussed before how the transistor was off, and how it could be turned on.

So, lets make a device that puts a light on with the presence of a voltage, even if that voltage source doesn't have the power (current sourcing capability) to light up the light itself.

In this tutorial we're interested in two areas of the transistors output, because we're going to use the transistor as a switch we'll either have the transistor in the cut-off region (off), or the saturation region (on) of it's output characteristics. (There are the areas marked in red in the chart below).



The Circuit
What we do is connect the input to the base of the transistor, we use a resistor to ensure that not too much current is pulled from the voltage source that we're detecting.

We'll also put a resistor between the circuit voltage source, and the transistor to limit the current being drawn from the source.

Our light will be an LED, we're expecting that the voltage going to the LED will be 5V at most, but as little as 3v so we look at some data sheets for LEDs and we find that the there are a couple that we can't use, (some have Vmax as 4v), and others will tolerate a higher voltage, but won't light with only 3v.

Eventually we come across the L-53GD-5V made by Kingbright

It has the following characteristics.


So we can see that it'll be on, and bright at 5v, and it will turn on, (though only be half as bright) at 3volts, (we're interested in sensing 5v Logic levels and 3.3v Logic levels right?)

Elsewhere in the data sheet it tells us that the maximum current is 17mA
We know that our greatest voltage going through the LED will be 5v
So we use ohms law to determine the resistor needed.

5/0.017 = 294

So we really want to make the total resistance between the supply voltage and the indicator LED around 300Ohms
In case you're interested

3.3/300 = 0.011 or 11mA available for the 3.3v logic level to light the LED.

I say the 3.3v, remember this is a current amplifier, not a voltage amplifier. The voltage is going to remain the same as what's going into the transistor base.
Anyway, at 3.3v the LED only draws some 6mA, so there is plenty of current available. (and that 11mA is below the devices max draw of 17mA

Schematic
Here is the schematic of the circuit.



And here's what happens when a logic level of 1 (+5v) is applied to the base resistor



When the circuit is on it pulls around 6ma from the logic source, and the current going through the LED is about 14mA.

Stay tuned to see this idea scaled up!

Tuesday, August 09, 2011

Electronics Lessons: The LED

I briefly touched on LEDs previously in the output devices post a while back.

That post was designed to be a little bit of a primer into all kinds of output devices, to get you thinking about the kind of output that you want to put on your projects.

Now I'm going to start looking at those output devices in a little more detail.
I'll skip over light bulbs for the moment, other than small signal lamps, (torch bulbs) there aren't a lot of light bulbs that are particularly practical to drive from beginner projects, they don't solder directly to boards (requiring bulb holders), and lots require either mains voltage, or the type of current that's really going to burn you if it goes wrong. -I'll come back to light bulbs as output devices later in the series mostly because it'll be necessary to explain a project that I've written up and am waiting to publish.)

LEDs
LEDs are light emitting diodes.

When you buy an LED you'll normally find that appears in a round shape with a dome top.
the round shape has a small ledge of skirt at the bottom of it and one of the sides of this next to a leg is flat.
You'll also find that when you buy the component that one leg is slightly shorter than the other.

LED

The reason that a diode has these characteristics is:
The round body: this is a nice easy package type to make, however, LEDs to come in all different shapes and sizes.
A look here: http://www.rapidonline.com/Electronic-Components/Optoelectronics will help to show just how many different shapes and sizes!

The reason that LEDs generally have a dome shaped top is so that they can be seen from a variety of different angles. if you look at surface mount LEDs these will generally have flat tops, this is so that light guides, that will carry the light from your board to your front panel can fit on top. (a light guide is like a fibre optic cable, except that it's generally made of clear plastic (not glass) and is quite thick (measured in millimetres not microns), and is rigid.

The reason that there is one leg shorter than the other, and the reason for the flat spot on the case is that these show which leg is negative.

The component is a diode and will only conduct one way (when used within specification). and when the diode is conducting it will let you know by giving out light.

Circuit symbol
The LED is a diode, therefore is shares the same basic symbol as the diodes, (arrow with a flat bar on it) however, as this device emits light there are also two arrows the come out of the diode.

I've only drawn the basic, and now standard symbol for the LED.
however, you may find that there is a circle around the diode symbol, you may find that the arrows have a zig-zag in the middle, the arrow heads may or may not be filled.


Some experiments to try
There are some experiments that you may wish to try.

The first experiment that you should do is either using a power supply with a variable voltage. or using batteries, the examples that I'll use will involve batteries.

For this experiment you're going to need 3AA batteries, (1.5 Volts).
and a 1K resistor (note this is not the same colour bands as shown in the pictures, that's just a picture).
and a 100Ohm resistor

First connect all the batteries end to end inside a battery holder.
Connect the 1k resistor to the battery packs' negative terminal.
Now connect the other leg of the resistor to the negative leg of the LED
Connect the positive leg of the LED to the first battery in the battery pack.

You'll see that the LED doesn't come on at all.

That's because in order to make the LED light up around 2volts is used up. since you don't even have 2 volts this thing won't light up.

so now connect the positive leg of the LED to the second batteries positive terminal.

Now you've got 3v as a supply voltage, so you've got enough to make the LED light up.
but it'll be very dim.


That's there isn't much current flowing through the device, and the amount of current going through the device is proportional to how bright it looks.

To figure out how much current goes through the device,
start with your supply voltage (3v)
take away the forward voltage of the LED (2v) you're left with 1v

Now use Ohms law to determine how much power is flowing through the circuit
1/1000 = 1miliamp (barely enough to even make it work!)

Now swap your 1k resistor for the 100Ohm, resistor.
the LED should appear to be brighter. the reason is that more current is flowing
1v / 100 Ohms = 10milliamps of current flowing.

Now repeat the same steps on the positive voltage of the last battery.

This time the LED should be reasonably bright with the 1k resistor and much brighter with the 100Ohm resistor

this is due to the fact that there is now 4.5v supply. (subtract 2 for the LED) leaves 2.5v being dissipated in the resistor.
2.5/1000 = 2.5milliamps.

Before you substitute the 1k resistor for the 100Ohm resistor be sure to take a look at the resistor from the top (birds eye view looking down on the dome,) and from the side.

Notice how it looks brighter at the top. and as you come down to look at the side view, the light almost disappears completely?

Now put that 100 Ohm resistor in the circuit.
When you put the 100ohm resistor into the circuit
2.5/100 = 25milliamps.

You may now find that either the LED is lit very brightly, or that it sort of lit brightly for a bit, but now doesn't work.
It's not going to have exploded! but it might have failed inside. (if you pump enough power through an LED it will explode though!)

Looking at data sheets
To find out why your LED doesn't work any more we'll have a look at the data sheet.

The data sheet that I'm using for reference is:
http://datasheet.octopart.com/L-53GD-5V-Kingbright-datasheet-578943.pdf

Data sheets give you all kinds of useful information, some are better than others, this one just happens to give a lot of information.

So... lets look at the data sheet and find out why the things that were happening above happened.
why varying the resistor made a difference to the brightness, why varying the voltage made a difference, and why the viewing angle made a difference.

We'll start with the viewing angle:
At the end of the data sheet is a diagram called spatial distribution. this diagram is a little confusing at first, but here is now to read it.

firstly there is a circle at the bottom, you need to imagine that the dome of the LED is inside this circle, now you notice that there is a straight line going up to the marking 0 degrees.

This means that you're looking straight down on the LED.
you can see on the blob shape in the middle touches this 0degree line at the top.
moving along this reaches 1 on the brightness scale.

Now if you change your viewing angle to 30degrees, you find that the blob touches a different brightness line, this line is 0.5
This means that at 30degrees that LED is half as bright as when looking at it from the top.

Now if you move anywhere in the 60 - 90degree region, you'll see that the blob doesn't even touch the line, basically, you'd be lucky to see any light at all.

Clearly this is important if you're using the light to indicate anything.

For a start, lets say that your device sits flat at one end of a room, sitting down at the other end of the room your viewing angle will be so shallow that you won't see it at all, OK so this might mean that you just don't know if your cat is inside of outside, no big deal.

Now consider that you're using these LED as brake lights? you're braking in one lane, people behind you can see, but what about people who are only slightly behind and alongside. they can't see that you're braking. what if you try to use these as direction indicators/turn signals? now it's really dangerous as people who need to know your intentions are now given no warning of your intentions.

You might think those LED bulbs are super bright and look cool (and they do) But what if they aren't bright enough? what of the viewing angle? what if they are too bright? this is why (in Europe at least) all car parts have to be E marked, to say that they are tested and approved.

Next let's look at the voltage characteristics:
What these charts are telling us is that as more voltage is applied, the device will get brighter.

And that as more voltage is applied, more current is passed through the device.
This is exactly what we saw in the experiment, as voltage increased, the device got brighter.
As the current limiting resistor was decreased, more current flowed through the device, which was proportional to the voltage "used" in the device, and so the device got brighter.

Next lets look at the maximum ratings:
The maximum ratings are there to tell us what conditions we can place on the device, this this case the maximum rating tell us a few things.

Firstly: forward current (max) the maximum current permitted to flow through this device is 17.5mA (when the voltage is 5v)
This means, select your current limiting resistor such that only this much current can flow.

Then we have absolute maximum ratings:
maximum power: 85mW this means select your input voltage, and current limiting resistor such that less power than this is able to flow, (for lower voltages you can use lower value resistors.)

The absolute maximum voltage rating is 6v, putting more voltage than this through the device will make it stop work, (possibly in a spectacular way.)

Last, but not least we have temperature ratings.
now these are important if you're planning on making a project that'll go in a particular place.
With temperatures of -40 - 60 degrees Celsius, these devices aren't going to be suitable for making stuff that you plan to use in the Antarctic, nor will they be suitable for devices that are left in the baking hot equatorial sunshine.

But lastly, they tell you how long you can hold a soldering iron on the leads before the heat will damage the component. this goes back to the Electronics workbench shopping list of equipment.

If you buy a low power soldering iron, you will have to wait longer for things to heat up. That's because it take the heating element longer to heat up, in the same way that a 2000w kettle boils faster than a 1000w, a 40W soldering iron heats up the components quicker than a 15 or 20Watt one, meaning that you don't have to hold it on the work as long. meaning that you're less likely to damage the components.

Thursday, August 04, 2011

Electronics Lessons: The Transistor

This lesson deals exclusively with Bi-Polar Junction transistors (BJT)
So I covered the diode, a couple of lessons ago.

I'm trying to make these lessons as simple as possible,

I'm trying to keep these beginner introductions to components as simple as possible, trying to keep them at a type GSCE level, so I'm not going to go into exactly how silicon is created and doped to P or N types, I'm not going to go through all the in depth technical stuff that a university course would cover.

These are beginner lessons, assuming that I do stick with this, those more in depth lessons should come a bit later.

The Diode
While I did just say that I wasn't going to go in depth as to how diodes are made it's important to understand a little bit about diodes.

Basically there are three types of silicon in this world.
There is silicon as you find it, that's pretty useless for electronics, then there is doped silicon, doping silicon enables to to be able to transport electrons and therefore allow electricity to flow.
There are two types of silicon, P type, (that contains what we call holes as the transport mechanism) and N type (that contains negative charge carriers [electrons]).

When you put these together you form a PN junction diode, which lets electricity flow one way.

The Transistor
transistortransistor
Once upon a time transistors came in metal cases, the little tab on the case was next to the emitter leg, the collector was usually attached to the case and the base was the remaining leg, now they tend to come in plastic cases, and you need the data sheet to tell which leg is what.

The transistor is like two diodes placed back to back, (or front to front depending on the transistor type), arranging the blocks of doped silicon like this allows you to make the transistor act like a switch, but let's not get ahead of ourselves too much just yet.

I'm going to look at the NPN transistor for now.

NPN Transistors
The NPN transistor is called such because the sandwich of silicon is a P-type piece of silicon sandwiched between two N-type pieces. this forms two PN junctions where the P type silicon is shared. (no you can't actually wire two diodes back to back to make a transistor, the semiconducting silicon actually has to be shared).

Each piece of silicon is attached to a leg, and on BJTs these legs are given the name collector, base and emitter.

The collector collects current, and the emitter emits it, (that's overly simplistic, but vaguely true) the base leg controls the amount of charge in the bit of silicon in the middle and therefore controls the amount of current, or electrons that can flow through the device.

If you apply voltage to the base, then you essentially turn the tap on, (assuming you apply enough voltage!).
If you apply 5v then the tap is on. (hard on) the component will what is called hard on.

When you look at the data sheet for the component, you're going to see that there is (of should be!) two values of particular interest, one of these is VBE(sat)

That's the VBE saturation voltage, the amount of voltage needed to turn the transistor hard on.

For BC108 transistors this value is 0.7 volts, (so this or any voltage over this is going to turn the transistor into saturation mode, where it's conducting as much as it can, and can't conduct any more).

You'll also notice that in the VBE values in general there are three values.
Min, Typ (typical) and Max.
Max is the same as the saturation voltage, which we've already covered.
Min is the minimum voltage needed to turn make the transistor start conducting at all.

There are a few more values of interest (depending on the project that you're doing) I'll tell you what these are, and how to use them in a later tutorial.

We've covered that if you apply less voltage that VBE(min), then the transistor won't turn on at all, and if you apply more than VBE(max) that transistor goes into saturation mode.

So what if you apply VBE(typ)?
Again this will be an over simplification, what we'll say is that the transistor is half on.
it's not conducting in it's full on saturation mode, nor is it in it's non conducting off mode. it's half on, go a little over VBE(typ) and it'll conduct a little more, go a little under VBE(typ) and it'll conduct a little less.

Note: That VBE is the voltage difference between the base and the emitter, not necessarily the voltage applied to the base, increasing this voltage above VBE(max) will force more current through the junction and destroy the component.

The transistor is a variable switch, a current amplifier, a voltage amplifier.

Schematic symbols
The symbol for a BJT transistor is a little more complicated than for other components, that's because there are three legs for a start, and they come in two varieties, NPN and PNP.

We'll start with the emitter leg, if you think back to the diode, the symbol for that was an arrow with a bar, the arrow pointed to the N type silicon,

The part of the symbol that shows the emitter is an arrow, the arrow points to the N type silicon.
so on an NPN transistor the arrow points outwards from the base (because the base is P and the emitter is N), on a PNP type the arrow points inwards (because the emitter is P and the base is N)

The Base is a thick straight line.
the collector is an angled straight line.

so here is the symbol for a NPN transistor (remember the arrow point out)
NPN Transistor

And here is the symbol for the PNP type transistor (remember the arrow points in)
PNP Transistor

Monday, August 01, 2011

Electronics Lessons: The Capacitor

Capacitor
In the first lesson we looked at resistors, In that post I said that you could think of a battery like a tank full of water, and a resistor as like a small pipe.

Well now I want to change my mind on that analogy and say that you can think of a battery like a mains pipe, and think of a capacitor as like the header tank that sits in your attic.

Capacitors have some pretty cool properties. What I will do in this lesson is explain the electrical characteristics of capacitors, what I'm not going to do is tell you about how capacitors are made, for the purpose of using them it's just not important, and if you want to know, then Google is your friend!

Another Water Analogy
Now I just said that capacitors were like a header tank.
I think that this is a good analogy. You see with a header tank of water, you always have some water pressure coming from your tank.
The tank is exhausted fairly quickly, but if there are workmen in your road who turn off the mains supply, you are still able to turn the tap on, at least for a little bit.

Storing Charge?
Capacitors store electricity, at least that is to say that capacitors store potential energy. They don't have a special electron repository, they have a metal plate inside and charge is accumulated on one side of the plate (as electrons are forced from one plate to another). When you discharge a capacitor you allow it to rebalance it's self (as in you allow the charge across the plates to equalise and become neutral).

Saying that capacitors store charge is technically wrong. There are no more electrons in a "charged" capacitor than there are in a "discharged" capacitor, but it's nice and simple to think of a capacitor like a mini battery, it gets charged, it gets discharged. it's not quite as good as a battery, it doesn't (usually) hold as much charge, and discharges far quicker, so like I said before, if your battery was like your mains water, your capacitor is like a tank full of water in your attic, or on your roof.

One of the first uses of capacitors that you may want to consider is using it to store charge in a power supply.

If you look at the diode lesson, you'll see that we used the diode to create a simple circuit that removed half of an AC waveform, meaning that we could connect it up to a circuit that had a positive and a negative, and that we wouldn't break anything that was sensitive to being connected in reverse. of course the problem with that circuit was that the waveform fell away to zero on the negative half cycle of the AC wave, this would, (in the case of a 50Hz mains signal). mean that you were turning off the power supply and turning it back on quickly every 1/50th of a second (or every 20ms).

A capacitor can be charged on this positive half cycle, when there is plenty of voltage, and then when the supply is in the negative half cycle (or off after the diode), the capacitor can discharge is accumulated charge into the circuit. just like the water tank in your attic/roof when the mains supply is off.

Symbols
Before introducing a circuit, it seems only fair to show you want the symbol that represents a capacitor in a circuit is.

Capacitors come (aside from being made from different things and in different ways) two types.
Polarised, and non-polarised.

Polarised capacitors have polarity, they have a positive and negative leg, non-polarised capacitors do not have either defined positive, nor negative leg and can be connected either way around.

If you remember from the resistor lesson, I said that there were two different symbols that you may see for the resistor, each invented at different times, well, unfortunately, there are more than 2 for the capacitor, (partly because of the polarised/un-polarised components), and partly because someone decided that a different notation would be nice.

You'll see that in the diagrams, sometimes there is a positive symbol, as you can imagine this tells you that the component is polarised, but sometimes there is not a positive symbol, but the rest of the symbol sill looks the same as for a polarised capacitor... you'll find that sometimes people may use a polarised symbol, and not put in that helpful little plus sign, it's still a polarised capacitor, and the rest of the symbol tells you what way round it's connected.

Lets start with the non-polarised capacitor: this will pretty much always look the same, (though the lines may be thicker or thinner.
capacitor

Now the polarised capacitors, I've drawn these so that they are always having the positive side on the left.
CapacitortCapacitorCapacitorCapacitor


Circuit use
Going back to that simple diode circuit what we do is add a capacitor between the output of the diode and the 0v rail in the circuit. and as described above, the capacitor charges and discharges.


Once again lets look at the wave forms coming out of that.



We can see that the supply circuit is better, our circuit won't be switching off every few seconds, and if we were just trying to light up an LED it'd be good enough. But that blue output wave form is pretty choppy, if we were using that in an audio circuit to drive an amplifier for example the fact that the circuits voltage sags so much means that you'd actually be able to hear it!

The problem here may seem obvious, we need a bigger capacitor.

So lets increase that 1Microfarrad capacitor to a 10uF


Now the output wave form is a lot better. It's been smoothed out as you can see below.

But it's still not perfect. there is still a ripple.

So the obvious answer is to increase the size of the capacitors again.

But I'm going to do it a little differently this time (as it'll help me segway to more information).



And the output wave.


What? You might be saying, what did I do there, I didn't increase the size of the capacitor at all, I just jammed more capacitors in there.

Adding capacitors together
Well you see what I actually did was added the values together.

Capacitors are basically made up of plates, the size of those plates (and amount of plates, and distance between those plates) determines the size of the capacitor.

The bigger the plates, the bigger the capacitance.

I joined these capacitors in parallel, so it's a big like stacking the plates next to each other, I've increased the size of the plates by using multiple capacitors.

When capacitors are connected in parallel, to determine the size of the capacitor you're creating, you just add them together.

C1 + C2 +C3 = Ctotal

So in this case the values are 3 10uF capacitors.
so it's
10uF + 10uF + 10uF = 30uF

So I did increase the size of the capacitor, I just did it in a different way.

There is a different formula for connecting capacitors in series and this is:

(1/C1) + (1/C2) = (1/sum) = Ctotal

Basically, capacitors in parallel have the same formula as resistors in series, and capacitors in series have the same formula as resistors in parallel.