Another good, simple construct which does what it says on the tin, and some good resources explaining what's happening, I really have not got any complaints about this circuit at all.  The only thing I would say is that the optional 220 uF capacitor should be installed anyway, since it won't harm anything if it's in. It's there to stop voltage and current being too far out of phase and if it's not there the effect can cause your Arduino to reset, which won't harm it but it is annoying. Let's look at the circuit as it appears in the book:

Go Back

So then, apart from the optional capacitor there are four components here; a resistor, a transistor, a diode and the motor itself. The motor needs a seperate supply wich is built into your board at the 5V terminal and the other way it goes to ground or 0V potential.


Why do we need the transistor? Because the Arduino does not supply enough current on its own to power a motor (few chips do) but it does supply enough to bias an NPN transistor on. If we supply that to the base of the transistor, we can use the current coming out of the Arduino to control the current at the collector of the transistor; in other words the transistor is acting as a current amplifier. By how much?

Well, running the motor at a constant speed (I'll explain how later) my multimeter said 0.5mA at the base, and 50mA at the collector. this would suggest a gain of 100.

The resistor is there to limit the current the Arduino throws into the base. If it were not there, the current would drive the transistor into saturation too quickly, or worse destroy it. That leaves us with the diode.

The diode performs a function in the circuit which is variously known as flyback, snubbing, freewheeling or catching. This is the principle:


A motor has armatures made of wound copper wire to which we apply a DC source. It therefore becomes an inductor, and if it didn't it wouldn't work. An inductor stores energy in a magnetic field, and if the current changes, it drops energy from that magnetic field back into the circuit in an attempt to resist the change, resulting in a voltage going the other way. Consider the drawing below:

When the switch is closed the inductor will resist the flow of electrons until it stabilises. At this point the magnetic field is as big as it can be for the current passed. (The resistor is there to represent minor resistance caused by the inductor; as it's made of wire it'll have some but it could be far less than 1 ohm). The switch being closed, the point labelled A will have a positive potential and B a negative. Having a negative at B and positive at A the diode is in a position where it does nothing, so long as the PIV is greater than the voltage supplied.

BUT- according to Lenz's Law (which, if you want to show off , you can say  is the electrical equivalent to Newton's Third Law; but if you do don't blame me if the fifth form de-bag you and throw you in the bushes for being a swot) when the switch is turned off then point A will have a negative potential and point B a positive one. Oh dear, because the other side of the switch is still connected to the battery and has a positive potential.

Diode Stuff.


A diode can block a voltage travelling in one direction  but lets it through in the other. The blocking end is usually marked with a stripe. A voltage applied to the blocking end is a voltage going in the reverse direction.



The PIV of a diode stands for Peak Inverse Voltage and it is the maximum that a diode can block in the reverse direction. If the PIV is exceed then the diode will behave like a wire and offer no resistance. If the excess is not too big the diode will recover, if it is too big the diode will be destroyed.





Lenz's Law


An induced electromotive force (emf) always gives rise to a current whose magnetic field opposes the original change in magnetic flux.



Newton's Third Law


Lex III: Actioni contrariam semper et æqualem esse reactionem: sive corporum duorum actiones in se mutuo semper esse æquales et in partes contrarias dirigi.


And for those of you who are now thinking "Look, Lang, stop being such a girly swot and give us that in English, you great poser ":


For every action there is always an equal and opposite reaction: or the forces of two bodies on each other are always equal and are directed in opposite directions.





Were the diode not there, this would mean trouble because although there is no longer a physical contact in the switch a high enough difference in potential can cause an arc. Electricity needs 30,000 volts per centimetre to get an arc under perfectly dry conditions; air is never perfectly dry and it's much much less than that distance and voltage. A sufficiently big arc won't do that switch any good. At best it'll cause a burn on the contacts making them less conductive. It could weld them together. At the very worst, it'll blow up.


In our circuit there is no switch as such but what there is is Bipolar Junction Transistor (BJT) which does not require very much to destroy it at all. The diode is there to stop this happening. The point B being positive finds a much easier path through the diode than it does through the air gap of a closed switch or indeed through a non-conducting transistor and so there it all goes, and from there back into the inductor, (hence flyback) where eventually it gets dissipated as heat and resistance losses. The process takes a few milliseconds until the energy is snubbed (hence snubber) or caught (hence catcher). Don't ask me why it's also called "freewheeling" though. The path is illustrated by the arrows in the diagram above. I've illustrated a Schottky diode, but for low power applications such as this it needn't be and indeed we're running a bog-standard  1N4001.


Well, that's the components done, so let's look at the supplied code. I've taken the first few REM statements off, they're not relevant to the workings, and we start at the first line of actual code:




















































































The numbered lines are what we want to concentrate on as they are the ones actually giving instruction to the microprocessor. The rest are REM statements.


Line 1  assigns a variable called motorpin the value of 9. This is the pin that the base of the transistor is connected to via the resistor.

Line 2 begins void setup ( ) which, you'll remember, only runs once when power is applied.

Line 3 defines motorpin (which has the value of 9 from line 1) as the output pin.

Line 4 closes void setup ( ) and line 5 opens void loop ( ) which as you know runs continually.

Lines 6, 7 & 8 call the subroutines. You will see that two of them are marked // and they will not run like this. if you delete the // from them, and re-upload, these routines will run. Similarly if you mark  motorOnThenOff(); with // it will not run.

Line 9 denotes the beginning of the subroutine motorOnThenOff ( )

Line 10 marks a variable giving the time the motor stays on, line 11 the same for the motor off.

Lines 12-14 turn the motor on, keep it on, turn it off, keep it off and as the command digitalWrite is used the motor will turn at full speed. Line 16 closes this subroutine.

Line 17 denotes the beginning of the subroutine motorOnThenOff WithSpeed( )

Line 18 and 19 define the variables that will run the motor at a higher speed for 2.5 seconds whilst 20 and 21 do the same for a lower speed for 1 second.

Lines 22-25 use these variables to turn the motor, and line 26 closes the subroutine.

Line 27 opens the subroutine motorAcceleration ( )

Line 28 sets the variable used to determine the time between each succesive step of acceleration of the motor. if you want this to be longer, increase the numeric value and remember it is in milliseconds.

Line 29 sets up a for/next loop  with variable i which will increase the speed of the motor from stopped to full speed

Line 30 sets an analogWrite command to determine the speed of the motor based on the value of the variable i at the time and tells pin 9 (motorpin) to set to this step. This isn't a true analogue signal, it's actually pulse width modulation which we'll discuss afterwards. To the motor though, it looks just like analogue.

Line 31 waits 0.05 seconds before continuing the loop and line 32 closes it. By this time the motor is running at its highest speed.

Line 33 to 36 do exactly the same except that this time i starts at 255 and every time the loop goes round, i gets 1 subtracted from it. This means that in the command analogWrite (motorPin, i) the value of the step is getting lower, and thus the analogue voltage that the motor sees is getting lower. The speed of the motor depends on the voltage, and so the motor decelerates (or slows down).

Line 37 closes this subroutine.



In the above I mentioned it is not true analogue causing the motor to speed up or slow down, but PWM or Pulse Width Modulation. In power delivery terms, you switch a pulse on and off very rapidly. You have a pulse window of a fixed time of  x nanoseconds, and the pulse has a duty cycle consisting of an on (mark) time and off (space) time which occurs within the timeframe of this window. The width of the mark compared to the space corresponds to a particular value of an AC voltage, and so working it backwards our AC voltage supplied to the motor corresponds to the width of the mark compared to the space. The longer the mark compared to the space, the more power delivered. It generates an AC voltage because there is a rise and fall in the power delivered, and the motor is in fact turning off and on, but because it is happening so fast  it looks to us like it's turning constantly.


Right, time to mess about a bit!



int motorPin = 9;  // define the pin the motor is connected to

                   // (if you use pin 9,10,11 or 3you can also control speed)



* setup() – this function runs once when you turn your Arduino on

* We set the motors pin to be an output (turning the pin high (+5v) or low (ground) (-))

* rather than an input (checking whether a pin is high or low)


void setup()


pinMode(motorPin, OUTPUT);




* loop() – this function will start after setup finishes and then repeat

* we call a function called motorOnThenOff()



void loop()                     // run over and over again








* motorOnThenOff() – turns motor on then off

* (notice this code is identical to the code we used for

* the blinking LED)


void motorOnThenOff(){

  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offTime = 1000; //the number of milliseconds for the motor to turn off for


  digitalWrite(motorPin, HIGH); // turns the motor On

  delay(onTime);                // waits for onTime milliseconds

  digitalWrite(motorPin, LOW);  // turns the motor Off

  delay(offTime);               // waits for offTime milliseconds




* motorOnThenOffWithSpeed() – turns motor on then off but uses speed values as well

* (notice this code is identical to the code we used for

* the blinking LED)


void motorOnThenOffWithSpeed(){


  int onSpeed = 200;  // a number between 0 (stopped) and 255 (full speed)

  int onTime = 2500;  //the number of milliseconds for the motor to turn on for


  int offSpeed = 50;  // a number between 0 (stopped) and 255 (full speed)

  int offTime = 1000; //the number of milliseconds for the motor to turn off for


  analogWrite(motorPin, onSpeed);   // turns the motor On

  delay(onTime);                    // waits for onTime milliseconds

  analogWrite(motorPin, offSpeed);  // turns the motor Off

  delay(offTime);                   // waits for offTime milliseconds




* motorAcceleration() – accelerates the motor to full speed then

* back down to zero


void motorAcceleration(){

  int delayTime = 50; //milliseconds between each speed step


  //Accelerates the motor

  for(int i = 0; i < 256; i++){ //goes through each speed from 0 to 255

    analogWrite(motorPin, i);   //sets the new speed

    delay(delayTime);           // waits for delayTime milliseconds



  //Decelerates the motor

  for(int i = 255; i >= 0; i--){ //goes through each speed from 255 to 0

    analogWrite(motorPin, i);   //sets the new speed

    delay(delayTime);           // waits for delayTime milliseconds



















































































Those of you who don't have any previous form in programming might be all at sea with some of the jargon involved. Here is your guide to some of the terms:




A variable is a named 'space'  in which we can store a piece of data.  In our example here the data is all numeric, and so for example;

x = 0


x is the variable, and this time it equals zero. But if we say at some point in the program:




we add 1 to x, making it now equal 1. If we did that 12 times, x would equal 12 at the finish, but inbetween it would be 2,3,4, etc all the way up to 12. Its value varies as we tell it to.




An array is a variable that has been subdivided into a row of variables. They all have the same name but each has a number position too. So if we had done that with x above, we'd have x[1], x[2],x[3] and so on. In general we tell an array the data it's going to have beforehand.

If you look at the code here you'll find two arrays; they're called   "uprange"   and "downrange".


For/Next Loop


A For/Next Loop has a numeric value which tells it how many times the loop should go round before going on to the next piece of code after it. All the code inside the For/Next Loop will be processed every time the loop goes round but not once the loop has been exited.



REM Statement


A remark put there by the programmer to denote what that particular piece of code is doing. It's ignored by the processor.




A set of code to carry out a specific instruction; the next  subdivision down from a program.




This is how the Americans spell analogue, they don't seem to like the letter U do they?  An analogue signal takes a continuous form and climbs or falls at a smooth rate, rather like a sine wave. This means you can have an infinite number of measurements for an analogue signal depending on where it is, and you need to go into differential calculus to get into the smallest measurements of position against time.




Digital signals rise and fall in discrete steps. If an analogue signal was 0-64 of whatever units, it could be any number between those parameters at a point in time. The digital will always be an integer 0,1,2,3.....36,37,38.....63,64

More> Copy & Paste Code from Here: