Chapter 11. Physical Feedback

Although there are projects that allow us to alter an aspect of reality as it confronts us (the Parallel Tracking and Mapping project at the Oxford Robots Lab or the ARToolkit library come to mind), nothing can replace the richness of the actual physical sensation of the world around us. This includes, of course, both the sound and the images of the world around us, as discussed in earlier chapters, but too often the easily manipulated senses are the only ones that interaction art and design addresses. Any industrial or product designer, architect, or sculptor can tell you about the emotional and cognitive effects that the physical product has upon us. Objects that are carried, lifted, or felt; that change the nature of space around us; or that let us change the nature of the space around us engage us differently than those that do not.

When you’re thinking about creating physical feedback, you’re thinking about using mechanics and about creating machines. More than any other topic in this book, physical feedback involves thinking about and using the practices of mechanical and electrical engineering and coupling them with programming. Luckily for you, the Arduino community on the bulletin boards is very knowledgeable and helpful in answering questions about these sorts of topics, and a host of other resources are available. This does require a slightly different approach and way of thinking, though, because you’ll need to follow along quite closely with electrical diagrams as well as copying down code. Debugging circuits is usually done using a voltmeter or, if you’re really dedicated or lucky, an oscilloscope. It’s a much different process than coding, but it has some rich rewards: enabling you to create things that move and that act in the world.

So, from the perspective of designing an interaction, how do you create good physical interaction? The rules are pretty much the same: spectrum feedback mechanisms usually should correlate to spectrum inputs, and binary feedback should correlate to binary input. User input that changes a state leads a user to expect a changed state. Thinking about this in terms of the physical environment that one or more viewers inhabit presents interesting challenges and wonderful opportunities to engage. You can explore a whole new range of senses and kinds of thinking with physical feedback, though. The feel of something, its actual sensation, or the changing of the physical space around us are all quite different sensory experiences than looking at a screen or hearing a sound. The physical nature of what a user is doing is going to shape drastically their perception of what should be happening, so the digital states of a system or an application and the physical states that the user perceives should be kept synchronized when possible.

When you design a system that presents physical feedback, it is necessary to understand and plan around every possible aspect of the physical environment of the user. The vibrate setting on my cell phone works because I keep my cell phone in my pocket. Just having a blinking light to indicate to me that my turn signal is on in my car doesn’t work because I might not be looking at the dashboard. Coupled with a clicking sound, I notice it.

Innumerable tools, from backhoes to bombs, alter our physical environment. Their actions in the environment are not intended to help a viewer or participant understand something that has occurred, to give or request information from them, or to further an exchange. Simple tools alter the world as the result of an action. Although the design and construction of such tools is fascinating, this chapter will focus on tools that use physical feedback to further an interaction or enable communication between a system and a user.

There is another element to some of the tools that we’ll be touching on in this chapter that takes the discussion outside the realm of this book, but it’s an important one nonetheless. Lots of times in physical computing there is no user, or the user really doesn’t matter much. That’s not often true with any of the other themes of interaction design that we’ve discussed so far, but it can be true with physical machines. Sometimes all the user does is watch or press a button to start a long process. That’s not the focus of this book, but it is a reality in physical computing, so it’s worth mentioning: lots of times the design of machines is pretty nonpeople-friendly, because the machine isn’t going to be interacting with people very much. However, in this chapter, we’re going to be looking at things with the assumption that someone will be actively operating or experiencing them.

Using Motors

The motor is the primary tool for creating motion. At its simplest, you can use a motor to make something spin. With a little more mechanical work, using gears and other mechanical devices, you can use a motor to make something move, vibrate, rise, fall, roll, creep, or perform almost any other type of motion that does not require precise positioning. There are several different kinds of motors: servos, stepper motors, or unidirectional DC motors. In this chapter, you’ll look at all three kinds and how you can use them. The simplest motors are good for designs that need motion forward or backward, like a remote control car or a fan, but not for things that need to move to a precise position, like a robotic arm or anything that points or moves something to a controlled position.

Motors are all around us; just look inside moving toys, and you’ll find a number of excellent motors and gears you can repurpose if you’d like. Any electronics supplier will have a wide range of motors that will suit many purposes from spinning small objects to driving large loads. In Figure 11-1, you’ll see two small motors that can be controlled by an Arduino controller and a diagram that shows how the internals of a brushed DC electric motor work.

Two small motor examples and a cutaway of another
Figure 11-1. Two small motor examples and a cutaway of another

DC Motors

In a motor, when current passes through the coil wound around the core, the side of the positive pole is acted upon by an upward force, while the other side is acted upon by a downward force. This creates a turning effect on the coil, making it rotate. To make the motor rotate in a constant direction, the current reverses every half a cycle, which ensures that the motor rotates in the same direction. To work through the example in this section, you’ll need a DC motor that runs on low-voltage DC, somewhere between 5V and 15V.

This part of the example reverses the direction that the motor spins. To reverse a DC motor, you need to be able to reverse the direction of the current in the motor. The easiest way to do this is using an H-Bridge circuit. There are many different models and brands of H-Bridge. This example uses one of the most basic, an L293E from Texas Instruments (a similar chip is the SN754410). If you simply want to turn a motor on and off and don’t need to reverse it—for example, if you’re controlling a fan—you can simply control the motor by controlling the current sent to the motor.

The example in Figure 11-2 uses an H-Bridge integrated circuit, the Texas Instruments L293E. You can find these chips or equivalent at most large electronics suppliers. This particular chip can control two motors. It can drive up to 1 amp of current and between 4.5 and 36V. If your motor needs more than that, you’ll need to use a more powerful H-Bridge.

The pinout and image of the 1293 H-Bridge chip
Figure 11-2. The pinout and image of the 1293 H-Bridge chip

There’s another component included in this circuit that you’ll need to understand: the capacitor. A capacitor is a pair of conductors (or plates) separated by an insulator (Figure 11-3), and it stores energy as an electrostatic field between the plates. Capacitance is a capacitor’s ability to store that energy. The basic unit of capacitance is the farad (F). So, you’ll see capacitors marked as 10 microFarads, or μF, as in Figure 11-4. Usually there are slight swings in the amount of current passed around a circuit. Sometimes variations in the voltages of these circuits can cause problems; if the voltages swing too much, the circuit may operate incorrectly. In the case of the motor in Figure 11-3, the capacitor smoothes the voltage spikes and dips that occur as the motor turns on and off.

The electrical symbol for a capacitor and a representation of a capacitor
Figure 11-3. The electrical symbol for a capacitor and a representation of a capacitor

Now you’re ready for the wiring diagram in Figure 11-4.

Let’s break the wiring diagram down a little bit. The switch connected to the Arduino pin 2 controls which direction the motor will turn. When the switch is high or on, Arduino pin 3 will send a low signal, and pin 4 will send a high signal. This tells the H-Bridge to send the motor one direction. When the switch is low, the Arduino pin 3 will send a high signal, and pin 4 will send a low signal, telling the H-Bridge to send the motor in the other direction:

int switchPin = 2;    // switch input
int motorPin1 = 3;    // H-bridge leg 1
int motorPin2 = 4;    // H-bridge leg 2
int speedPin = 9;     // H-bridge enable pin
int ledPin = 13;      //LED

void setup() {
    // set the switch as an input:
    pinMode(switchPin, INPUT);

    // set all the other pins you're using as outputs:
    pinMode(motorPin1 , OUTPUT);
    pinMode(motorPin2 , OUTPUT);
    pinMode(speedPin, OUTPUT);
    pinMode(ledPin, OUTPUT);

    // set speedPin high so that motor can turn on:
    digitalWrite(speedPin, HIGH);

    // this is borrowed from Tom Igoe and is a nice way to debug
    // your circuit, if the light blinks 3 times after the initial
    // startup that's probably an indication that the Arduino has reset itself
    // because the motor caused a short
    blinkLED(ledPin, 3, 100);
}

void loop() {
Wiring the motor and H-Bridge
Figure 11-4. Wiring the motor and H-Bridge

If the switch is set to high, the motor will turn in one direction:

    if (digitalRead(switchPin) == HIGH) {
        digitalWrite(motorPin1, LOW);   // set 1A on the H-bridge low
        digitalWrite(motorPin2, HIGH);  // set 2A on the H-bridge high
    }

If the switch is low, the motor will turn in the other direction:

    else {
        digitalWrite(motorPin1, HIGH);  // set 1A on the H-bridge high
        digitalWrite(motorPin2, LOW);   // set 2A on the H-bridge low
    }
}

// this method just blinks an LED
void blinkLED(int whatPin, int howManyTimes, int milliSecs) {
    int i = 0;
    for ( i = 0; i < howManyTimes; i++) {
        digitalWrite(whatPin, HIGH);
        delay(milliSecs/2);
        digitalWrite(whatPin, LOW);
        delay(milliSecs/2);
    }
}

Now that you know how to wire a motor, you can begin to use a motor to create motion in any of your projects. If you’re looking to use a motor to drive a more complex motion, you’ll probably need to use some gears or wheels in different kinds of configurations. A number of websites worldwide sell tracks, wheels, and gear and axle kits.

Stepper Motors

Stepper motors operate differently from normal DC motors. Instead of just rotating when voltage is applied to their terminals, they have multiple toothed electromagnets that are given power by an external control. To make the motor shaft turn, first one electromagnet is given power, which makes the gear’s teeth magnetically attracted to the electromagnet’s teeth. When the gear’s teeth are thus aligned to the first electromagnet, they are slightly offset from the next electromagnet. When the next electromagnet is turned on and the first is turned off, the gear rotates slightly to align with the next, and so on, all the way around the gear. Each rotation is called a step, with an integral number of steps making a full rotation that lets you set the position of the motor to a precise angle.

To work with a Stepper motor and an Arduino, you’ll probably need to use a chip to control a stepper, called a driver, like the one pictured in Figure 11-5.

A stepper motor driver and connecting it to the Arduino
Figure 11-5. A stepper motor driver and connecting it to the Arduino

The driver lets the Arduino control the motion of the motor with pin 3 connected to the Step input as marked on the diagram and pin 2 connected to the Dir input as marked in the diagram. To power your motor, you’ll send the current to the pin on the EasyDriver marked +V. How much current you’ll need to send is dependent on the motor that you’re using, so check the datasheet for your motor.

The Arduino code to control a stepper motor looks like this:

int dirPin = 2;
int stepperPin = 3;

void setup() {
    pinMode(dirPin, OUTPUT);
    pinMode(stepperPin, OUTPUT);
}

void step(boolean dir,int steps){
    digitalWrite(dirPin,dir);
    delay(50);
    for(int i=0;i<steps;i++){
        digitalWrite(stepperPin, HIGH);
        delayMicroseconds(100);
        digitalWrite(stepperPin, LOW);
        delayMicroseconds(100);
    }
}

void loop(){
    step(true,1600);
    delay(500);
    step(false,1600*5);
    delay(500);
}

Another option is to use the Stepper library that comes with the Arduino IDE distribution. You can find examples of using this library both on the Arduino site and on the MAKE magazine site at makezine.com. Anything that you need to move a very controlled amount, such as a camera, a light, a small door, a slide for a slide whistle, can all be controlled with a stepper motor.

In the next section, we’ll look at servo motors, which are quite similar but have a few differences from a stepper motor. A servo is much smoother and better for continuous motion, while stepper motors can much more easily lock into fixed positions and can hold those fixed positions with much greater torque than a servo, making them more appropriate for moving into preset positions. You can see stepper motors at work in printers, laser cutters, tool and die machines of all flavors, as well as throughout industrial production lines.

Other Options

Another option for working with stepper motors is a motor shield from Adafruit Industries, shown on the right in Figure 11-6. As of the writing of this book, the motor shield supports two smaller (5V) servos, up to four bidirectional DC motors, and two stepper motors, as well as providing a block of connectors to easily hook up wires (10-22AWG) and power. These are worth looking into because they simplify working with multiple motors.

Pololu is a robotics supply company, which is also making motor drivers, as shown on the left of Figure 11-6, that can be used to drive stepper and bidirectional motors. While the boards made by Pololu are more versatile, the AdaFruit shield is much more Ardunio-ready. If any of these different tools is appropriate for your project, that is dependent of course on how much you can spend.

Two different motor driver shields
Figure 11-6. Two different motor driver shields

Using Servos

The motor is not, on the face of it, an interactive element; it is a reactive element. For example, I turn the key, and my car turns on. But motors are important and relevant to interaction and interactivity because working with motors and servos allows you to make the first step into the one of the most important areas of human computer interaction and computing: robotics. Now, given the space constraints that I frequently mention, it’s impossible for us to delve too deeply into robotics, but it is quite easy to show some of the basics of controlling a servo and creating programmable motion.

A servo is a type of motor but with a few added advantages. It, like the motor, receives a PWM signal that it uses to power itself; however, a servo reads the amount of voltage passed in to determine how far to rotate within a limited range. The most common range for a servo motor is 180 degrees, and the servo can move from any point in that range to any other point clockwise or counterclockwise, making it a powerful tool for controlling anything that needs a controllable, repeatable movement. Robots, puppets, cars, and in fact most automated machinery make extensive use of servos. For our purposes in this chapter, we’ll be looking at small servos, but you are encouraged to think big. One of the really wonderful aspects of servos is that though there are many to choose from with different sizes and performance, the signals used to control the servo are almost always the same, meaning that you could apply the same code to move a small hobbyist servo as you would to move a very large servo.

Now, although this won’t quite make sense until we look at code to control the servo, it’s worth mentioning here that the PWM pin on the Arduino control isn’t set at the correct frequency to control a servo motor. That means that we can’t write simple instructions to tell a servo to move to a certain position. We have to send the servo a 5V pulse where the duration of the pulse tells the servo to move to a given position. This isn’t as difficult as it sounds, although it does make our code a little strange. But don’t worry, because it will be explained in full.

Connecting a Servo

To connect a servo motor to the Arduino controller, you need to provide the servo with power from the 5V pin on the Arduino controller, to ground the servo, and to send commands to the servo PWM port. Now, as we mentioned, the PWM port of the Arduino controller doesn’t operate at the proper frequency to communicate with a servo. If you’re savvy with AVR microcontrollers, the chip that the Arduino uses, and C programming, you can change it, but that’s beyond the scope of this book and isn’t necessary to communicate with the servo.

Communicating with the Servo

To control the servo, you send it a command every 20 milliseconds. The servo responds to a short pulse (1ms or less) by moving to one extreme, and it moves around 180 degrees in the other direction when it receives long pulses (around 2ms or more). The amount that the servo moves is determined by the length of time that the pulse is sent to the servo (Figure 11-7). You should be aware that there is no standard for the exact relationship between pulse width and position; different servos may need slightly longer or shorter pulses.

Positioning a servo using the pulse width or duration
Figure 11-7. Positioning a servo using the pulse width or duration

Servo motors have three wires: power, ground, and signal, as Figure 11-8 shows. The power wire is typically red and should be connected to the 5V pin on the Arduino board, though some servo motors require more power than the Arduino can provide. The ground wire is typically black or brown and gets connected to a ground pin on the Arduino board. The yellow (or white) wire of the servo goes to the digital pin that you’re using to control the servo. In Figure 11-8 it’s pin 9, and the red and black wires go to +5V and ground, respectively.

Connecting an Arduino to a servo motor
Figure 11-8. Connecting an Arduino to a servo motor

Wiring a Servo

As you’ll see in the code snippet that follows, controlling a servo is really just a matter of determining how long in microseconds you need to send each command to the servo. Sending commands to the servo is a matter of writing a pulse to the motor that is the desired length. In this example, a value between 0 and 180 degrees (followed by a nondigit character) is sent using the serial connection to a computer to the servo. For example, 180 microseconds will move the servo fully in one direction, and 0 microseconds will move it fully in the other:

int refreshTime = 20;
int command;
int pulseWidth = 1500; // this is the default value
long lastServoPulse;

int servoPin = 9;

void setup(){
  pinMode(servoPin, OUTPUT);
}

void loop(){
    if(Serial.available()){
        command = Serial.read(); // get the keyboard input
        if(command > '0' && command < '9')
            command = command - '0';
        else{
             pulseWidth = (command * 9) + 700; // get the right amount of time
             command = 0; // reset to get ready for the next command
        }
    }
    sendPulse();
}

void sendPulse(){
    if(millis() - lastServoPulse > refreshTime) {
        digitalWrite(servoPin, HIGH);
        delayMicroseconds(pulseWidth);
        digitalWrite(servoPin, LOW);
        refreshTime = millis(); // make sure we only update at the right moments
    }
}

Many objects that you want to turn or rotate can be manipulated with a servo, cameras, mirrors, directed lighting etc. To control these kinds of movement there’s an easy correlation between a potentiometer and a servo; turn the potentiometer, and the servo turns. You can use buttons as well, both to set the servo to a preset position or by turning the servo as the button is held down. Other input devices that can be matched to a servo are infrared and ultrasonic sensors, which were covered in Chapter 8.

Another way of programming the servo is to use the Servo library, which is included with the Arduino IDE. This library provides a somewhat easier way of communicating with the servo motor.

This library lets an Arduino board control one or two RC (hobby) servo motors on pins 9 and 10. Servos have integrated gears and a shaft that can be precisely controlled. Standard servos let the shaft be positioned at various angles, usually between 0 and 180 degrees. Continuous rotation servos let the rotation of the shaft be set to various speeds.

This library uses functionality built in to the hardware on pins 9 and 10 (11 and 12 for the Mega) of the microcontroller to control the servos without interfering with other code running on the Arduino. If only one servo is used, the other pin cannot be used for normal PWM output using analogWrite(). For example, you can’t have a servo on pin 9 and PWM output on pin 10.

The Servo library provides three methods:

attach()

Starts reading the Servo instance on the pin passed in to the method and has the following signatures:

servo.attach(pin)
servo.attach(pin, min, max) // optionally set the min and max pulse widths
write()

Writes a value to the servo. On a standard servo, this will set the angle of the shaft (in degrees). On a continuous rotation servo, this will set the speed of the servo (with 0 being full speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

read()

Reads the current angle of the servo (the value passed to the last call to write()).

To start the Servo library, declare an instance of it in your application code:

Servo servoInstance;

In this example, a potentiometer is attached to analog pin 0, and then the value from the potentiometer is used to set the position of the servo:

#include <Servo.h>
Servo myservo;  // create the servo object

int potpin = 0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin

void setup()
{
    myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
    val = analogRead(potpin); // reads the value of the potentiometer
        //(value between 0 and 1023)
    val = map(val, 0, 1023, 0, 180);// scale it to use it with the servo
        //(value between 0 and 180)
    myservo.write(val); // sets the servo position according to the
        scaled value
    delay(15); // waits for the servo to get there
}

One issue to keep in mind is that when you send a command to the servo, it takes a moment for the actual position of the arm to reach that point. If you want the servo to go from 0 degrees to 180 degrees, you’ll probably need to send the command multiple times so that the motor can arrive at the position. In the following example by Hernando Barragan, the servo slowly rotates around its full range. Note the delay to allow the motor to move into the correct position:

#include <Servo.h>
Servo myservo;  // create servo object to control a servo
int pos = 0;    // variable to store the servo position
void setup() {
    myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
    for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
    {                                  // in steps of 1 degree
        myservo.write(pos);            // tell servo to go to position in
                                             //variable 'pos'
        delay(15);                     // waits 15ms for the servo to
                                             //reach the position
    }
    for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
    {
        myservo.write(pos);            // tell servo to go to old position
        delay(15);                       // waits 15ms for the servo to
                                              //reach the position
    }
}

Lots of different types of servo motors are available. Most have only a 180-degree turning range, but some have 1.5- and 3-turn radii. Others, like the Parallax Continuous Rotation Servo, allow for full and complete continuous rotation.

There are several different shields and boards to simplify the wiring for servo motors. The Adafruit stepper shield pictured in Figure 11-6 is among them. Driving multiple servos—for instance, to create a simple robotic arm or a piece of animatronics—can get complex quickly, and though using a board will increase the price of your project, it can also make your wiring cleaner and your assembly quicker.

Another option for working with servo motors that you may be interested in is the MegaServo Hardware Servo library developed by Michael Margolis that is available for download on the Arduino website. This library allows an Arduino board to control 1 to 12 RC (hobby) servo motors on any digital pin on a standard Arduino board or up to 48 servos on an Arduino Mega. It can be used just like the Servo library. It also allows you to control up to 48 servos on the Arduino Mega or 12 servos on the other boards. Any digital pin can be used with any servo, and pulse widths can be written and read in degrees or microseconds that makes writing the pulse widths easier.

Some experiments with servos that you might be interested in trying are creating a motion detector using several infrared motion sensors and a servo to control a webcam. By using four infrared motion sensors pointed in each of the four cardinal directions, you can determine where motion is occurring and use a servo to point a camera in that direction. You’ll need a 360-degree servo to do this. Another interesting idea is creating a drawing machine by using servos to control a pen or pencil. By pairing servos, you can have one mechanical control to change the position of the pen and another to control the location of the paper. In tandem, they would be able to draw pictures and write letters.

Using Household Currents

The Arduino controller can easily power a small LED light or a very small incandescent bulb, but to power up anything larger than that, you’ll need to use more current than you can safely run through the Arduino pins. This means that you’ll need to run the power through a separate piece of hardware called a transistor and control that piece of hardware using the Arduino controller. A transistor can act as a switch to a circuit that carries a certain amount of current, in this case, way more current than you want to allow near your Arduino pins. Normally the transistor doesn’t allow the circuit to complete, and no current flows through the high power circuit. But when the base of the transistor is turned on, the transistor completes the larger circuit, and whatever you’re powering with the big circuit turns on.

In Figure 11-9, you can see the solid-state relay with its input and output posts labeled. The input posts are attached to the Arduino so that the switch inside can be thrown by the 5V signal from the Arduino. The output posts are used to control the voltage for the larger appliance, such as a light. You can control larger voltages using a combination of a diode, a transmitter, and a relay, but an easier approach is to use a solid-state relay, which combines all three of these into a single unit and makes wiring substantially less difficult. Note that most of these are used to control AC current like household current, not DC current.

Using a solid-state relay with the Arduino controller
Figure 11-9. Using a solid-state relay with the Arduino controller

To control household AC voltages such as a standard household light, you need something like a relay to switch the high voltage and isolate it from the Arduino.

Warning

You’ll need to be very careful when following along with these instructions because you’re dealing with enough electrical current to hurt yourself and start a fire. This is important enough that it bears repeating: household current can hurt you and start fires.

Figure 11-10 shows how to hook up a household AC light to the solid-state relay.

Connecting a lightbulb and a solid-state relay to the Arduino controller
Figure 11-10. Connecting a lightbulb and a solid-state relay to the Arduino controller

The code for this can be quite simple:

int relayPin = 12; // choose the pin for the relay
void setup() {
    pinMode(relayPin, OUTPUT);  // declare relayPin as output
}

void loop(){
    digitalWrite(relayPin, LOW);  // turn relay OFF
    delay(1000);
    digitalWrite(relayPin, HIGH);  // turn relay ON
    delay(1000);
}

Beware that turning lights on and off frequently in a short span of time could burn the bulb out quickly. However, you can do more than turn lights on and off with this controller: you can control any household device as long as it does not exceed the current capacity of the relay you use.

Working with Appliances

One simple way to create physical feedback is to use preexisting appliances. There’s a great device for doing this created by the guys at LiquidWare called the RelaySquid, shown in Figure 11-11. The RelaySquid is a board that has four relays, each of which controls an extension cord with three outlets. Each relay can be individually controlled by the Arduino by sending it a digital signal.

The pins marked “Relay drive” should each be attached to the pins on the Arduino. The following bit of code assumes that relay drive pin 1 is attached to digital pin 4, that relay drive pin 2 is attached to digital pin 5, and so on. It will turn each outlet on the RelaySquid for one second and then go onto the next one:

void setup() {

    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);

}

void loop() {

    digitalWrite(HIGH, 4);
    delay(1000);
    digitalWrite(LOW, 4);
    digitalWrite(HIGH, 5);
    delay(1000);
    digitalWrite(LOW, 5);
    digitalWrite(HIGH, 6);
    delay(1000);
    digitalWrite(LOW, 6);
    digitalWrite(HIGH, 7);
    delay(1000);
    digitalWrite(LOW, 7);

}
The pins on the RelaySquid
Figure 11-11. The pins on the RelaySquid

So, beyond turning lights on and off, what can you do with the RelaySquid? For starters, you could attach a clock sensor to the Arduino and turn an appliance on or off at a specific time for home security. You could program a schedule for grow lights to turn on and off for plants. You could turn a television, a generator, or any other appliance on or off. You need to take a few things into account: some devices work well with rapid cycling, and some do not. Some types of lights work well being turned on and off quickly. In my experience, halogen bulbs work particularly well, and incandescent bulbs burn out quickly when turned on and off in rapid succession. Televisions do not work well when turned on and off quickly. A little bit of searching and asking questions on forums can save you unpleasant surprises later on.

Other preassembled components are available for switching large loads like the one shown in Figure 11-12 on the left from electronics-lab.com and the one shown on the right created at sparkfun.com.

Two shields for working with household currents: the anykit Solid State Relay Switch and the sparkfun Inline Power Control
Figure 11-12. Two shields for working with household currents: the anykit Solid State Relay Switch and the sparkfun Inline Power Control

Introducing the LilyPad Board

There’s another Arduino-compatible board that has a particular relevance to providing physical feedback: the LilyPad board shown in Figure 11-13 and developed by Leah Buechley. One of the challenges of providing physical feedback is always deciding on the scale and scope of that feedback. A signal should be appropriate to its message and also to the context in which the user finds themselves, which is why there’s a discrete vibrate setting on almost all cell phones and mobile devices. Removing this would make some signals inappropriate for their context, like a loud ringing during an opera. And so it goes with interactive design: ensuring that the correct feedback is provided for the context is a vital affordance for the user. What does this have to do with the LilyPad? The LilyPad Arduino is a microcontroller board designed for wearables and e-textiles. It can be sewn to fabric and mounted to power supplies, sensors, and actuators with conductive thread. Leah Buechley has provided code and schematics and links to several projects on her website at web.media.mit.edu/~leah/, including a turn signal jacket for bicyclists. So, the means of input and feedback can become much more subtle, becoming invisible or inaudible to anyone except the user. It also allows you to use preexisting form factors. That is, you can simply sew the LilyPad into a shirt, a jacket, a bag, or any other common object and let that object create the form of your device.

The LilyPad
Figure 11-13. The LilyPad

The board is based on the ATmega168V, which is a slightly lower-power version of the ATmega168 chip that the Arduino uses. It is programmed using the Arduino IDE just like any other Arduino device and can be powered from a USB if you either get a USB connector or use one of the USB modules for the Arduino Mini, as shown Figure 11-14.

The LilyPad to a connected to a USB programmer
Figure 11-14. The LilyPad to a connected to a USB programmer

It has 14 pins; all can be used as digital outputs, 6 can be used for analog (PWM) outputs, and 6 can be used for analog inputs. The LilyPad is also a little more fragile than a regular Arduino board, so you’ll need to be a bit careful when working with it and particularly when wiring it up. Also, the LilyPad is not particularly sensitive to water. If the LilyPad is not powered up, it can be washed with nonabrasive detergent. This doesn’t help when your project is caught in a sudden torrential rainstorm, but it does make the device a little less susceptible to the sweat, small spills, and environmental moisture that a wearable piece of technology will invariably encounter.

Using Vibration

Vibration is a simple and subtle signal that, given the correct contextualizing information, can be a great alert to a user. The LilyPad comes with a number of prebuilt components that can easily be connected either as inputs or as feedback devices, one of which is the LilyPad Vibe Board shown in Figure 11-15. This small motor works in much the same way as the vibrate motor on a cell phone. A 5V signal is enough to power the vibration motor, alerting the user to whatever you’d like to alert them to.

LilyPad Vibe Board
Figure 11-15. LilyPad Vibe Board

Since the LilyPad is generally meant to be used in a completely mobile application, you’ll need to provide power to it. One AAA battery is enough to power the LilyPad for a reasonable amount of time using the LilyPad power supply. You can also use the LiPower module with a Lithium Ion battery, shown in Figure 11-16.

Lithium Ion battery and the LiPower board
Figure 11-16. Lithium Ion battery and the LiPower board

The LiPower board is small, is inconspicuous, and lets you use a rechargeable Lithium Polymer battery like the one shown on the left in Figure 11-16. These batteries are smaller, are flatter, and last much longer than AAA cells. Simply attach a single cell for Lithium Polymer (LiPo) battery, flip the power switch, connect the LiPower battery to the LilyPad, and you have a small, portable, short circuit–protected 5V supply.

The last part of the puzzle with the LilyPad is the connection between the LilyPad and all of its component pieces. When working with an Arduino Duemilanove, most of your connections are made with 22- or 24-gauge wire or with solder. This approach doesn’t translate as well to clothing, so you might considering using a special kind of conductive thread that can be used to connect the LiPower, the LilyPad, and the Vibe Board. Conductive thread is an excellent way to connect various electronics onto clothing. It isn’t as conductive as traces on a printed circuit board, but it lets you create a complete circuit that remains flexible, near invisible, and, most important, wearable.

Note that when designing applications with the LilyPad, you should always keep your power supply and LilyPad main board as close to each other as possible. If they are too far apart, you are likely to have problems with your LilyPad resetting or just not working at all because of the resistance in the conductive thread connecting the boards. The resistance usually isn’t as big of a deal when it’s on the line connecting the LilyPad to a sensor or component, but between the LilyPad and its power supply, it makes a big difference in the reliability and durability of your project.

Figure 11-17 shows how to connect the LilyPad, LiPower, and Vibe Board.

Connecting the Vibe Board
Figure 11-17. Connecting the Vibe Board

The code to turn on the Vibe Board can be as simple as this:

void setup() {

    pinMode(1, OUTPUT);

}

void loop() {

    digitalWrite(HIGH, 1);
    delay(1000);
    digitalWrite(LOW, 1);
    delay(1000);

}

As of the writing of this book, the LilyPad has several other available types of components for input: an accelerometer, a light sensor, a temperature sensor, a button board, and an XBee-compatible breakout board for integrating an XBee antenna into a LilyPad system. Some of the other feedback options that the LilyPad provides are sound-generating buzzers and three-color LED components. At the moment, all LilyPad components are available through the Sparkfun website as well as other online retailers.

Using an LED Matrix

A light-emitting diode (LED) can indicate something to a user, it can provide recognition of a user action, or it can act as an alert. Using multiple LEDs in concert with an Arduino is usually limited by the number of digital out pins that the Arduino has. By using an LED driver chip, though, you can control up to an 8 × 8 matrix of LEDs or an eight-digit LED display. This lets you draw simple shapes, characters, and digits to begin creating simple animations.

This section is going to be rather long because of the great number of ways that you work with LEDs and in particular with LED matrices (group LEDs arranged in rows and columns). These are the three relevant libraries for working with LEDs in Arduino:

Matrix

This library enables you to work with a single LED driver.

LedControl

This library enables you to work with multiple LED drivers and newer drivers as well.

Sprite

This library allows you to create image sprites to use with the Matrix library.

Using the Matrix Library

We’ll focus on the Matrix library first. The chip and the idea of an LED matrix requires a bit of explanation. First the chip: the most common approach to drive an LED matrix, and the one that we’ll examine in this section, is to use a chip called the Maxim MAX7221 to drive the LEDs.

Figure 11-18 shows the pins of the MAX7221.

Pins on the MAX7221
Figure 11-18. Pins on the MAX7221

In Figure 11-19, you’ll see how it can be wired to an 8 × 8 LED matrix and an Arduino.

You’ll notice that the wiring from the MAX7221 looks a bit complex, but it’s actually made easier by the chip’s pin diagram in Figure 11-19. The pins on the LED matrix go from DIG 0 to DIG 7, left to right, and SEG DP (comes before SEG A) to SEG G, top to bottom.

The Matrix library allows you easily communicate with the MAX7221 chip. You can turn individual LEDs on or off, as well as setting the brightness or clearing the LED matrix. For example, to make a smiley face, you import the Matrix library and tell it which pins are connected to the MAX7221.

The constructor for the Matrix library looks like this:

Matrix mat = Matrix(2, 3, 4);

Those three parameters specify which pins are connected to the MAX7221 control pins. The first is which pin is connected to the data (din), then which pin is connected to the load (load), and lastly which pin is connected to the clock (marked clk on the MAX7221). These pins are used internally by the Matrix class to drive the chip:

#include <Matrix.h>

Matrix mat = Matrix(2, 3, 4);

void setup() {
    // nothing here at the moment
}

void loop()
{
    myMatrix.clear(); // clear display
    delay(1000);

    // turn some pixels on
Maxim7221 schematic
Figure 11-19. Maxim7221 schematic

The write() method take two parameters, the first to indicate the row of the LED that should be turned on and the second to indicate the column of the LED that should be turned on. The following calls to the write() method will create a smiley face:

mat.write(1, 5, HIGH);
    mat.write(2, 2, HIGH);
    mat.write(2, 6, HIGH);
    mat.write(3, 6, HIGH);
    mat.write(4, 6, HIGH);
    mat.write(5, 2, HIGH);
    mat.write(5, 6, HIGH);
    mat.write(6, 5, HIGH);

    delay(1000);
}

Aside from the tricky wiring situation, creating a single LED matrix isn’t too difficult. Creating multiple LED matrices is also fairly easy, but it requires that you use a different Arduino library: the LedControl library.

Using the LedControl Library

The LedControl library is quite similar to the Matrix library except that it allows you to easily work with multiple MAX7221 and LED matrix pairings. Note, though, that for each LED matrix that you want to use, you’ll need to have a driver chip for it. You can use up to eight driver and matrix pairs with this library. The constructor looks like this:

#include "LedControl.h"

LedControl lc1=LedControl(12,11,10,1);

The initialization of the LedControl library takes four arguments. The first three arguments are the pin numbers on the Arduino that are connected to the MAX7221, just like the Matrix library. You are free to choose any of the digital I/O pins on the Arduino, but since some of the pins are also used for serial communication or have an LED attached to them, it’s best to avoid pins 0, 1, and 13. I chose pins 12, 11, and 10 in my example.

The fourth argument for the LedControl constructor is the number of cascaded MAX72XX devices you’re using with this LedControl. Valid values can be between 1 and 8. There is a little performance penalty implied with each device you add to the chain, but the amount of memory used by the library code will stay the same, no matter how many devices you set. This is quite important with a limited memory device like the Arduino. Here is the syntax for the constructor, followed by a description of the four parameters:

LedControl(int dataPin, int clkPin, int csPin, int numDevices);
dataPin

An int that represents the pin on the Arduino where data gets shifted out

clockPin

An int that represents the pin for the clock

csPin

An int that represents the pin for selecting the device when data is to be sent

numDevices

An int that represents the maximum number of devices that can be controlled

If you need to control more than eight driver and matrix pairings, you can always create another LedControl variable that uses three different pins on your Arduino. This means that if you’re using the Arduino MEGA, you can have up to 17 MAX7221 drivers connected. Figure 11-20 shows how to connect the signal lines for multiple MAX7221 chips.

Connecting multiple MAX7221 chips
Figure 11-20. Connecting multiple MAX7221 chips

Now you can create an LedControl for two devices:

LedControl lc1=LedControl(12,11,10, 2);

If you’ve attached multiple MAX7221 drivers to your LedControl, you can loop through them all using the getDeviceCount() method, as shown here:

    for(int index=0;index<lc1.getDeviceCount();index++) {
      lc1.setLed(1, 0, 0, 1);
   }
}

