Google+ Followers

Wednesday, May 22, 2013

22. The Raspberry Pi Camera

On 14-May-13, the Raspberry Pi Foundation released their much anticipated Camera Board.  I ordered mine from one of the distributors, CPC (Farnell), and I got delivery the next day!  I think I was very lucky because they ran out of them very soon and lots of people who want them will be waiting for some time.  The roughly one-inch square board looks like this:

I have suspended mine with a piece of green jumper wire through two of its mounting holes.  I have photographed it at this angle because this is the orientation it takes pictures in (top of the object at the top of the image).  The images taken are mirror reflections (although you can easily change this with a -hf addition to the command line - see below), as you would expect to see the image in a mirror, rather than as a photographic camera would take them.  [Note that this is not a problem with later Raspbian "wheezy" software updates].  The connector tape can just be seen coming out of the bottom, on its way to the Raspberry Pi.

Above is the camera connected to my Pi.

The images are surprisingly good for such a cheap camera (less than £20 delivered).  
The camera has 5 megapixels, so its resolution is good, and although it is permanently focused at infinity, objects more than a couple of feet away are pretty sharp.  A useful comparison of the Raspberry Pi camera with 2 camera phones and a couple of cameras showed that the Raspi Cam came out not too badly:

The software is still being developed by the producers and the plan is to not only improve the image quality, but to increase the video frame rate.

The commands raspistill (for taking still pictures) and raspivid (for taking video) need to be qualified by adding options to the command line - for example,  

raspistill -o image1.jpg will capture a jpeg image named image1.jpg,
raspivid -o video1.h264 will record a 5 second video in h264 (raw) format -  video1.h264,
raspivid -o video1.h264 -t 10000 will record a 10 second video named video1.h264

The basic command options for capturing still (2592 pixels by 1944 pixels) are as follows:

-?, --help : This help information
-w, --width : Set image width
-h, --height : Set image height
-q, --quality : Set jpeg quality <0 data-blogger-escaped-100="" data-blogger-escaped-to="">
-r, --raw : Add raw bayer data to jpeg metadata
-o, --output : Output filename (to write to stdout, use '-o -'). If not specified, no file is saved
-v, --verbose : Output verbose information during run
-t, --timeout : Time (in ms) before takes picture and shuts down (if not specified, set to 5s)
-th, --thumb : Set thumbnail parameters (x:y:quality)
-d, --demo : Run a demo mode (cycle through range of camera options, no capture)
-e, --encoding : Encoding to use for output file (jpg, bmp, gif, png)
-x, --exif : EXIF tag to apply to captures (format as 'key=value')
-tl, --timelapse : Timelapse mode. Takes a picture every ms
Preview parameter commands
-p, --preview : Preview window settings <'x,y,w,h'>
-f, --fullscreen : Fullscreen preview mode
-n, --nopreview : Do not display a preview window
Image parameter commands
-sh, --sharpness : Set image sharpness (-100 to 100)
-co, --contrast : Set image contrast (-100 to 100)
-br, --brightness : Set image brightness (0 to 100)
-sa, --saturation : Set image saturation (-100 to 100)
-ISO, --ISO : Set capture ISO
-vs, --vstab : Turn on video stablisation
-ev, --ev : Set EV compensation
-ex, --exposure : Set exposure mode (see Notes)
-awb, --awb : Set AWB mode (see Notes)
-ifx, --imxfx : Set image effect (see Notes)
-cfx, --colfx : Set colour effect (U:V)
-mm, --metering : Set metering mode (see Notes)
-rot, --rotation : Set image rotation (0-359)
-hf, --hflip : Set horizontal flip
-vf, --vflip : Set vertical flip
Posted by  in Tutorials on May 22, 2013 . 0 Comments.

RaspiStill Camera App
Runs the camera for a specific time, and takes a JPG capture at the end if requested 
Usage: RaspiStill [options] Image parameter commands

Exposure mode options:
off, auto, night, nightpreview, backlight, spotlight, sports, snow, beach, verylong, fixedfps, antishake, fireworks 

AWB mode options :
off, auto, sun, cloud, shade, tungsten, fluorescent, incandescent, flash, horizon 

