Tuesday, 11 August 2015

How to Control a Servo with the Arduino

By using a potentiometer (or any analog sensor), it’s possible to directly control your servo with the Arduino in the same way that you’d control a mechanical claw at the arcades.

The Knob sketch

This example shows you how you can easily use a potentiometer to move your servo to a specific degree.
You need:
  • An Arduino Uno
  • A breadboard
  • A servo
  • A 10k ohm variable resistor
  • Jump wires
The servo is wired exactly as in the Sweep example, but this time you need extra connections to 5V and GND for the potentiometer, so you must use a breadboard to provide the extra pins. Connect the 5V and GND pins on the Arduino to the positive (+) and negative (-) rows on the breadboard.
Connect the servo to the breadboard using either a row of three header pins or three jump wires. Connect the red socket to the 5V row, the black/brown socket to the GND row, and the white/yellow socket to pin 9 on the Arduino.
image0.jpg
Find a space on the breadboard for the potentiometer. Connect the center pin to pin A0 on the Arduino and the remaining pins to 5V on one side and GND on the other.
image1.jpg
After you have built the circuit, open the sketch by choosing File→Examples→Servo→Knob. The code for the sketch is as follows:
// Controlling a servo position using a potentiometer (variable resistor)
// by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>
#include <Servo.h>
Servo myservo; // create servo object to control a servo
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, 179);  // 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
}
You may notice that there are a few discrepancies between the comments and the code. When referring to the range of degrees to move the servo, the sketch mentions both 0 to 179 and 0 to 180. With all Arduino tutorials, it’s best to assume that they’re works in progress and may not always be accurate.
The correct range is 0 to 179, which gives you 180 values. Counting from zero is referred to as zero indexing and is a common occurrence in Arduino, as you may have noticed by this point.
After you have found the sketch, press the Compile button to check the code. The compiler should highlight any syntax errors in the message box, which lights up red when they are discovered.
If the sketch compiles correctly, click Upload to upload the sketch to your board. When it is done uploading, your servo should turn as you turn your potentiometer.
If that isn’t what happens, you should double check your wiring:
  • Make sure that you’re using pin 9 to connect the data (white/yellow) line to the servo.
  • Check your connections to the potentiometer and make sure that the center pin is connected to Analog pin 0.
  • Check the connections on the breadboard. If the jump wires or components are not connected using the correct rows in the breadboard, they will not work.

The Knob sketch breakdown