The setLed() method sets the LED value at the address indicated:

setLed(int addr, int row, int col, boolean state)

The setLed() method takes four parameters:

int addr

The address of the display to control, between 0 and 7.

int row

The row in which the LED is located, between 0 and 7.

int col

The column in which the LED is located, between 0 and 7.

boolean state

If true, the led is switched on; if false, it is switched off.

To initialize the MAX7221, you may need to wake the device by calling the shutdown() method with false passed to the method instead of true:

shutdown(int addr, bool shutdown);

This method takes two parameters:

addr

Indicates which MAX7221 should be altered.

shutdown

Indicates whether the device should go into power-saving mode if true is passed or whether it should come out of power-saving mode if false is passed.

When a new LedControl is created, the library will initialize the hardware with the display blanked, the intensity set to the minimum, the device in power-saving mode, and the maximum number of digits on the device activated. To completely initialize the LED, you’ll want to set the brightness on it so that it’s ready to display data as soon as the setup is complete on your Arduino. A common display sequence might look like this:

void setup() {
    //wake up the MAX72XX from power-saving mode
    lc.shutdown(0,false);
    //set a medium brightness for the Leds
    lc.setIntensity(0,8);
    }

To clear a display, call the clear() method, and pass the address of the controller that you want to clear:

void clearDisplay(int addr);

I’ll mention two other useful methods in the LedControl library:

The setRow() method sets an entire row on or off and uses the following signature:

void setRow(int addr, int row, byte value)

The setRow() method takes three parameters:

int addr

The address of the display to control.

int row

The row on which the LEDs are to be set. Valid values are between 0 and 7.

byte value

A bit set to 1 in this value will light up the corresponding LED.

The setColumn() method sets an entire column on or off and uses the following signature:

void setColumn(int addr, int col, byte value)

The setColumn() method takes three parameters:

int addr

The address of the display to control.

int col

The column on which the LEDs are to be set. Valid values are between 0 and 7.

byte value

A bit set to 1 in this value will light up the corresponding LED.

So, now that you have an understanding of how to use multiple LED devices, you can begin creating small displays using multiple LED matrices. Some fun ideas might be a version of the classic video game Pong controlled using potentiometers, small graphics or animations, or a readout for an application.

You might be interested in working with three-color LEDs, that is, LED matrices where each LED segment contains three LEDs (red, green, and blue), meaning that each segment can be adjusted to many different colors by turning the brightness up or down on each LED. These three-color LED matrices can be controlled using multiple MAX7221 controllers, or you can look at using the serial interfaced LED matrices from Sparkfun that include a logic board that handles connecting the logic controller and the pins. To connect those, you’ll simply need to connect the Arduino to the backpack included with the Serial matrix and send commands to it using the spi_transfer() method. This is a pretty advanced technique that shifts data into the data register to be read by any device that communicates using the SPI protocol.

Using the SPI Protocol

There’s only space for a very short tutorial on the Serial Peripheral Interface (SPI) protocol. SPI is generally used to communicate with other microcontrollers. In an SPI connection, there is always a master device that controls all the peripheral devices connected to it over three common lines:

Master in slave out (MISO)

The line that the slave uses to send data to the master controller

Master out slave in (MOSI)

The line that the master uses to send data to the slave devices

Serial clock (SCK)

The clock pulses that synchronize data transmission generated by the master

The really tricky thing about SPI is that generally each device implements it a little bit differently. Information on the nuances for each will always be available on the datasheet for the device in online documentation.

All SPI settings are determined by the Arduino controller’s SPI control register (SPCR). A register is just a byte of microcontroller memory that can be read from or written to. Registers generally serve three purposes: control, data, and status.

Control registers control settings for various microcontroller functions. Usually each bit in a control register affects a particular setting like the communication speed.

Data registers simply hold bytes. The SPI data register (SPDR) holds the byte that is about to be shifted out the MOSI line for all the peripheral devices to receive and the data that has just been shifted in the MISO line from any peripheral devices.

Status registers change their state based on various microcontroller conditions. For example, the seventh bit of the SPI status register (SPSR) is set to 1 when a value is shifted in or out of the SPI.

The SPI control register (SPCR) has 8 bits, each of which controls a particular SPI setting:

7 SPIE

Enables the SPI interrupt when set to 1.

6 SPE

Enables the SPI when set to 1.

5 DORD

Sends data last bit first when set to 1 and sends the first bit first, usually the bit that determines whether a number is negative or positive, when set to 0.

4 MSTR

Sets the Arduino in master mode when set to 1 and sets slave mode when set to 0.

3 CPOL

Sets the data clock to idle when high if set to 1 and to idle when low if set to 0.

2 CPHA

Samples data on the falling edge of the data clock when set to 1 and on the rising edge when set to 0.

1 and 0 SPR1 and SPR0

Sets the SPI speed; 00 is the fastest (4MHz), and 11 is the slowest (250KHz).

This next example will help you understand what this method means when you encounter it, such as if you try to control one of the Serial RGB LED matrices mentioned earlier in this chapter:

char spi_transfer(volatile char data)
{
  SPDR = data;                    // Start the transmission
  while (!(SPSR & (1<<SPIF)))     // Wait for the end of the transmission
  {
  };
  return SPDR;                    // return the received byte
}

The spi_transfer() function loads the output data into the data transmission register, thus starting the SPI transmission. It checks the value of the SPSR to detect when the transmission is complete and, when it is, returns complete. This is how external memory can be used with Arduino, such as when you need to write to external nonvolatile memory. Here’s what setting an application up to use SPI looks like:

#define DATAOUT 11//MOSI
#define DATAIN  12//MISO
#define SPICLOCK  13//sck
#define SLAVESELECT 10//ss

void setup()
{
    Serial.begin(9600);

Here, pin 13 will be the clock pin to connect to the SPIClock pin of the LED matrix controller, pin 12 will go to the DataOut pin, pin 11 to the DataIn, and pin 10 will go to the SlaveSelect pin.

    pinMode(DATAOUT, OUTPUT);
    pinMode(DATAIN, INPUT);
    pinMode(SPICLOCK,OUTPUT);
    pinMode(SLAVESELECT,OUTPUT);
}

Figure 11-21 shows how the peripheral devices are connected to the Arduino.

The Serial RGB LED matrices’ connections
Figure 11-21. The Serial RGB LED matrices’ connections

There are dozens of kinds of SPI devices that you might encounter, from memory storage devices to GPS devices to LCD screens.

Using LCDs

We are surrounded by liquid crystal display (LCD) screens, and although what they provide is not necessarily a physical sort of feedback, a small screen is an important element of many small devices because it lets you return data that is more complex than an analog range or a digital value. Although representing “Hello World” in sound is a very interesting exercise, it’s often a lot easier to simply get an LCD screen and print the characters to it. Moreover, a small screen can be held in the hand, attached to another object, and embedded in the environment in a way that provides supplementary information to a user.

There are many kinds of LCD screens and no foolproof way to communicate with all of them. With that in mind, we’ll look at one of the more common types of LCDs that has an Arduino library. LCD panels that are controlled by the Hitachi HD44780 LCD controller chip or equivalent can be used with the LCD Interface library, you can check which chip a LCD uses online. This library has methods to initialize the screen, print characters and strings, and clear the screen, making your coding substantially easier. The library is included with the Arduino IDE, so to get started, simply import the library using the Tools tab in the IDE, choose Import Library, and then choose LiquidCrystal. Figure 11-22 shows the next example.

