Lawrence Technological University
College of Arts and Science
Department of Mathematics and Computer Science

## Notes for Arduino Platform Summer Camp activities at LTU, 2012

### by John M. Miller M.D.

 You may be familiar with the idea of open-source software. The Arduino is open-source software on open-source hardware. Most previous development boards or prototyping platforms were tailored to sell one particular micro-controller and encouraged the use of peripheral chips sold by the same company. The Arduino approach allows you to use working solutions from a large number of sources, modify them to suit your purposes, and re-assemble them to solve any problem that you want to work on.

The Arduino camp activities are spread over a few sessions

General introduction, hours:

1. What's a micro-controller, what's an Arduino? A micro-controller is just a small computer that has been dedicated to controlling some physical process. As an example, we will try to turn on a fan if the room is too hot and turn off the fan if we are no longer working or moving about in the room. Of course we can already do this with our hands. Can we have the Arduino do this for us? The Arduino project has made it quite a bit easier for an average student to become a hardware hacker and actually build their own solution to a problem like this. Getting started:
2. Electrical safety and measuring volts, amps and watts. The voltages on the Arduino board, 5 volts, 9 volts and 3.3 volts are pretty safe for a person to touch with their bare hand. But our little project is about controlling something plugged into a wall outlet. Trying to move electricity efficiently over distances, power companies have settled on 120 volts alternating 60 times per second. Dry skin resists low voltages pretty well, but 120 volts not so well. Safety for tissues with electricity running through them follows a U shaped curve with the bottom of the valley (unfortunately for us) at just about 60 cycles per second. So we have to be careful and learn a little about electricity and electronics:
• Ohm's law. E = I × R or voltage = current × resistance. One Volt will move one Ampere of current through one Ohm of resistance. For our purposes here the analogy with water flow is helpful: The same water pressure will push more water through a big pipe (lower resistance) than through a smaller pipe (higher resistance.)
• Power. P = E × I or power = voltage × current. 1 Watt = 1 Volt moving 1 Ampere of current. 60 Watts = 120 volts moving 0.5 Ampere of current. Power is what the power company charges us for and what we are trying to conserve by turning the fan off when it is not needed. How much does it cost to run our desktop fan?
```>> # A calculation in interactive Ruby using the last DTE Energy bill.
?> # \$ 55.70 for 404 Kilo Watt Hours
?> rate = 55.70 / 404
=> 0.137871287128713
>> # About 14 cents per KWH.
?> # From the label on bottom of fan 0.8 amps.
?> # From multimeter fan on low 0.2 amps, on high 0.3 amps.
>> high_amps = 0.3
=> 0.3
>> hours_in_day = 24
=> 24
>> volts = 120
=> 120
>> watts = volts * high_amps
=> 36.0
>> kilowatts = watts / 1000.0
=> 0.036
>> cost_per_day = kilowatts * hours_in_day * rate
=> 0.119120792079208
>> # About \$0.10 to run this fan on high all day.
```
A digression: This is OK for the fan which draws about the same amount of power all the time. For something like a refrigerator that has a compressor coming on and going off at not easily predictable intervals the Kill A Watt EZ for about \$30 from places like Home Depot would be more convenient. Maybe after this camp you might want to try hacking a Kill A Watt EZ with the Adafruit Tweet A Watt Kit.
• Using the multimeter. The Fluke multimeter has many imitators of its functionality and many more imitators of its yellow case.
• Ohm's law in action with a multimeter, the Arduino and the resistors from our kit.
• When ground is not ground: For a three pronged plug the round prong (ground or green wire) should be connected, near the service box for the house, to the wider flat prong (neutral or white wire) and so there should be zero volts between the green and white wires. There should be 120 volts between the narrower flat prong (hot or black wire) and either the white wire or the green wire. There are many reasons the voltage between the green and white wires could be much higher than 0 -- and enough to hurt you or destroy the Arduino board, (Things like broken wires, corroded connections, wiring errors and adaptors.) A bit ago, when I was about your age and working in auto repair, I remember a lecture about never trusting a customer who said, "The brakes are fine" and always testing those brakes yourself before moving the car. I would ask when someone hands you the end of an extension cord that you assume nothing before you plug your device into it. Another digression to follow when you have had a little more experience: The Tweet A Watt design on LadyAda.net, mentioned above, is an interesting one where the hacked Kill A Watt can send data to an Arduino without having to worry if both the Kill A Watt and the Arduino are properly grounded.
3. Measuring temperature and detecting motion.
TMP36 - Analog Temperature sensor
This sensor is both easy to use and inexpensive. The tutorial page is helpful. If using the 5 volt power is not accurate enough, try the 3.3 volt sketch -- remembering to change either the analog pin connection or the tempPin variable.
PIR (motion) sensor
This sensor is also easy to use. This is a digital sensor rather than an analog sensor like the TMP36.
4. Turning 120 volt electricity on and off. There are two very important considerations:
1. The person could be injured or the micro-controller could be damaged if either comes in contact with the 120 volts. The usual manual switch has a plastic toggle or knob that insulates your hand from high voltage. The limit of that protection (in volts) is stamped on the switch. The Powertail is opto-isolated. That is a small LED is turned on with the low voltage and that light is sensed by a separate circuit that turns on the higher voltage. The separation protection is maintained up to 6000 volts.
2. The on-off switch needs to be robust enough to handle the amount of current flowing when the device is on. Our fan runs at a maximum of 0.8 amps a manual switch usually comes labeled with a capacity of 15-20 amps. The little relay switch in the Powertail II has a 20 amp capacity.
5. Soldering is one electronic construction technique we will practice along with tinning the ends of stranded wires and applying heat shrink tubing. (Maybe later we can also play with liquid electrical tapes and Sugru.) Building the Powertail II kit, we will generally follow the assembly instructions. Yet another digression on grounding: The extension cord we are splitting with our Powertail II kit follows the custom for 3-wire lamp cord -- the hot wire has a smooth side and the neutral wire has a ribbed side. Always check this with the multimeter, and don't assume the customary standard was followed. Before we screw the cover on, we will make a connector cable (out of 22 gauge speaker wire, some bits of hookup wire and some heat shrink tubing)
for the low voltage circuit and attach it to the terminal strip. Also we will add a little more strain relief to the power cords in the form of zip ties just inside the grommets and to the connector cable with a little nylon bracket.
6. Testing the Powertail II with the Arduino board connected to your laptop by the USB cable.:
1. With the Powertail unplugged, connect the - lead from the Powertail II to ground on the Arduino and connect the + lead to + 5 volts on the Arduino. The red LED on the Powertail II should light up.
2. With the Powertail II still not plugged into the wall, remove the + lead from the Arduino +5 volt pin and connect it instead to the Arduino digital output pin D3. Use the Arduino IDE to upload this sketch.
```/* powertail_cycle
A program to test the Powertail II connected to
a digital output pin.
*/

#define POWERTAIL_PIN 3

void setup() {
pinMode(POWERTAIL_PIN,OUTPUT);   // At power-up all pins are input.
digitalWrite(POWERTAIL_PIN,LOW); // Begin with Powertail OFF.
delay(1000 * 10);                // Wait 10 seconds.
}

void loop() {
digitalWrite(POWERTAIL_PIN,HIGH); // Turn Powertail ON.
delay(1000 * 10);                 // Wait 10 seconds.
digitalWrite(POWERTAIL_PIN,LOW);  // Turn Powertail OFF.
delay(1000 * 10);                 // Wait 10 seconds.
}
```
The red LED should go on and off in 10 second cycles.
3. Now plug the Powertail II in. The red LED should continue to cycle and you should hear the relay click on and off.
4. Now plug the fan into the Powertail II and turn the fan on. The fan should cycle on and off in time with the red LED.