Image Effect mode options:
none, negative, solarise, sketch, denoise, emboss, oilpaint, hatch, gpen, pastel, watercolour, film, blur, saturation, colourswap, washedout, posterise, colourpoint, colourbalance, cartoon 

Metering Mode options :
average, spot, backlit, matrix

To display the still image on the Raspberry Pi, you can simply open the file using Image Viewer or a similar Raspberry Pi program.

Here is an example of a still image which is an image of the Pi and camera in a mirror, with a map background:

PiCam Self Portrait - it's all done using mirrors!

The options for recording video (1920 x 1080 pixels, at 30 fps (frames per second) (Described as Full HD) or 1280 x 720 (60 fps), or 640 x 480 (at 60 or 90 fps) are:

Posted by  in Tutorials on May 22, 2013 . 0 Comments.

RaspiVid Camera App
Display camera output to display, and optionally saves an H264 capture at requested bitrate Usage: RaspiVid [options] Image parameter commands 

-?, --help : This help information
-w, --width : Set image width <size>. Default 1920
-h, --height : Set image height <size>. Default 1080
-b, --bitrate : Set bitrate. Use bits per second (e.g. 10MBits/s would be -b 10000000)
-o, --output : Output filename <filename> (to write to stdout, use '-o -')
-v, --verbose : Output verbose information during run
-t, --timeout : Time (in ms) before takes picture and shuts down. If not specified, set to 5s
-d, --demo : Run a demo mode (cycle through range of camera options, no capture)
-fps, --framerate : Specify the frames per second to record
-e, --penc : Display preview image *after* encoding (shows compression artifacts)
Preview parameter commands
-p, --preview : Preview window settings <'x,y,w,h'>
-f, --fullscreen : Fullscreen preview mode
-n, --nopreview : Do not display a preview window
Image parameter commands
-sh, --sharpness : Set image sharpness (-100 to 100)
-co, --contrast : Set image contrast (-100 to 100)
-br, --brightness : Set image brightness (0 to 100)
-sa, --saturation : Set image saturation (-100 to 100)
-ISO, --ISO : Set capture ISO
-vs, --vstab : Turn on video stablisation
-ev, --ev : Set EV compensation
-ex, --exposure : Set exposure mode (see Notes)
-awb, --awb : Set AWB mode (see Notes)
-ifx, --imxfx : Set image effect (see Notes)
-cfx, --colfx : Set colour effect (U:V)
-mm, --metering : Set metering mode (see Notes)
-rot, --rotation : Set image rotation (0-359)
-hf, --hflip : Set horizontal flip
-vf, --vflip : Set vertical flip
Exposure mode options :
AWB mode options :
Image Effect mode options :
Metering Mode options :

When the video image is captured, you will now want to display it.  On the Raspberry Pi, you can do this using omxplayer:

omxplayer video1.h264 or

omxplayer video_out.mp4

So - how do you get mp4 files?

METHOD 1: (Didn't work for me)
It is possible to convert the h264 video format into mp4 by using ffmpeg:

ffmpeg -r 30 -i video_in.h264 -vcodec copy video_out.mp4

This can also be done for mkv format as well as mp4 format.

I tried to show an example of the video images that are possible.   I recorded a 10 second h264 video, converted it to an mp4 file, but when I got it transferred to my PC from my Pi, the video upload on this blog kept failing....

METHOD 2: (Worked for me)
I eventually got a 5 second mp4 file to work, by trying a different approach - I did a

sudo apt-get install gpac

to install this package, and to convert the .h264 to .mp4 on the Pi (it actually puts the h264 file into an mp4 wrapper), I used the following from the gpac installation:

MP4Box -add filename.h264 filename.mp4

and transferred the resulting mp4 file to my PC by email (note the usual 25 MB limit could be a problem for long videos, so I will have to get some other method to do this kind of transfer).

Anyway - it worked!!  And here is the amazing result: 

What a gripping video!!  Now I have to find out how to get the big files from the Pi to the PC without using email.

Thursday, May 16, 2013

21. Using the PC as a Remote Raspberry Pi Terminal

If you don't have a dedicated keyboard, mouse and monitor for your Raspberry Pi, you will have to borrow these from the family PC and TV room.  However, this is only temporary, because you can use your PC (desktop or laptop) to display the RasPi desktop and windows, and run all your RasPi programs this way:

My RasPi's desktop looks like this on a small TV:

and the result on my PC's screen looks like this:

There is a noticeable difference in the shape of the image due to the different aspect ratios of the TV and my PC monitor, but don't let this put you off.

The first thing to do is to enable the Pi to undertake SSH (which means Secure Shell - ie what we're trying to do here), and to do this you need to have the Pi connected to the temporary keyboard/mouse and monitor (TV) and of course, the internet.  Open the Terminal on the Pi and find out what the Pi's internet address is.  We did this before in an earlier post.  Type: 

sudo ifconfig

and a lot of information is printed on the screen.  At the section which starts wlan0, look for 
inet addr: and the four numbers separated by dots, are the Pi's (Dynamic) IP address.

Now type the RasPi command:

sudo raspi-config

and you will be faced with a screen like this:

You can navigate about this screen with the Up-, Down-, Left- and Right-arrows.  

Highlight the line beginning with ssh (see the picture above) and hit Enter.  You then have the opportunity to Enable or Disable.  Highlight Enable and hit Enter.  This enables the Pi to participate in the SSH session.

Now, on your (Windows) PC, it is necessary to download a couple of programs - PuTTY (an open source, free, SSH client, and Xming, an X-window client, also free.  The procedure for PCs running operating systems other than Windows, is slightly different.  A good website to download these from is:

This is useful as it shows screen shots for setting up the two programs Xming and PuTTY.  Then when these programs have been installed on your PC (ignore warnings), 

  1. run Xming
  2. run PuTTY
  3. Select SSH as the connection type.
  4. Enter in your Pi’s IP address (see above) as the Host Name
  5. The port should be 22 unless you know better
  6. In PuTTY’s option tree, select Connection/SSH/X11
  7. Check the box labelled Enable X11 forwarding
  8. Go back to Session options (in the option tree)
  9. If you would like to save these settings, type a name in the Saved Sessions box and click Save
  10. Click Open
  11. Once you have logged into the Pi using the login details  - "pi" & "raspberry" (unless you have changed these)
  12. Type startlxde (NB no space!!) and you will see the desktop of your Raspberry Pi in the Xming window.

The  Saved Session in 9 above is very useful for repeating these settings at another time.

And Hey Presto! you have your Pi running on your PC monitor with full control!!  Please note that this system is only working on your local network, and not through the internet, so your PC is the only one that will be able to run your Pi.

Any way - you can now give back the keyboard, mouse and TV to their rightful owners!

For more detailed information on this subject, once again Lady Ada has come up with an excellent  tutorial at:

Wednesday, May 15, 2013

20. Infra Red Remote Detector

This is a nice little project, and makes use of an IR Sensor which is a 3-legged component that looks like a large transistor.  The actual component I have is a Vishay TSOP4138.  This requires an input voltage (or Vcc) of 2.7V to 5.5V.  It's easy to take 5V from the Arduino supply.

You will see from my breadboard pictures that I am using my latest Arduino - another BreadboArduino from HobbyTronics Ltd.  You just can't have enough of them!!  The ATMega 328 chip has been given a useful label on the top, to help identify the pin-outs of the chip.  This BreadboArduino uses a mini USB connection from my PC, to a Sparkfun FT232 Breakout (bottom middle), which supplies power and connections for programming on the PC via the Arduino ISP. 

At the top left, I have included 2 LEDs close together (and surrounded by heat shrink to insulate the long legs from other connections).  The red LED shows "power on" and the green LED is connected via a resistor to Digital Pin 13 - as is usual with proper Arduinos.  Pin 13 is used in my sketch, so that the LED will blink when the IR sensor receives a signal.

The IR Sensor is at the top right of the picture and the three legs as we see them in the picture, are Vcc, GND and Vout signal.  You can also see my oscilloscope probes connected to the IR Sensor signal out and GND, so that I can have a look at what's coming out.

Remote Controllers
TV and Hi-Fi remote controllers are very common in the home, but do we really know much about them?

I found I had several of them about the house, and borrowed a couple:

On the left is a Haier TV controller and on the right is a Toshiba VCR player controller.  If you look at the upper end of these, you see an infra red LED, whose light you can't see with your naked eyes.

However, most digital cameras can "see" these LEDs light up - unless they have been fitted with IR filters.

The IR transmitter LED transmits Near Infra Red (or IR-A) light, carrying hexadecimal (Hex) codes which are pulse-width modulated at a high frequency (38 kHz) (hence the 38 in the model number).

The Vishay TSOP4138 is a smart device because it de-modulates the carrier frequency, so that it's output signal is the Hex code only.

The video below shows each of the controllers above emitting IR light:

You can also see in the video that when I press buttons on the IR controller, my IR Sensor picks up the signal, and flashes the green LED (which is connected to Pin 13 on the Arduino) at the same time.

The files that can be downloaded as the IRremote library include a test sketch which allows identification of the sensor's Hex output corresponding to each button on each IR controller:

The example sketch is on the top and the Serial Monitor output is below.  From this I identified the numbered buttons on each of the two IR controllers.  I then modified the IRrecvDemo sketch to detect if any of the number buttons on either of the two IR Controllers have been pressed.  When any other button is pressed, even on any other controllers, the output from the Serial Monitor is simply "--------------------------".  Otherwise, if any of the numbered buttons on either of the two IR controllers is pressed, its identification is printed, along with the Hex code itself:

Here are a couple of oscilloscope traces of the sensor hexadecimal output, one resulting from the Haier and one from the Toshiba:


My modified version of the sketch is listed below:

1:  /*  
2:   * IRremote: IRreceiveKC - demonstrates receiving IR codes previously identified with IRrecv  
3:   * An IR detector/demodulator must be connected to the input RECV_PIN.  
4:   * Version 0.1 July, 2009  
5:   * Copyright 2009 Ken Shirriff ::: Modified by Sparks N Smoke  
6:   *  
7:   */  
9:  #include <IRremote.h>  
11:  int ledPin = 13;  
13:  int RECV_PIN = 12;  
14:  IRrecv irrecv(RECV_PIN);  
15:  decode_results results;  
16:  String v;  
18:  void setup()  
19:  {  
20:   Serial.begin(9600);  
21:   irrecv.enableIRIn(); // Start the receiver  
22:   pinMode(ledPin, OUTPUT);  
23:  }  
25:  void loop() {  
26:   if (irrecv.decode(&results)) {  
28:    digitalWrite(ledPin, HIGH);  
29:    delay(100);             // wait   
30:    digitalWrite(ledPin, LOW);  
31:    //Serial.println(results.value, HEX);  
32:    v=String(results.value, HEX);  
33:    //Serial.println(v);  
34:    if(v=="22dd807f")  
35:    {  
36:     Serial.print("Button 1, Toshiba ");  
37:     Serial.println(results.value, HEX);  
38:    }  
39:    else if(v=="fb2ad5")  
40:    {  
41:     Serial.print("Button 1,  Haier ");  
42:     Serial.println(results.value, HEX);  
43:    }   
44:     else if(v=="22dd40bf")  
45:    {  
46:     Serial.print("Button 2, Toshiba ");  
47:     Serial.println(results.value, HEX);  
48:    }   
49:    else if(v=="fb6897")  
50:    {  
51:     Serial.print("Button 2,  Haier ");  
52:     Serial.println(results.value, HEX);  
53:    }   
54:    else if(v=="22ddc03f")  
55:    {  
56:     Serial.print("Button 3, Toshiba ");  
57:     Serial.println(results.value, HEX);  
58:    }   
59:    else if(v=="fba857")  
60:    {  
61:     Serial.print("Button 3,  Haier ");  
62:     Serial.println(results.value, HEX);  
63:    }   
64:    else if(v=="22dd20df")  
65:    {  
66:     Serial.print("Button 4, Toshiba ");  
67:     Serial.println(results.value, HEX);  
68:    } else if(v=="fb0af5")  
69:    {  
70:     Serial.print("Button 4,  Haier ");  
71:     Serial.println(results.value, HEX);  
72:    }   
73:    else if(v=="22dda05f")  
74:    {  
75:     Serial.print("Button 5, Toshiba ");  
76:     Serial.println(results.value, HEX);  
77:    }   
78:    else if(v=="fb48b7")  
79:    {  
80:     Serial.print("Button 5,  Haier ");  
81:     Serial.println(results.value, HEX);  
82:    }   
83:    else if(v=="22dd609f")  
84:    {  
85:     Serial.print("Button 6, Toshiba ");  
86:     Serial.println(results.value, HEX);  
87:    }   
88:    else if(v=="fb8877")  
89:    {  
90:     Serial.print("Button 6,  Haier ");  
91:     Serial.println(results.value, HEX);  
92:    }   
93:    else if(v=="22dde01f")  
94:    {  
95:     Serial.print("Button 7, Toshiba ");  
96:     Serial.println(results.value, HEX);  
97:    }   
98:    else if(v=="fb32cd")  
99:    {  
100:     Serial.print("Button 7,  Haier ");  
101:     Serial.println(results.value, HEX);  
102:    }   
103:    else if(v=="22dd10ef")  
104:    {  
105:     Serial.print("Button 8, Toahiba ");  
106:     Serial.println(results.value, HEX);  
107:    }   
108:    else if(v=="fb708f")  
109:    {  
110:     Serial.print("Button 8,  Haier ");  
111:     Serial.println(results.value, HEX);  
112:    }   
113:    else if(v=="22dd906f")  
114:    {  
115:     Serial.print("Button 9, Toshiba ");  
116:     Serial.println(results.value, HEX);  
117:    }  
118:    else if(v=="fbb04f")  
119:    {  
120:     Serial.print("Button 9,  Haier ");  
121:     Serial.println(results.value, HEX);  
122:    }    
123:    else if(v=="22dd50af")  
124:      {  
125:     Serial.print("Button 0, Toshiba ");  
126:     Serial.println(results.value, HEX);  
127:    }   
128:    else if(v=="fb30cf")  
129:    {  
130:     Serial.print("Button 0,  Haier ");  
131:     Serial.println(results.value, HEX);  
132:    }  
133:    else  
134:    {  
135:     Serial.println("--------------------------");     
136:    }  
137:    irrecv.resume(); // Receive the next value  
138:   }  
139:  }  

This ability to control systems via infra red would be very useful for controlling robots, and other systems which are within line-of-sight (although as you will see with your TV controller, the signal does seem to scatter off other surfaces in the room, without pointing directly at the TV) and at the sort of ranges that you find within household rooms.

For more information on this kind of project, there is an excellent tutorial from Lady Ada at  - highly recommended!

Tuesday, May 14, 2013

19. Back to the Raspberry Pi - WebIOPi

You might remember in Post 1 that this all started because of the Raspberry Pi.  I then got a Raspberry Pi extension board, the Gertboard, which happens to have an Arduino chip, which can be programmed using the Arduino API on the RasPi.  Having gone off on a tangent following electronics combined with the Arduino, I then concentrated on just breadboard projects.

Now it's time to get back to the Raspberry Pi.  A couple of MagPi editions ago ( I came across WebIOPi, by Eric Ptak.  This uses the web, to control Input/Output pins on the Pi.  A truly amazing piece of technology!  Just imagine that you can have a web page on any PC or mobile device - anywhere - and by clicking on the web page buttons, you can control things connected to your remotely-situated RasPi.

All kinds of applications come to mind - from controlling the security or heating systems in your home, over the internet, to operating robots remotely with your mobile phone.

The Pi becomes a web server, and that part of the coding is written in Python, while the client (webpage) is written in HTML and JavaScript.

The first thing you need to do is find out what your Pi's IP address is (NB this changes periodically), so on the RasPi terminal, you need to do a:

sudo ifconfig  (your Pi has to be on-line of course)

to find out what your particular Pi's address is.  The Pi's terminal pours out a lot of stuff, but in the wlan0 section, it should list inet addr:   My particular address is a Dynamic IP (internet protocol) address, as opposed to a Static IP address, meaning that it will change each time my router is restarted:

My Pi is running Raspbian Wheezy available for free download from   At the time of writing this post, the latest version is 2013-02-09 ie 9-Feb-13.  You need to keep an eye on this download page to update to the latest version whenever one is released.

To freshen up my version, I did a: 

sudo apt-get update && sudo apt-get install raspi-config libraspberrypi* 

and it does no harm to do a: 

sudo apt-get upgrade

before going any further.  Then I followed the instructions to install and use the standard web page - and it came up in my browser (on my desktop and on my iPod Touch):

I wired pins P0, P1 and P4 on my Gertboard (remember I keep the Gertboard connected to my Pi all the time) to a mini breadboard with an RGB LED (through suitable resistors).  Don't forget to run a GND from the Gertboard to the common cathode (in my case) of the RGB LED.  These 3 pins correspond to RasPi pins GPIO 0, GPIO 1 and GPIO 4, which are illustrated on the web page, whose address is

If you click on the grey buttons, you can change the function of that pin to OUT (output) or IN (input).  You can see from the image above, that all the GPIO pins are initially set to IN.  The GPIO pins are shown by rectangles with respective numbers in them, and are either black (inactive) or orange (active) to indicate whether they are in high state or low state.

My GPIO 8, GPIO 9, GPIO 10 and GPIO 11 are still connected to the Gertboard, and are used for programming the ATMEGA 328).  Be careful with GPIO pin numbers - the latest version of the Pi is different!  As I'm using GPIO 0, 1 and 4, I clicked on the grey buttons beside these to make them outputs:

and when I clicked on the 3 to make it orange, the LED on my desktop beside my Pi lit up red, when I clicked to make 5 only orange, the blue element of the RGB LED lit up, and with 7 only orange, green lit up.  You can make any combination of these 3 buttons active, and get any one of the primary colours, or with any two active, the secondary colours cyan, magenta and yellow, or with all 3 active, white.

I thought this was really cool - being able to control the colour of my LED from anywhere in the world (providing you have port forwarding on your router).  Even Col Chris Hadfield on the International Space Station (he's just landed safely in Kazakhstan today) could control my LED, and therefore any other Raspberry Pi circuit, for example, motors, servos, or any other devices that spring into life when they get an electrical pulse!

I went on to fiddle about with some Javascript and made my own page:

In this case, the LED is glowing Red.

And here's my Pi with the RGB LED's red and blue active, making a bright magenta:


Thursday, May 9, 2013

18. The 555 Timer

Moving on from the simple transistor, and still not involving any coding, some devices have a number of components incorporated into them, including transistors.  The 555 device is an integrated circuit (IC) containing about 23 transistors, 16 resistors and a couple of diodes.

There are three ways to use a 555 timer:
Monostable operation is when the output signal switches between the default off position and a temporary on position at regular intervals - most commonly used for timers. 
Astable operation is when the output signal rises and falls in a set pattern, making it an oscillator. The pattern can be varied, so this mode of operation has many uses.
Bistable operation is when the signal can be held in one of two positions, enabling the 555 timer to act as a basic unit of computer memory.

A more simplified version shows the circuit in terms of operational amplifiers and logic gates :

The three resistors are 5kΩ each, and this is where the name of the chip comes from.  The pin-out is shown below:

Below is my circuit -  when I press the pushbutton, the red and green LEDs in the video (D1 and D2 respectively) flash alternately at a frequency depending on the setting of the variable resistor R2 (the knob on the right in the video).  This is astable operation.

I designed the circuit using Circuit Lab ( which is excellent for designing and examining waveforms in advance of actually putting the components together:
With the variable resistor set at 0.5 (halfway), the predicted signals to the LEDs (ie the voltages across the LEDs - [Vnode1-Vnode2] and [Vnode2-Vnode3)] were:
and with R2 set at 0.1 (a tenth), the predicted voltages across the LEDs were:

The upper graph represents the red LED, which can turn on at 2.1V but not at 1.8V.  The lower trace represents the green LED, which can illuminate at 1.9V but not at 200mV.  

Here is the real thing in action (using a 9V battery):

And here are some captured waveforms, corresponding to the voltage across the red and green LEDs respectively:

Note that the duty cycle is not what Circuit Lab predicted. (I must look into that!  If you have any explanation, I would be eternally grateful).

However, although the trigger positions are not identical, the red LED voltage (top) is much smaller than green's, and when one is on, the other is off - as predicted.

17. The Humble Transistor - Darlington Pair and Darkness Detector

This circuit doesn't need any programming.  Having described the transistor as 'humble' I should retract that because it is an amazing device, basic to all modern electronics, and there's nothing simple about it either. The transistor is anything but humble!!

It has been described as an example of quantum physics in action, because to explain how it works, you need to talk about the energy levels of electrons within materials, in particular, semiconductor materials.

Three physicists, Bardeen, Brattain, and Shockley, developed the transistor (formed from the words "transconductance” and “varistor") and this was announced by the Bell Telephone Laboratories in 1948.  Around the same time, German physicists Herbert Mataré and Heinrich Welker, at Westinghouse Laboratory in Paris also developed it.  The Americans were later awarded the Nobel Prize for this work.

Semiconductors are substances that conduct electric currents, but only very poorly. They are in between true conductors (for example silver, aluminum, and copper) and non-conductors (examples are wool, cotton, paper, air, wood, and plastics). Two of the most commonly used semiconducting materials are the elements silicon and germanium.  Important semiconducting compounds that have been developed include cadmium telluride, gallium arsenide and cadmium selenide.

Semiconducting materials fall into two categories: n-type and p-type semiconductors. n-type have a slight excess of electrons, while p-type have a deficiency of electrons (the deficiencies are known as holes).  This why they are called bi-polar (holes and electrons).
Transistors consist of three layers, n-type/p-type/n-type (known as NPN) or p-type/n-type/p-type (known as PNP).  The most commonly used transistors are NPN type, and they come in different shapes and sizes, but they usually have 3 legs, connectors to the three layers.  The transistor shown below has a D-shaped cross section (it's lying on its flat surface) and E, B and C correspond to Emitter, Base and Collector - the 3 regions.

The middle slice of the transistor is known as the base, and if the transistor is included in a circuit, so that current can flow through it, the current flows into the transistor through the collector, across the base, and out through the emitter.

This current can be controlled by applying a second source of electric current to the base. The amount of current that flows between the collector and emitter will be determined by the base current, so the collector emitter current will be switched off with no base current. With a relatively small base current, the collector emitter current is small, and if a relatively large current is allowed to flow into the base, the transistor allows a much larger flow of current through it.  So the transistor acts like a switch and/or as an amplifier.

Below is an example of two identical NPN transistors, TR1 and TR2, working together.  The input voltage causes a base current at TR1 which gives rise to a collector-emitter current (indicated by the direction of the arrow).  This becomes the base current for TR2, and an even bigger collector-emitter current flows through TR2, making the pair very sensitive to changes in the INPUT voltage:

My example is a "darkness detector".  It uses 2 NPN general purpose transistors (BC548B) arranged together in what's known as a Darlington Pair:

A nice animation for demonstrating it working was found on the following excellent site:

The transistors in the diagram above are drawn with (going clockwise) the Collector and Base in red, with the Emitter in grey:

The variable resistor is the component with a screw-head, for adjustment.  The light dependent resistor (LDR) or photo-resistor is on the left and the moving object is blocking different amounts of light from reaching the LDR.  The less light incident on the resistor, the more resistance it has (more than 20kΩ), and the more voltage there is across the LED.  So when the ambient light's dark, the LDR has a resistance of around 1.5kΩ and the LED glows, when it's bright, the LED is off, and it is very sensitive for detecting the degree of darkness in between the two.

The circuit can also be built with a single transistor, but the Darlington Pair configuration makes the circuit much more sensitive to the small current changes produced by the incident light.

Circuit Lab ( is excellent for designing and examining waveforms and voltages in circuit designs, before actually building the circuit.  Have a look at the DC information in the left-hand panel below, giving information on the voltage between NODE1 and NODE2 ie across the LED.  

I ran Circuit Lab on 2 cases - one where the LDR was illuminated (measured resistance ~9kΩ) and one where it was relatively un-illuminated (measured resistance ~20kΩ):

Above: AMBIENT LIGHT ON: V(Node1)-V(Node2) ie the voltage across the LED, [see the text in the upper left] is 319.9 mV - NOT enough to turn on the LED

Above: AMBIENT LIGHT OFF: V(Node1)-V(Node2) ie the voltage across the LED, [see the text in the upper left] is 2.575V - enough to turn on the LED.

Note that the transistors aren't the same model as mine, but generally, as long as they are also NPNs, it doesn't really matter.