A simple 16 × 2 LCD screen, a 20 × 4 LCD, and a Serial Miniature OLED
Figure 11-22. A simple 16 × 2 LCD screen, a 20 × 4 LCD, and a Serial Miniature OLED

The LCD Interface library provides five main methods:

void clear()

Clears out anything shown in the LCD screen.

void home()

Sets the cursor back to the beginning of the display.

void setCursor(int row, int column)

Sets the cursor to the position indicated by the row and column. So, in a display with 2 rows of 16 columns, to set the 19th character or the character in the 4th position of the 2nd row, you would use this:

setCursor(1, 3); // rows and columns start from 0
void write(byte value)

Writes the character to the current cursor position.

void command(byte value)

This method is a little trickier, but for the ambitious among you, it will be interesting. The HD44780 chip defines different commands that you can use to do things like set the display in and out of display mode quickly, control whether the cursor blinks, and so on.

Table 11-1 shows how the Arduino pin maps to an LCD using the HD44780 chip.

Table 11-1. Arduino to LCD Panel Chip Pin Map

Arduino pin

Pin on the LCD

2

14 (DB7)

3

13 (DB6)

4

12 (DB5)

5

11 (DB4)

6

 

7

 

8

 

9

 

10

Enable

11

Read/Write (RW)

12

Register Select (RS)

Keep in mind, though, that the pins might not be in the same order, so you’ll need to check the datasheet. Figure 11-23 shows how the HD44780 LCD screen is connected to the Arduino controller.

Connected an LCD screen to the Arduino
Figure 11-23. Connected an LCD screen to the Arduino

To control the contrast of the display, you will need to connect a 10k (or 20k) potentiometer to provide the voltage to LCD pin 3 because without the correct voltage on this pin, you may not see anything displayed. As shown in the figure, one side of the potentiometer connects to Gnd (ground), the other side connects to Arduino +5v, and the center of the potentiometer goes to LCD pin 3. Many LCD screen have an internal lamp called a backlight that illuminates the display. The datasheet for your LCD screen should indicate whether the backlight needs a resistor. Many do; you can use 220 ohms or so if you are not sure.

This allows you to use the LiquidCrystal library that is included with the Arduino distribution:

You have two different versions of the constructor available. One lets you pass the pins that will be used for all seven control pins:

LiquidCrystal(rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7)

Another lets you just pass four pins:

LiquidCrystal(rs, rw, enable, d4, d5, d6, d7)

Both options use the following three parameters:

rs

Specifies the number of the Arduino pin that is connected to the RS pin on the LCD

rw

Specifies the number of the Arduino pin that is connected to the RW pin on the LCD

enable

Specifies the number of the Arduino pin that is connected to the enable pin on the LCD

Whichever constructor version you decide to use, make sure that those pins are correctly attached to the LCD device. Now, to test, you could do the following:

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup()
{
    lcd.print("I'm in an LCD!");
}

void loop() {}

You should see the words “I’m in an LCD!” printed to your screen.

Serial LCD

Another option for working with LCD screens is the Serial LCD style. Some LCD screens can be controlled simply by connecting them to the Arduinio’s RX and TX pins, which are the digital 0 and 1 pins on your controller. The Serial LCD works by having certain command bytes that indicate that the next byte will be a message. For instance, sending 0x01 over the Serial port to the LCD might clear it, but sending 0x10 would move the cursor left one space.

To communicate with the Sparkfun LCD, you can use the SLCD library, written by Ian McDougall, which makes working with LCD screens a great deal easier. Different manufacturers use different commands. They aren’t standardized, so you’ll need to check the datasheet for your board if you’re using a different one. To use this library, download the SLCD library from the Arduino site, and place it in the hardware/libraries folder of your Arduino application. Next, you’ll need to load the following code onto your Arduino:

#define numRows 2
#define numCols 16

Pass the number of rows and columns to the library:

SLCD lcd = SLCD(numRows, numCols);

void setup()
{

Now, call the init() method to initialize it:

    lcd.init();
}

void loop()
{
    lcd.clear();
 // can use string, line, col
    lcd.print("Help I'm stuck", 0, 0);
    // or line, col, string
    lcd.print(1, 11, "in an LCD!");
    delay(500);
    lcd.clear();
 // can use string, line, col
    lcd.print("Just Kidding", 0, 0);
}

As you can see, the print() method writes characters to the screen, and the clear() method erases the screen. The SLCD library also defines a few more methods for the Serial LCD:

brightness()

This takes an integer to set the brightness of the display.

lcd.flash(5, 500)

The first parameter sets the number of times the screen should flash, and the second is the length of time in milliseconds that the screen should flash.

vscroll(numCols, 100)

This scrolls the text on the LCD screen to the right or left depending on whether the number passed is negative or positive.

setCursorPosition()

The LCD screen has a small cursor that can be shown at the cursor position. This is especially useful if you want to prompt the user to enter something.

The Serial LCD enables a few other methods. You can find out more about these either by checking the datasheet available from an electronics supplier or by checking online.

Another option for working with the Serial LCD is to use the SoftwareSerial libraries. If you want to connect multiple LCD screens to your Arduino, take a look at Chapter 15 where we discuss these different approaches to sending and receiving serial data.

You can use the LCD screen in a few different ways; since it’s small, it can be embedded in touchable devices to send messages or can be put in plain view in an interface. Since the LCD is such a common way of providing feedback, to make it noteworthy or playful, you’ll need to use it in a novel fashion, such as embedding it in novel location or using its lightness and relative thinness to your project’s advantage. Of course, you can always use an LCD screen in a simple and straightforward manner: to provide simple textual feedback to a user without requiring a large screen that consumes more power.

Using Solenoids for Movement

This section requires that a few terms be defined for you first, so let’s start at the beginning.

A solenoid is a coil of wire with a magnetic core and usually with a rod resting inside that coil of wire. It works by sending a current through the wire that either pushes or pulls the rod, depending on the type of solenoid. When the current triggers the solenoid, the rod moves in its primary direction, either pushing if it’s a push solenoid or pulling if it’s a pull solenoid (see Figure 11-24). The names simply indicate in which direction the magnetic field tries to move the solenoid. When the current is off, then the rod in the center of the solenoid returns to its resting position. Solenoids are used frequently in machines, in automobile transmissions, and in robotics.

How a solenoid functions
Figure 11-24. How a solenoid functions

Diodes are used to ensure current flows in only a single direction, acting almost like a valve that lets water flow in only one direction (see Figure 11-25). Diodes use a small amount of voltage to operate, typically 0.7V, so a diode receiving the voltage from a 7.2V battery would reduce it to 6.5V. They are used for many purposes in more advanced electronics, but the most common use for beginners is to protect a microcontroller from “noise” that could destroy the microcontroller or interfere with other components. Diodes called Zener diodes are also useful for dropping high voltages to a lower voltage.

Transistors are, at the moment, probably the important electrical component ever invented. They may even be one of the most important inventions of all time (see Figure 11-25). Almost everything that is electronic probably has at the very least one of them and, in the case of your computer, probably millions, if not billions, of them (in the digital world). A transistor is not much different from a simple mechanical on/off switch. Instead of flipping a switch, a signal is sent to the transistor telling it to connect the circuit that runs through it from your microcontroller.

