Learning to Program the Arduino
Listing 7. Servo Control Sketch
/*
* servo1: servo1.pde
* Servo control from the Serial port
*
* Slower, faster, Center and Stop a Servo with an LED Blinky
* Created: 1 June, 2011, Amit Saha (http://echorand.me)
* Adapted from http://principialabs.com/arduino-serial-servo-control/
*/
/** Adjust these values for your servo and setup, if necessary **/
int servoPin = 2; // control pin for servo motor
int minPulse = 500; // minimum servo position
int maxPulse = 3000; // maximum servo position
int turnRate = 10; // servo turn rate increment (larger value,
faster rate)
int refreshTime = 20; // time (ms) between pulses (50Hz)
int OFF=0; // This variable will be used to get/set the status of the servo
/** The Arduino will calculate these values for you **/
int centerServo; // center servo position
int pulseWidth; // servo pulse width
int moveServo; // raw user input
long lastPulse = 0; // recorded time (ms) of the last pulse
/* LED setup*/
int ledPin=13;
void setup() {
pinMode(ledPin, OUTPUT); // LED Blink
pinMode(servoPin, OUTPUT); // Set servo pin as an output pin
centerServo = maxPulse - ((maxPulse - minPulse)/2);
pulseWidth = 0;
Serial.begin(9600);
Serial.println(" Arduino Serial Servo Control");
Serial.println("Keys:'(s)lower' or '(f)aster', spacebar to center
and o to stop");
Serial.println();
moveServo = 60;
}
void loop() {
// wait for serial input
if (Serial.available() > 0) {
// read the incoming byte:
moveServo = Serial.read();
// ASCII 's' is 115, ASCII 'f' is 102, 'o' is 111, 'spacebar' is 32
if (moveServo == 115) { pulseWidth = pulseWidth - turnRate; OFF=0;}
//slower
if (moveServo == 102) { pulseWidth = pulseWidth + turnRate;OFF=0; }
//faster
if (moveServo == 32) { pulseWidth = centerServo; OFF=0;} //center
if (moveServo == 111) { OFF= 1;} //STOP
// limit the servo pulse at min and max
if (pulseWidth > maxPulse) { pulseWidth = maxPulse; }
if (pulseWidth < minPulse) { pulseWidth = minPulse; }
}
// pulse the servo every 20 ms (refreshTime) with current pulseWidth
// this will hold the servo's position if unchanged, or move it if
// changed
if (OFF == 0)
{
/* Turn ON the LED*/
digitalWrite(ledPin,HIGH);
if (millis() - lastPulse >= refreshTime) {
digitalWrite(servoPin, HIGH); // start the pulse
delayMicroseconds(pulseWidth); // pulse width
digitalWrite(servoPin, LOW); // stop the pulse
lastPulse = millis(); // save the time of the last pulse
}
}
else
{
/* Turn OFF the LED*/
digitalWrite(ledPin,LOW);
//Stop the servo
digitalWrite(servoPin, LOW);
}
}
Once the sketch is uploaded, open a serial communication channel
using screen (feel free to substitute it with your favorite terminal
communication program). Type screen /dev/tttyACM0 9600, and you should see the
"servo prompt" at your service:
Arduino Serial Servo Control
Keys:'(s)lower' or '(f)aster', spacebar to center and o to stop
Pressing the keys to the servo should produce the desired behavior. If you see the code listing for the servo mechanism, you will see that the key to controlling the speed is basically the duration of the delay (variable pulseWidth) between sending a HIGH and LOW signal to the servo. Here, we are simulating an analog behavior using the important technique called Pulse Width Modulation, which you can read about elsewhere.
If you have gotten this servo example up and running, you also might want to check out the other example sketches for working with servos in the Arduino IDE under File→Examples→Servo.
A Peek under the Hood
I'm drawing toward the close of this article, and I hope you have had a lot of fun. However, if you are like me, you already have started wondering what's going on behind the scenes—the journey of the processing sketch to the bytes getting executed on the Arduino board.
The real work behind the scenes is done by the GNU C/C++ compilers,
linkers and libraries for the AVR microcontroller. If you hold the
Shift key when you compile your sketch, you will see that the commands
- avr-g++, avr-g++,
avr-ar and avr-objcopy are invoked.
First, your Arduino
sketch is converted to a suitable C++ file (with the .cpp extension), which
then is compiled, linked and finally converted to the hex file that
is uploaded to the Arduino board. You can see all these intermediate
files in the /tmp/build*.tmp directory. Knowledge of this build process
can enable you to bypass the IDE for your Arduino development by writing
an appropriate Makefile. See the "Command-Line Arduino development"
article listed in Resources for an example.
Conclusion
I've described a few simple but cool things that can be done with an Arduino, but this article barely scratches the surface. A number of excellent books are available that list a great number of Arduino projects you can build for fun and profit. These are, of course, in addition to all the excellent on-line resources available. During exploring Arduino purely from the various blog posts on the Web and a trial-and-error-based approach to learning, I discovered many great projects in the Arduino ecosystem. Be sure to see the Resources for this article for some of the most interesting Arduino books, articles and projects.
Also note that wires are good, but only when you want to limit yourself to the confines of your tabletop or even your room. If you want your Arduino to be out there, decoupled from your host machine, you need to explore ways of wireless communication. Say hello to XBee modules, which allow communication with the ZigBee communication standard.
And before I end, you might face issues with erratic serial communication. Especially during extended periods of experimenting with serial communication, I found that the serial ports would remain locked or just be plainly not accessible from the host computer. My advice is to be patient. Unplug and plug back in a few times, and try killing the lock file manually. Now, you should be good to go.
Acknowledgements
Thanks to the awesome Arduino community members for their documentation and numerous other bloggers on the Web. The Arduino circuit diagrams were drawn with Fritzing (http://fritzing.org).
Resources
Author's Code for This Article: https://bitbucket.org/amitksaha/articles_code/src/6bed469945fd/arduino_article
Plumbing for the Arduino: http://www.concurrency.cc/book
PureData (Audio Processing and Visualization): http://puredata.info
Firefly Experiments (bridging the gap between Grasshopper, the Arduino microcontroller, the Internet and beyond): http://www.fireflyexperiments.com
Arduino: http://arduino.cc
Processing Language: http://processing.org
Arduino Hardware (I/O Boards): http://www.arduino.cc/en/Main/Hardware
Arduino Uno: http://arduino.cc/en/Main/ArduinoBoardUno
Sparkfun's Starter Kit for the Arduino: http://www.sparkfun.com/products/10174
Installing Arduino on Linux (for different distributions): http://www.arduino.cc/playground/Learning/Linux
Command-Line Arduino Development: http://shallowsky.com/software/arduino/arduino-cmdline.html
Getting Started with Arduino by Massimo Banzi, O'Reilly Media/Make: http://shop.oreilly.com/product/9780596155520.do
Programming Interactivity: A Designer's Guide to Processing, Arduino, and openFrameworks by Joshua Noble, O'Reilly: http://shop.oreilly.com/product/9780596154158.do
Arduino Cookbook by Michael Margolis, O'Reilly: http://shop.oreilly.com/product/0636920022244.do
Arduino Language Reference: http://www.arduino.cc/en/Reference/HomePage
Tom Igoe's Physical Computing Page: http://www.tigoe.net/pcomp
Experimenter's Guide for Arduino: http://ardx.org/src/guide/2/ARDX-EG-ADAF-WEB.pdf
Arduino Tutorials (tronixstuff): http://tronixstuff.wordpress.com
Principia Labs, Arduino Serial Servo Control: http://principialabs.com/arduino-serial-servo-control
Make's Arduino Web Site: http://blog.makezine.com/arduino
Arduino Tutorial on Lady Ada: http://www.ladyada.net/learn/arduino
- « first
- ‹ previous
- 1
- 2
- 3
- 4
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- New Products
- Linux Systems Administrator
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- Designing Electronics with Linux
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- Reply to comment | Linux Journal
4 hours 30 min ago - Nice article, thanks for the
15 hours 11 min ago - I once had a better way I
20 hours 57 min ago - Not only you I too assumed
21 hours 14 min ago - another very interesting
23 hours 7 min ago - Reply to comment | Linux Journal
1 day 1 hour ago - Reply to comment | Linux Journal
1 day 7 hours ago - Reply to comment | Linux Journal
1 day 8 hours ago - Favorite (and easily brute-forced) pw's
1 day 10 hours ago - Have you tried Boxen? It's a
1 day 15 hours ago



Comments
Really interesting
Arduino is a really intersting project because its way to use are limitless. It can be adapted to many things and it's quite easy to program.
I love the Arduino! Thanks
I love the Arduino! Thanks for the interesting article.
Processing, C/C++ and Arduino
Thank you for the comment.
Thank you for the comment. Perhaps, "based on Processing" is not very true.
However to me, the language looks "very" C. And yes as you pointed out, its really gcc-avr down below as also pointed out in the later parts of the article. My experience with Processing is not beyond a basic level, so I came to Arduino "from" C, rather than processing.
Cheers,
Amit
Great article. Just a brief
Great article.
Just a brief observation.
Arduino doesn't stand for "good friend" in Italian (I'm Italian). As far as I know Arduino is the name of the cafè Arduino inventors where used to meet.
But Wikipedia says so?
Hello: Thanks for your comment. I am sorry if I got it wrong, But Wikipedia has this: "Arduino" is an Italian masculine first name, meaning "strong friend". The English version of the name is "Hardwin".(From: http://en.wikipedia.org/wiki/Arduino#History)
Cheers,
Amit
You're mistaken.
Amit is a Hebrew name which has the meaning "Friend" but it's not correct to say that Amit is the Hebrew word for friend. Just because the name's origin is Italian doesn't mean it's a current Italian word for something.
Name of Cafe, Name of King
The name Arduino comes from the cafe the founder(s) frequented where they thought of the project . Cafe Arduino takes it's name from medievel king that briefly ruled the area . I can't find my source right now but it's something like King of Ardo , therefore he was an Arduino , hence Cafe Arduino , hence the Arduino Project . Much of this comes from the IEEE article a few months ago .
Unfortunately, the lack of research in the first sentence makes me doubt the entire 5 page article . I'll glance at it later anyway in case there's something useful . - MC
I'm from Italy, therefore I
I'm from Italy, therefore I can give a definitive answer. Arduino is the name of a bar in Ivrea (Piedmont, Italy) frequented by the (Italian) creators of the open source framework. The bar was named after Arduin of Ivrea, first King of Italy from 1002 to 1017. By the way, Arduino is not a common name nowadays in Italy
actuators
The IO pins can't drive much: 5v and 40ma each, not to exceed 120ma total. You need a tiny relay to do anything more than power an LED, and even there you need to limit the current to prevent burnout. I have had luck with tiny reed relays connected directly to the IO pins. See www.elexp.com p/n 22RD5, with 5v/500ohm coils. These draw only 10ma. Buy more than you need and test them all. Two of the 12 I ordered had open coils. And put a diode across any relay coils. The Arduino already has pull-up/pull-down diodes on all the pins, which is why the AD pins read around 2.5v if not connected. Remember, when you stop applying any power to a coil, the magnetic field collapses which produces a brief voltage spike. Also, any of the above reed relays can also be used as magnetic sensors to detect an open window, for instance. Just glue a small magnet nearby.
Figures 2 and 3
The LEDs shown in figures 2 and 3 are shorted as illustrated. The edge rows on most (if not all) breadboards are buses.
Ground wires and tty
Right. Also the ground wire of the rightmost LED does not connect anywhere. It should be in the same column as the LED it is supposed to ground.
If you are using a recent version of Arduino (and a newer original board) you are more likely to find /dev/ttyUSB0 that /dev/ttyACM0. (Just a typo, but /dev/tttyACM0 won't do any good at all).