In the declarations, the servo library, Servo.h, and a new servo object are named. The analog input pin is declared with a value of 0, showing that you are using Analog 0.
You may have noticed that the pin is numbered as 0, not A0 as in other examples. Either is fine, because A0 is just an alias of 0, as A1 is of 1, and so on. Using A0 is good for clarity, but optional.
There is one last variable to store the value of the reading, which will become the output.
#include <Servo.h>
Servo myservo; // create servo object to control a servo
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
In setup, the only item to define is myservo, which is using pin 9.
void setup()
{
 myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
Rather than use two separate variables for input and output, this sketch simply uses one. First, val is used to store the raw sensor data, a value from 0 to 1023. This value is then processed using the map function to scale its range to that of the servo: 0 to 179.
This value is then written to the servo using myservo.write. There is also a 15 millisecond delay to reach that location. Then the loop repeats and updates its position as necessary.
void loop()
{
 val = analogRead(potpin);   // reads the value of the potentiometer
          // (value between 0 and 1023)
 val = map(val, 0, 1023, 0, 179);  // 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
}
With this simple addition to the circuit, it’s possible to control a servo with any sort of input. In this example, the code uses an analog input, but with a few changes it could just as easily use a digital input.

10 Places to Find Arduino Parts and Components

You can find many Arduino-related shops in the world, but there are also a number of suppliers that are good to know about when shopping for the right parts and components.

RS Components (World)

RS Components markets itself as “the world’s largest distributor of electronics and maintenance products,” so it’s a reliable source of products available in an extensive range and at low prices. RS also has a sister company that operates in the United States, Allied Electronics.

Farnell (World)

Farnell is a British suppler of electronics with an enormous range of components to choose from. It operates worldwide under the Premier Farnell Group. This company is made up of several sister companies that allow the group to distribute to 24 countries in Europe (Farnell), North America (Newark Electronics) and Asia Pacific (Element14).

Rapid (World)

Rapid is one of the United Kingdom’s leading electronics distributors. Its main promise is to source components quicker than other suppliers. Among its stock is a huge selection of educational electronics kits, ideal for those who are just starting out with soldering.

Digi-Key (World)

Digi-Key is one of the largest distributors of electronic components in North America. The company originally started by supplying the hobbyist market of amateur radio enthusiasts, but it has since grown into the international electronics distributor that it is today.

eBay (World)

One person’s junk is another person’s treasure, and eBay is a great source of tech products that need a new home. Many parts are available through eBay — even quite specific ones. But better than that, you can find other bits of consumer electronics that you can hack to suit your own ends.

Maplin (U.K.)

Maplin is a consumer electronics shop that can be found in most city centers across the United Kingdom, providing all sorts of electronic products as well as a fair selection of components, kits, and tools. Maplin can be a lifesaver for Arduin-ists when they’re caught in a tight spot. The company has also recently started stocking a range of Arduino products that show off the new Arduino branded retail packaging.

RadioShack (U.S.)

RadioShack sells a wide range of consumer electronics product accessories and has more than 7,000 stores in the United States. As well as stocking more conventional consumer electronics, it offers a selection of electronics components, kits, and tools.

Ultraleds (U.K.)

Ultraleds is a U.K.-based specialist supplier of LED lighting products and other accessories to use them. Ultraleds stocks more conventional LED replacement bulbs for use around the house and offers a wide range of low-voltage DC LED ribbon and bulbs at extremely competitive prices.

EnvironmentalLights.com (U.S.)

EnvironmentalLights.com is a leading supplier of sustainable and energy-efficient lighting based in San Diego, California. It offers a huge variety of LED lighting that can be used for an equally huge number of applications. The company may even give you ideas for new projects as well.

Skip/Dumpster diving (World)

People are always amazed at the amount of useful stuff that’s thrown away, but they rarely know what’s useful and what’s not. The key is to know what you’re looking for and find out whether you can salvage the parts you need for your project. This may take a bit of Googling because there are so many products and components out there that could be of use to your project.
The motor is one such component that can be extremely expensive if bought new but is used in a variety of consumer electronics that are often discarded. Printers and scanners use relatively complex and expensive stepper motors to work, which can be used again another day. Even the cost of a new printer with several motors can be cheaper than buying motors on their own.

Ten Links to Online Arduino Learning Resources

If you are interested in learning about Arduino projects, there are loads of things you can discover through some online resources. Check out the following links, which are some favorite online resources for learning about Arduino and electronics in general:
  • Adafruit Learning System: Adafruit Industries’ learning zone is probably one of the best online resources for learning about Arduino and checking out some cool projects. Don’t miss it.
  • All About Circuits: These online textbooks written by Tony R. Kuphaldt will help you to learn everything you need to know about electronics and circuit design.
  • The Interactive Telecommunications Program at New York University: If you are interested in Arduino, you’ll want to know more about Physical Computing, which is about making things interactive. It’s taught at NYU and led by Tom Igoe, one of the Arduino core team members.
  • Tronixstuff: John Boxall’s website is a great resource for learning about Arduino. He has dozens of different Arduino projects and demos on his site. Don’t miss it!
  • Collin Cunningham’s Make Videos on YouTube: Collin Cunningham made some great videos for Make Magazine, which are all available on YouTube. His primer on Electronics Tools is a great. From there you find many of his other great videos.
  • Mike’s Electric Stuff: Mike’s site is not dedicated to Arduino stuff, but if you are at all interested in tesla coils, antique electronics, and anything with high voltages, his site is definitely worth checking out.
  • EvilMadScience.com: A great online shop offering Arduino kits and more amazing electronic stuff.
  • Wearable Technology at Kobakant: The Kobakant website has a great section on making interactive stuff with soft circuits. Their site has a great treasure trove of wearable kits and project to choose from. Why not wear your Arduino wherever you go?
  • Arduino projects at Lifehacker.com: LifeHacker has an amazing range of cool weekend projects from Arduino controlled window blinds to an MP3 jukebox.

LED Cube Pattern Generator

For the LED cube, you have to write the correct code to generate the animation. But writing all of those 1s and 0s can be really tedious. To make things easier, use the LED Cube pattern generator to create sequences of animation frames and play them back. Here’s how to use it:
  1. Click on the gray boxes to turn them orange.
    This means the corresponding LED will be illuminated in that frame of the animation sequence, once you have uploaded the code to your cube. You can preview the results in an isometric preview window on the right.
  2. Click on the insert button at the lower right to create a new frame and determine which of its LEDs are turned on.
  3. When you are happy with your frame, set its duration and click the Apply button.
    By default, each frame lasts for 100 milliseconds, so 10 frames of animation will take 1 second to play back on your cube.
  4. Keep going until you’ve created your animation sequence.
  5. Click the Play button, when you’re ready to preview the animation.
    The animation will be played at approximately the same speed you’ll see when it’s uploaded to your cube.
  6. When you are satisfied with the animation, click on the Get code button.
    This displays the necessary code in a pop-up window.
  7. Cut and paste the results in the textbox directly into your Arduino sketch!
  8. Upload your code to your LED cube and watch the three-dimensional show!

Arduino Projects Schematic Symbols

When building Arduino projects, you often need to consult a schematic. Have a look at the following table, which shows the common schematic symbols you encounter when building Arduino projects:
image0.jpg

Troubleshooting Your Arduino Electronics Project

If your Arduino electronics project isn't working, you have to check both your hardware and your software. Start with your hardware and then move on to the software. Troubleshoot your electronics project by following these steps to check for the most common problems.

Troubleshooting hardware in a problematic electronics project

Review the following steps to check for hardware problems:
  1. Check your hardware connections.
    Look for open connections. The most frequent cause of problems is things simply being disconnected. Also check for short circuits. This can anywhere wires are touching or connected that they shouldn't be. Make sure that you are using your Arduino's digital inputs for sensors that give a digital output (either HIGH or LOW) and analog inputs for sensors that output a variable voltage.
  2. Check your power.
    Make sure that you have enough power then make sure it's getting to the right place. Confirm your power indicator lights are on. If you are powering external components from your Arduino but they don't seem to be working, try powering them independently from your Arduino by using a battery or external power supply.
  3. Check for hot components and funny smells.
    Locate any components that may be too hot to touch. They are probably wired incorrectly or receiving too much power. Sniff your components for anything that might seem to smell like burning. This is a definite indication of an incorrect connection, and you should disconnect the power right away. Replace any damaged components and recheck your circuit for incorrect connections before powering up.
  4. Check your output values.
    Use a multimeter to measure the voltages from your devices. Make sure that you are getting +5 volts for digital HIGH values and 0 volts for LOW values. Test your digital sensors to make sure they are outputting the correct values. Test your analog sensors to make sure they are providing a voltage that ranges from 0 to 5 volts.
  5. Check your digital inputs and outputs.
    If you have run too much current (more than 40mA) on a digital or analog pin, you've overdriven the pin, and it may have stopped operating. If you suspect a pin is dead, try using an adjacent pin by changing your code accordingly. If that solves the problem, you might have a dead pin.

Troubleshooting software in a problematic electronics project

Review the following steps to check for software problems:
  1. Check your syntax.
    The most common problem is a missing semicolon at the end of a line. Probably the second most common problem is a missing curly bracket. Also, look for typos, incorrect spelling, or a mismatch in capitals or lowercase text, because Arduino code is case sensitive. If there's an error in your code, the IDE will usually highlight the line where the error occurred.
  2. Use the serial monitor.
    Use Serial.println() statements at key points in your code to output the contents of variables to the serial monitor. You can also print messages to the serial monitor at important points in your code. You may need to also add a delay() statement to provide a moment, so you can read the value(s) as they are printed to the screen.
  3. Check your inputs and outputs.
    Locate any components that may be too hot to touch. They are probably wired incorrectly or receiving too much power. Sniff your components for anything that might seem to smell like it's burning. This is a definite indication of an incorrect connection and you should disconnect the power right away. Replace any damaged components and re-check your circuit for incorrect connections before powering up.
  4. Use a simulator or emulator.
    You can use Arduino simulators that mimic the behavior of the Arduino and emulators for the AVR chip family. These are technical tools aimed at engineers and give you a wealth of information about your code, as it's running. Download one of these tools to try running your code on a virtual Arduino on your computer.
  5. Check the forums.
    The official Arduino website, Adafruit, Sparkfun, and Element14 have Arduino forums where people post discussions. Those communities are filled with people who just want to get their Arduinos to do cool stuff. They are almost always helpful and supportive.

11 Great And Best Arduino Resources

If this is your first step into the world of Arduino, you will be relieved to know that you have an abundance of resources available to you on the Internet. You can find new, Arduino-compatible hardware, projects, tutorials, and even inspiration.

Arduino blog

The Arduino blog is a great source of all Arduino-related news. You can find news on the latest official hardware and software as well as on other interesting projects. Also found here are talks that the Arduino team wants to share with the community.

Hack a Day

Hack a Day is an excellent resource for all sorts of technological magic. In addition to presenting a lot of Arduino-related projects and posts, the site offers equal amounts of just about any other category of technology that you can think of. This site contains an excellent collection of posts and information to fuel the imagination.

SparkFun

SparkFun manufactures and sells all sorts of products to make your projects possible, and many of these involve Arduino. SparkFun has an excellent and well-maintained newsfeed that always has some sort of interesting new product or kit to show off. The company also provides excellent videos that explain its kits and document any events that the SparkFun team hosts or attends.

MAKE

MAKE is hobbyist magazine that celebrates all kinds of technology. Its blog covers all kinds of interesting do-it-yourself (DIY) technology and projects for inspiration. Arduino is so important to this community that it has its own subsection in the blog.

Adafruit

Adafruit is an online shop, repository, and forum for all kinds of kits to help you make your projects work. Its blog announces the ever growing selection of available Adafruit products as well as other interesting tech news.

Bildr

Bildr is an excellent resource that provides in-depth, community-published tutorials. As well as providing clear tutorials, Bildr also has excellent illustrations, making the connections easy to follow. Many of the tutorials are Arduino based and provide all the code and information on the components that you will need as well as where to buy the parts.

Instructables

Instructables is a web-based documentation platform that allows people to share their projects and step-by-step instructions on how to make them. Instructables isn’t just about Arduino or even technology, so you can find a whole world of interesting material there.

YouTube

YouTube is a great place to kill time, but rather than watching cats do funny things, why not enter Arduino in the site’s search box to discover new projects that people are sharing. YouTube videos won’t always be the most reliable sources for well-documented projects, but they provide you with a broad look at Arduino projects in action. Watching videos is especially useful for seeing the proper result of projects.

Hackerspaces

Hackerspaces are physical spaces where artists, designers, makers, hackers, coders, engineers, or anyone else can meet to learn, socialize, and collaborate on projects. Hackerspaces are found in a loose network all over the world, and a this map is a good resource to find one near you.

Forum

The Arduino Forum is a great place to get answers to specific Arduino questions. You often find that other people are working through the same problems that you are, so with some thorough searching, you’re likely to find the answer to almost any problem.

Friends, colleagues, and workshops

Starting out in the world of Arduino can be difficult on your own. You can find many sources on the Internet, but one of the best ways to learn is with friends and colleagues, because learning together teaches you much more than learning on your own can.
Even better is to go to workshops and meet people. You may find that they have the same interests, allowing you to pool your knowledge; or they may have different interests, providing an opportunity to show you something new. Arduino workshops are going on all over the world, so with some searching in the Arduino Forum, Hackerspace forums, and Google, you should be able to find a workshop near you.