Introduction to Arduino programming and libraries, (if you have not done so already see Getting Started above) hours:

1. Some good programming habits that apply to any development platform:
• The many wonderful examples already written for the Arduino tempt you to start by copying and pasting fragments of code until the mash-up of code seems to do what you wanted. The more innovative and complex your idea is, the more you will waste lots of time this way. Begin by describing your idea in outline form. Flow charts and pseudo-code are popular ways to do this.
• Next turn your outline into comments. Don't just add your comments as an afterthought. To your generation, a long term job may last a year. As you move to another job you will hope that the programmer you are replacing left good enough comments that you can easily understand what they were doing. Be kind kind enough to leave the code you write with clear comments that the programmer that comes after you can easily understand.
• Comments should be complete sentences and be spell-checked. Don't write comments like you write tweets.
The basic parts to each Arduino program:
1. Comments with the name, purpose and author of the program. Also include here acknowledgements of other programmers and important version history.
2. Global variables and #defines.
3. Initialization --
```void setup() {
// All the stuff to do just once at the beginning of the program.
}
```
4. The main loop --
```void loop() {
// The things to do over and over as long as the program is running.
}
```
2. Using Arduino libraries, always take a look at the Examples provided with the library. Using the serial monitor.
3. Digital output -- a blinking LED. Digital input -- the pushbutton. Analog input -- voltage with resistors and a potentiometer. Analog output -- PWM.
5. Add analog input for temperature. Report temperature to computer screen. Turn on red LED if too hot. Review the Adafruit tutorial page.
6. Turn on fan with Powertail II if too hot and turn off if motion ceases. Review the Powertail II datasheet.

An RFID/NFC demo, hours:

1. Overview of our electronic lock demonstration.
• What are RFID and NFC? Back when a microcomputer and its memory were miniaturized enough to be encased in a plastic card or key-chain fob, there developed two ways to provide power and communicate with the encased computer. One way is to use external contacts like those on USB thumb drives and SD cards. The other way is to also encase a small antenna that is tuned to a specific radio-frequency. The various types of Near Field Communication protocols are examples of this approach.
• Watch the video at http://www.adafruit.com/products/789
• What is a servo? Servos are motors where it is easy to turn the armature a set number of degrees. Low power servos can work with an Arduino without added equipment. http://www.adafruit.com/products/155
• Today we will assemble the RFID/NFC shield and add a connector for a servo. Then we can program a LEGO NXT robot to drive up to a gate controlled by our Arduino and its shield. Sensing the correct "license-plate" card taped to the front of the NXT, the Arduino should use the servo to open the gate for the NXT robot. The robot should sense that the gate is opened and drive through in less than 10 seconds.
• So far we have used just the functions built into the the Arduino IDE. This project will use 3 more libraries
1. The Wire library which comes with the IDE and handles serial communication between the Arduino and the RFID/NFC shield.
2. The Servo library which comes with the IDE and handles controlling the servo motor which opens and closes the gate.
3. The RFID/NFC library which is downloaded from Github and controls talking to the NFC chip on the shield. The Wire library can use a few different dialects of serial communication. The RFID/NFC library comes in two separate dialects -- we will download and use the I2C version as it matches the default configuration of the RFID/NFC shield.
2. Build it
• Soldering techniques.
• Assembling the RFID/NFC shield. We will use the header strips that come with the shield kit.
• Testing: Using the format example code changed to add the URL: `http://robofest.net`
```// For a http://www. url:
// const char * url = "adafruit.com";
// uint8_t ndefprefix = NDEF_URIPREFIX_HTTP_WWWDOT;
const char * url = "robofest.net";
uint8_t ndefprefix = NDEF_URIPREFIX_HTTP;
```

 Viewed through the Arduino IDE serial monitor. Using the dump example code to verify that `http://robofest.net` was written correctly on the card.
3. Use it: Open a gate for an NXT robot identified by a proper RFID card. Using code from the Adafruit_NFCShield_I2C library examples and from the built in Servo library.
```// rfidgate
// Open a gate when the proper RFID tag is presented.
#include <Servo.h>
#include <Wire.h>
#define IRQ   (2)
#define RESET (3)  // Not connected by default on the NFC Shield
#define SERVO_PWM 10
// Globals
Servo gate;   // Boom rotator.
int pos = 0;  // Boom rotator position.

void open_gate()
{
gate.write(90);
}

void close_gate()
{
gate.write(0);
}

void setup(void) {
Serial.begin(115200);
Serial.println("Hello!");
nfc.begin();
gate.attach(SERVO_PWM);   // Boom rotator servo on pin 10.
close_gate();             // Initial position closed.
delay(10000);
// Check that shield is connected.
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // Halt on error!
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

// configure board to read RFID tags
nfc.SAMConfig();
}

void loop(void) {
boolean success;
uint8_t tid[] = { 0x9e, 0x35, 0x7b, 0xd3 };  // Target card ID.
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
Serial.println("Waiting for an ISO14443A card");
// Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
// 'uid' will be populated with the UID, and uidLength will indicate
// if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
if (success) {
Serial.println("Found a card!");
Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print("UID Value: ");
for (uint8_t i=0; i < uidLength; i++)
{
Serial.print(" 0x");Serial.print(uid[i], HEX);
}
Serial.println("");
for (uint8_t i=0; i < uidLength; i++) {
if (uid[i] != tid[i]) success = false;
}
if (success) {
Serial.println("Enter");
open_gate();
delay(10000);
close_gate();
} else {
delay(5000);
}
}
}
```

 Serial Monitor view of presenting our ID card.
So our lock works pretty well. We could use it on a door at our home or even on a car door. (Well, maybe the car door is not so easy. Finding out how to provide clean power is an example of a problem where you might go to the Auduino user community for a little help.)

On your own, here are some books that would help you learn electronics with the Arduino while building some fun projects:

Pulse-Width Modulation and slow motors. Now that you have completed your Powertail II and are finished shrinking tubing with the mini heat gun, if you learn a little about PWM, your Arduino can do a nice job of roasting a marshmallow. The windings of small electric motors are pretty thin. Increasing the voltage to a motor increases the torque but runs the risk of burning up those thin windings. You need higher torque to start a small motor slowly. Years ago small motors could only start and run quickly. Fortunately PWM changed all that by providing full speed voltage for a small fraction of a cycle. Now we can turn a marshmallow on a spit slowly and evenly enough to get it a nice golden brown outside and soft inside. The Motor Shield from Adafruit makes this speed control easy. Even the tiny stepper motor to turn a marshmallow needs more power than can be borrowed from your laptop through the USB cable. For this project we will get the extra power from the 9 volt wall plug adapter.

```#include <AFMotor.h>

AF_Stepper motor(48, 1);

void setup() {
motor.setSpeed(6);  // 6 rpm
}

void loop() {
motor.step(100, FORWARD, SINGLE);
}
```
Maybe we will add an on-off switch as well. (ladyada.net on pushbuttons.) Or maybe since the mini heat gun already has a nice on-off switch we should make a circuit to sense when the mini heat gun is turned on and start turning the marshmallow automatically? (The multimeter and CircuitLab.com can help.)

Revised July 18, 2012