# Lab 4: Motors

## Topics

1. First Build
2. Hardware Theory
3. Software Theory
4. Exercise

## 1. First Build

You can collect a LEGO motor with cable, a transistor and a diode from the instructor.

You will know you got this sketch right if the motor spins at two different speeds.

### 1.1 The Circuit

Build Notes:

• Diode:  black with a gray stripe on negative end. It looks like it's backward in this diagram, but it serves an important purpose.
• Transistor:in the sample circuit layout on the right, the N represents the round back of the transistor. The flat side should face away from the Arduino in the breadboard diagram below.
• Motor: The black and white wires power the motor. it doesn't matter which wire goes where. Swapping wires changes the motor's direction of rotation. The other four wires are for meauring the motor's position.

### 1.2 The Code

The code for the motor sketch:

```/*
* Arduino Experimentation Kit Example Code
* CIRC-03 .: Spin Motor Spin :. (Transistor and Motor)
*
* Modified Oct 11 2011 by Alex Clarke.
*/

// constants
const int motorPin = 9;// prototypes for user defined functions
void motorOnThenOff();void motorTwoSpeed();void setup(){  pinMode(motorPin, OUTPUT);}void loop(){  //motorOnThenOff();
motorTwoSpeed();
}

/*
* motorOnThenOff() - turns motor on then off
* Notice we use digital writes,
* just like with LEDs.
*/
void motorOnThenOff(){  const int onTime = 2500; //the number of milliseconds for the motor to turn on for
const 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
}

/*
* motorTwoSpeed() - turns motor on then off but uses speed values as well
* Notice we use analog writes to set motor speeds,
* just like with LED brightness.
*/
void motorTwoSpeed(){  const int onSpeed = 200; // a number between 0 (stopped) and 255 (full speed)
const int onTime = 1000; //the number of milliseconds for the motor to turn on for

const int offSpeed = 27; // a number between 0 (stopped) and 255 (full speed)
const int offTime = 2500; //the number of milliseconds for the motor to turn off for

analogWrite(motorPin, onSpeed); // turns the motor
delay(onTime); // waits for onTime milliseconds
analogWrite(motorPin, offSpeed); // turns the motor Off
delay(offTime); // waits for offTime milliseconds
}

```

## 2. Hardware Theory

So far we've been able to do what we want with the Arduino's input and output pins. They're fine for controlling low current devices. Some devices, like electric motors, require more power. If you try to drive these devices with the Arduino's pins, the devices may not work, and the Arduino's pins will soon break. To use high current devices you need the ability to control the +5V supply. One component in your kit that allows you to do this it the transistor. Transistors are solid state devices that use a small current to control a much larger current.

### 2.1 Electric Motors

Many electronics kits come with a toy electric motor similar to the ones used in RC cars:

You will be using a LEGO motor instead. It operates on the same principles as any electric motor, but it has additional circuitry, gears and casing to make it more useful.

Electric motors move because of magnetism. They contain permanent magnets surrounding a freely spinning electromagnet core. An electromagnet is a piece of iron with wire wound around it. Brushes connect this wire to the two wires sticking out of the motor. When current passes through the wire the core becomes magnetic. Because the core can spin freely it will move so it aligns with the magnets surrounding it. There is a mechanism that switches the current's direction so that the electromagnet never quite lines up with the permanent magnets causing the motor to keep spinning as long as there's a strong current.

Electromagnets can be used to generate power. This is a property of coils of wire, or inductors. Because of this you have to take precautions when you use them to prevent doing damage to sensitive components in the circuit. When you try to turn off an inductor it turns its magnetic field  back into voltage, but the poles are reversed. This happens very quickly and the voltage can be very high - up to 10 times the source voltage. If you don't do something to dissipate the energy safely it can cause sparks to fly between wires, or it can cause surges of power to pass through electrical components like the transistor in this week's circuit or your Arduino's pins. Diodes are used in a special configuration to dissipate these power surges.

### 2.2 Diodes

As you have learned, diodes only allow electricity to pass through them in one direction. The positive end is the anode and the negative end is the cathode. Diodes are made of semi-conductors, usually silicon. There are two "flavors" or dopings of silicon inside, a p-type (positive) doping for the anode and an n-type (negative) for the cathode. The side by side arrangement of differently doped semiconductors only allows electricity to flow in one direction.

This property is being exploited in this circuit to protect the transistor. A diode placed parallel to an inductor and backward to the normal flow of electricity in a circuit is called a flyback diode. When current is flowing through the circuit, the diode does nothing because it is backward. When the current stops the inductor produces a strong reverse voltage. The diode connects the two ends of the inductor and forms a low resistance loop - a flyback loop. The reverse power surge will go round and round this loop until it dissipates.

You can see a flyback diode in action if you replace the regular diode with an LED. Don't do this for too long though or you may cause damage. Flyback diodes have very low forward voltage, usually less than 1 volt. LEDs typically have a forward voltage of 1.7 volts.

### 2.3 Transistors

Transistors are awesome multipurpose components. Their invention enabled the modern era of electronics. Transistor casings seem easy to identify, but be careful. Some integrated circuits use the same casing, like the temperature sensor on your Danger Shield. If you look carefully at the flat side you should see an inscription like the one pictured below. If you see TMP on it, then you have the wrong part.