Transistors and diodes
Figure 11-25. Transistors and diodes

When you send 0 volts to the base of the transistor, the collector is turned off, and when you apply a signal of 5V, the transistor collector is turned on, which is why it’s like a light switch. Transistors can be used to control things other than lights. By sending a small signal, you can control huge flows of water through a pipe. In the case of an Arduino board, the transistor controls a larger flow of current by sending a digital on or off signal from one of the digital pins on the board. With the solenoid, the transistor will be used to power the magnetic coil of the solenoid to push out. The Arduino controller wouldn’t have enough power on its own to power up the solenoid, but by feeding the current through a transistor, you can use the small 5V signal of the Arduino to control the 12V solenoid.

The circuit that you’ll be building to control the solenoid looks like Figure 11-26.

A circuit to connect a Solenoid to the Arduino
Figure 11-26. A circuit to connect a Solenoid to the Arduino

The solenoid power is going to depend on the solenoid that you’re using. A 12V solenoid will require a 12V power source. You’ll also want to make sure that the diode is “facing” the right direction, that is, that power from the solenoid power source is not flowing into your Arduino, because the solenoid won’t work and the solenoid power source will be shorted when the transistor is turned on.

Another way to do this is to use a low power relay switch, like the one shown in Figure 11-27 on the left.

Connecting a solenoid using a relay
Figure 11-27. Connecting a solenoid using a relay

The relay functions in much the same way as the transistor and diode but integrates the two devices into a single unit. The relay that you use will need to be rather specific because it needs to have a coil current of 40 milliamps and a coil voltage of 5V. Some models you can investigate are the JQ1AP-5V or the Panasonic Electric Works TQ2SA-L2-5V. You can now connect your solenoid to your Arduino in the way shown on the right of Figure 11-27.

Since solenoids can be used to push, one possibility is to use them to create a drumbeat of sorts. You can easily do this by purchasing two solenoids and attaching one of them to a cymbal and another to a snare drum with some tape or with small clamps. The beat would be defined in two arrays of Boolean values to save space. Your code could be as simple as this:

boolean hihats[] = {1, 0, 0, 0, 0, 1, 0, 1};
boolean snare[] = {1, 0, 0, 0, 1, 0, 0, 0};

int hatPin   = 2;
int snarePin = 3;
int counter;

void setup() {
    counter = 0;
}

void loop() {

    digitalWrite(hatPin,   hihats[counter]);
    digitalWrite(snarePin, snare[counter]);

     if(counter == 7) {
        counter = 0;
    } else {
        counter++;
    }
    delay(200); // delay between beats
}

You could, of course, make your rhythms much more complex and, if you wanted, use as many relays and solenoids as you have digital pins on your Arduino. Another option is to have a button control a solenoid, making user-driven controls. Yet another option is to drive the solenoids with a Processing or oF application by sending data over the Serial port. This, coupled with the computer vision techniques in Chapter 14 could allow you to create a remote virtual drumming machine. Or, coupled with the network communication techniques from Chapter 12 it could enable a user to remotely drum or control any other kind of movement. The difficult part of working with a solenoid is not the programming; it’s getting the power and wiring right. However, as mentioned earlier, using a relay switch can make that quite a bit easier for you.

What’s Next

This chapter mentioned a few different topics that you can explore further. Mechanical engineering is a vast field that many of the devices here have touched on only just briefly. Working with several stepper motors or servos requires some engineering thinking to ensure that equipment doesn’t fail or destroy other parts of the project. For instance, using multiple servos to create complex motion requires some careful planning; controlling multiple appliances or motors also requires a fair amount of planning and research. That said, there are plenty of resources to help. There are a few good introductory texts on robotics that can be of great help. Practical Electronics for Inventors by Paul Scherz (McGraw Hill), Robot Building for Beginners by David Cook (Apress), Getting Started in Electronics by Forrest M. Mims III (Master Publishing), and Physical Computing by Tom Igoe and Dan O’Sullivan (Course Technology) are all resources that will help you. Also, the Arduino website contains a wealth of information in its Playground section. The Arduino community is also very prolific in publishing books, tutorials, and libraries to make working with components easier. Another excellent book for learning more about hardware, electronics, and components is Designing Embedded Hardware by John Catsoulis (O’Reilly).

You might also be interested in taking a look at some of the more far-out projects that people in the Arduino community have been exploring. Some of my favorites are the RepRap Research Foundation’s self-replicating machines; the Asurino library and development project, which uses the Arduino to control the Asuro hobby robot; and the Braitenberg Vehicle, the light-seeking robot designed by Alexander Weber. Another fascinating breed of projects that has emerged in the Arduino community is research into unmanned autonomous vehicles (UAVs). There are already several small projects underway to provide componentry and drivers for UAV projects built with Arduino controllers, among them the ArduPilot. There are also non-Arduino UAV platform kits available if the idea of creating things that run around is interesting.

Review

DC motors come in several different kinds. Brushed DC motors, for example, are composed of two magnets and a core that spins as the voltage around the core changes. To reverse a DC motor, you need to be able to reverse the direction of the current in the motor. The easiest way to do this is using an H-Bridge circuit.

In addition to buying an H-Bridge circuit, you can purchase several kinds of driver boards that will allow you to control motors with prebuilt kits. Several major suppliers have created different boards for running motors.

Another kind of motor is a stepper motor. Instead of spinning in one direction or another depending on the current, a stepper motor advances to predefined steps. Stepper motors can provide more torque than a servo. There are several different libraries, most prominently the Stepper library, included with the Arduino IDE that can be used to control stepper motors. As with DC motors, there are also driver shields that are ready to be fit onto an Arduino controller.

A servo allows for programmable motion. It receives a signal of varying pulse position to determine how far to rotate within a limited range. The most common range for a servo motor is 180 degrees.

You can use the Servo library or control the servo using pulse width depending on which is more appropriate for your application.

To use household currents, you can either use a solid-state relay, or you can use a device like the RelaySquid from LiquidWare. It’s very important to check your circuit carefully when working with high voltage because you can hurt yourself or damage your electronics.

Using the Vibe Board in conjunction with the LilyPad is another interesting way to provide feedback because it lets you send small vibratory signals to a user from a small controller that can be sewn into clothing or carried.

An LED matrix is an array of either 5 × 7 or 8 × 8 LED lights. They can be controlled using a chip such as the MAX7721. To control a single LED matrix, you can use the Matrix library; to control up to eight LED matrices, you can use the LedControl library.

The spi_transfer() method is used to send and receive data from another microcontroller or peripheral using the Serial Peripheral Interface protocol. This is a low-level protocol that lets you set other devices to be the slave devices for the Arduino controller, which will act as the master device.

LCD devices can be controlled by the LiquidCrystal library. This lets you write to the LCD screen using the print() method and lets you clear the screen using the clear() method. Most LCDs also support using cursors and scrolling.

Solenoids are magnetic devices that can push or pull depending on the kind of solenoid it is. These can be used in many different kinds of mechanical devices and are quite common in electrical engineering and robotics.

You’ll need to use a transistor and a diode to control a solenoid, or you can use a relay switch to control whether the solenoid is powered on or off.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.213.87