The transistor in this circuit is an NPN transistor, the 3904. NPN stands for negative positive negative which is their internal silicone structure. They are a bit like two diodes that share the same positive terminal or anode. When you apply a charge to the base (the middle of the NPN sandwich), it allows current to flow across the transistor. This current can only flow in one direction. The positive side of this flow is the collector and the negative side is the emitter. A small amount of current applied to the base can allow very large amounts of current to flow from the emitter to the collector.

Different transistors have different pin arrangements. The ones in your kit have a very natural arrangement. The picture below shows the collector, base, and emitter on both your transistor and the NPN transistor symbol.

There are many types of transistors. The 3904 has a cousin, the 3906. It is a PNP transistor. PNP transistors are the precise reverse of NPN transistors. They allow current to flow from the emitter to the collector and are activated by grounding the base. You shut them off by bringing the base high.

### 2.4 Temperature Sensor

The other transistor-like component in your ARDX kit is actually a complicated integrated circuit (IC) that can sense temperature. If you put it in a 5V circuit it will provide a voltage based reading that is related to its temperature.

You need to know some properties of the sensor (datasheet here) to convert its output to a temperature in degrees:

• Conversion factor: A 10mV change in this component is equivalent to a 1°C change in temperature. That means there's 0.01 V/°C. To convert from Volts to Celsius you need to invert that value: 100°C/V
• Offset: 0V represents -50°C. We have an offset of -50°C.
This suggests the following equation:
temperature_in_celsius = output * conversion_factor  - offset
temperature_in_celsius = output * 100 - 50

## 3. Software Theory

### 3.1 Functions

If you look at this week's sample code, you will notice that loop() has almost no code in it. All the work is being done by user written functions. You can use comments to easily change whether the motor is dual-speed or simply on-off.

Functions are really nothing new to you. You defined the behaviour of a function every time you wrote a loop() or setup(). You have been using or calling functions to do almost everything you have done with your Arduino. Some functions, like digitalWrite() and tone(), are commands that perform an action that is controlled by arguments. These are called void functions.  Others functions, like analogRead() and map(), provide you with information that your can use later in your sketch. These are called value returning functions. Both types of functions are meant to hide the messy details of a complicated task and give it a useful name.

User written functions are often declared before they are actually used/called. This forward declaration is also known as a function prototype. The general syntax of a function prototype is:

`returnDataType functionName(ParameterList);`
• returnDataType: If a function is a value returning function, the returnDataType will be something like int, float, or char and so on. If the function is a command that does not return any value, we use the word void for the return data type.
• functionName: this is what you will call your function. It should begin with a letter. After that it can contain letter, numbers and underscores but not spaces.
• ParameterList: a comma separated list of data types and variable names. These are the slots for arguments to the function. You can have no parameters, or several.

Once a function is declared, it must be defined somewhere in the program. The definition of a function has the following general format:
`returnDataType functionName(ParameterList){ Statements . . . return data; //only if returnDataType is not void! }`
The first line is a restatement of the prototype without the semicolon at the end. The rest of the function is a sequence of commands. If your function has a non void return type, your function must return a value. The function ends when a return statement is reached, even if there are more lines of code that follow.

#### Example of Void Function With Arguments

In the First Build sketch we have two very simple functions that take no arguments and return no value. Let's look at one of them, motorOnThenOff():

Prototype:
`void motorOnThenOff();`

Call:
`void loop(){ motorOnThenOff();}`

Defintion:
`void motorOnThenOff(){ const int onTime = 2500; //the number of milliseconds for the motor to turn on for const 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}`

If you want to be able to control the motor's on and off times then you would change the function and its call like this:

Prototype:
Add parameters for the parts of the function you want to control.
`void motorOnThenOff(int onTime, int offTime);`

Call:
Add arguments to the function. Their values will be copied into the function's parameters. You can use different arguments each time you call a function.
`void loop(){ motorOnThenOff(2500, 2500); //Change the arguments to change on and off times}`

Defintion:
Add parameters the first line. Those can now be used as variables inside the function. In this example the parameters replace the onTime and offTime constants, so delete the lines where they are declared.
```void motorOnThenOff(int onTime, int offTime){ const int onTime = 2500; //the number of milliseconds for the motor to turn on for
const 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
}```

#### Example of Value Returning Function: AnalogToVolts

Here's an example of a program that uses a value returning function:

```/*
* Analog to Volts Function Demo
* Created Oct 2011 by Alex Clarke.
*/

// Function Prototype

Serial.println(volts);}// Function Definition
float AnalogToVolts(int reading){  float volts;  volts = reading/1023.0 * 5.0;  //Perform conversion
return volts; //Return result
}
```

## 4. Project

### Part 1:  International Temperature Controlled Fan

In this exercise you will build a very slow fan that turns on when the temperature passes 27°C.
• Add a temperature sensor to the First Build circuit and connect its output to pin A0.
• Write a sketch that:
• reads the output from the temperature sensor
• converts that reading to volts using the AnalogToVolts() function from the notes
• converts the the result in volts to a temperature in degrees Celsius
• prints the temperature to the Serial Monitor
• turns on the "fan" (motor with visual aid) if that temperature is higher than 28°C. The fan should be off otherwise.
• Test your sketch. Demonstrate it to the lab instructor if you have any questions.
• Use your own body heat to activate the sensor.
• Reduce the threshold if you can't warm the sensor enough to turn on the "fan"
• When the fan turns on, do you notice anything about the readings your temperature sensor gives? (If you don't notice anything try another power supply.) What do you think is happening? How would you solve this?

### Part 2: International Temperature Controlled Fan (for dummies)

Modify Part 1 so that it prints temperatures in Fahrenheit for the Americans.