Saturday, March 12, 2011

Arduino Tutorial for Beginner



The Arduino website offers free resources and tutorials as well as a language reference to help you understand the code and syntax. In order to get started, you will at the very minimum need an Arduino board. Note that all the Arduino (and most of the clone boards) can use the Arduino software. If you are unsure what hardware to get, the Arduino USB is currently the most popular model

Windows Connection and Setup

Hardware: none

  1. Go to www.arduino.cc to download the latest version of the Arduino software (Direct link:http://arduino.cc/en/Main/Software and select your operating system; in this case we are using Windows)
  2. Save the ZIP file to your desktop (you can move or delete it later)
  3. Create a new folder called “Arduino” under “Program Files”. To do this, go to “My computer” -> “C:” (or the drive where the operating system is installed) -> “Program Files”, then left click once on “program Files” folder, then select “New”->”Folder” from the main Explorer menu.
  4. Extract the entire ZIP folder to this new “Arduino” folder
  5. To run the Arduino software, open Windows Explorer by pressing the windows key (usually between the Ctrl and Alt keys on your keyboard) and the ‘E’ character at the same time (there are other ways to access explorer as well).
  6. Go to “My computer” -> “C:” (or the drive where the operating system is installed) -> “Program Files” -> “Arduino” In this folder you will see an executable file (Blue colored icon), you can left click (once) and then right click and select “send to” -> Desktop (create shortcut) to have Arduino more easily accessible.
  7. Double click the icon to start the software. The Arduino Software is ready to use.


Arduino Software Interface

Hardware: Arduino USB Microcontroller or Arduino Microcontroller with USB

The Arduino interface is “bare-bones”. When you load the software, the first screen you will see is a white window with several different shades of blue and blue-green as border. There are the main headings “File” “Edit” “Sketch” “Tools” “Help” and several shortcut icons beneath “Verify”, “Stop”, “New”, “Open”, “Save”, “Upload” and “Serial Monitor”. Note that all these icons are also available from the main menus. Arduino projects are called “sketches” and when you start a new sketch, several files are also created. To connect to your board,

1. Start the Arduino software by double-clicking the Arduino icon (see S1 for details)
2. Plug one end of the USB into the Arduino and the other end into your computer.
3. In the software, select “Tools” -> “Board” -> “Arduino Duemilanove w/ATMEGA328” (if you have a different board, select it from the drop-down list; if you have purchased a compatible board, that manufacturer should indicate which board to choose).
4. In the software, select “Tools” -> “Serial Port” -> COM X (note that if you have several COM ports, you will need to go to Control Panel to see which is assigned to your board.

The computer may ask you to install the USB to Serial interface; let the system find and install the drivers automatically.

Basic Program Structure
Hardware: Arduino Microcontroller with USB

The Arduino language is CASE SENSITIVE: a capital letter is not the same as a lower case letter. Arduino software requires the following code in order to compile:
The “setup” section is widely used to initialize variables, pin modes, set the serial baud rate and related. The software only goes though the section once. The “loop” section is the part of the code that loops back onto itself and is the main part of the code. Note that you are free to add subroutines using the same syntax:

void subroutinename() {}

Almost every line of code needs to end with a semicolon ‘;’ (there are a few exceptions which we will see later). To write single line comments in the code, type two back slashes followed by the text:

//comments are overlooked when compiling your program and are used used to explain the code textually

To write multi-line comments, start the comment with /* and end with */

/* This is a multi-line comment and saves you having to always use double slashes */

Serial Communication

Hardware: Arduino Microcontroller with USB

The Arduino board can communicate at various baud ("baud rates"). A baud is a measure of how many times the hardware can send 0s and 1s in a second. The baud rate must be set properly for the board to convert incoming and outgoing information to useful data. If your receiver is expecting 2400 changes per second your transmitter is transmitter at a different rate, the data you get will not make sense. To set the baud rate, use the following syntax in

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

Other standard baud rates available on most Arduino modules include: 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200 and you are free to specify other baud rates. To output a value in the Arduino window, consider the following program:





























Verify the program by pressing the “verify” button (looks like a “play” button); you should not get any errors at the bottom of the screen. If you get errors, check that only the two numbers in the code are black, the rest of the text should have been automatically recognized and assigned a color. If part of the text is black, check the syntax (often copy/pasting text from another program can include unwanted formatting). If this does nto correct the error, you may need to re-do S1 and S2 in this tutorial.

Next, upload the sketch to the board using the “Upload to I/O Board” button (arrow pointing right). Wait until the sketch has finished uploading. You will not see anything unless you then select the “Serial Monitor” button (rectangle with a circle that looks like a TV). Make sure the baud rate selected is the same you wrote in your program. Try using


Serial.print("Hello World");

If you want to save all your programs, we suggest creating a new folder called “reference” and save this program as Hello World.

Arduino and LED
Hardware: Arduino Microcontroller

Making an LED light up is very straightforward. Many Arduino boards such as the Uno come with an LED soldered to the board and connected to digital pin13.
Note that the ‘W’ is capitalized. The line digitalWrite(pin, HIGH); puts a specified pin high to +5V. In this case we chose pin 13 since on the Uno, the LED is connected to pin 13. Replacing HIGH with LOW, the pin is set to 0V. You can attach your own LED using a digital output and the GND pin. The delay(1000); line causes the program to wait for 1000 milliseconds before proceeding (where 1000 is just a convenient example to get a 1 second delay). Compare this to a program that uses variables and comments.

Arduino and Potentiometers
Potentiometers (also known as “pots”) are great little electromechanical devices used to get angular or linear position feedback. Potentiometers are used to set volume level, or as feedback devices in servo motors. Pots can vary in quality, size, feedback type and most are linear or rotary (some have additional features incorporated inside). Almost all potentiometers have three outputs: one for ground, another for voltage input and a third for analog signal output (almost always the middle pin). A good pot to start with is a 10k (which is 10 kilo ohms) linear rotary potentiometer.


  1. Cut three lengths of wire and remove the shielding from either end.
  2. Solder one end of each wire to the three terminals on the pot.
  3. Connect the middle wire to one of the Analog pins on the Arduino (in this case pin #2)
  4. Connect one of the other wires to the Gnd on the Arduino
  5. Connect the last wire to the +5V output pin on the Arduino.
Upload this program to the board and change to the Serial monitor. As you rotate the knob (or slide the slider), the values should change between 0 to 1023. You can now read values and use them within your code. The new function used here is “analogRead();” where the pin selected is pin #2 (if you used analog pin #5, you would change the code to
x = analogRead(5);


Troubleshooting:

If you bought a very cheap or old potentiometer, there is a chance it may be mechanically defective. You can test this using a multimeter and connect the ends to the middle pin and an outer pin. Set the multimeter to read resistance and rotate the knob; if the resistance changes slowly, the pot is working, and your connections or code may be at fault. If the resistance is erratic, you need a new potentiometer.

Arduino and Infrared Distance Sensors
Hardware: Arduino Microcontroller with USB, Infrared Distance Sensor and cables

Infrared distance sensors are useful for measuring distances without actually contacting a surface. The three wires protruding from a distance sensor represent +5V (in most cases), Gnd (Ground) and signal. These are almost always color coded with black as ground, red as +V and white or yellow as the signal. If your infrared distance sensor did not come with any wires, you will either need to find the appropriate connector, or solder wires directly to the leads (ensure the pins and solder do not contact one another).
  • Connect the red wire to +5V on the Arduino
  • Connect the black wire to Gnd on the Arduino
  • Connect the yellow wire to an analog pin on the Arduino

Since the sensor is connected to the analog input of the Arduino, the code is identical to that of the potentiometer:


Upload this program to the board and change to the Serial Monitor. As you move the front of the distance sensor closer to and away from an object, the values should change between 0 to 1023. You can now read values and use them within your code. Check the range for your sensor (not all sensors can read up close). Note that some sensors have a minimum distance - although it is always listed in the specifications, try to find it by experimentation.

Arduino and Push Buttons
Hardware: Arduino Microcontroller with USB and push button

Connecting toggle switches, push buttons and momentary contact switches to the Arduino is straightforward. A push button is a simple device that completes a circuit. One end of the button is connected to source, usually a low voltage (5V on the Arduino is ideal) and the other connected to the digital pin. When the switch is flipped, pressed or toggled, the circuit is either opened or closed. The digital pin simply returns if there is 5V or 0V. The code associated with this is:

digitalRead(pin); 

In the following simple program, a pushbutton is used to turn on the LED connected to pin 13:

Arduino and Servo Motors
Hardware: Arduino Microcontroller and USB, a low power servo motor and additional wires

Controlling a servo motor directly from the Arduino is quite easy. Note however that a servo motor may require significantly more current than the Arduino can provide. The following example uses a standard sized servo (without any load) powered directly from the Arduino via USB. If you want to use a more powerful servo, or if you want to connect it to a load, you’ll need to use an external power supply connected to the red and black wires (ensure you also connect the black (ground) wire to the Gnd pin on the Arduino (common ground).
  1. Connect the black wire from the servo to the Gnd pin on the Arduino
  2. Connect the red wire from the servo to the +5V pin on the Arduino
  3. Connect the yellow or white wire from the servo to a digital pin on the Arduino
Note that it is often unwise to connect a motor of any kind directly to the Arduino as it often requires more power than the board can provide. In this case, the servo is being used to demonstrate code and is not encountering any resistance. Note that you should use a standard or small size servo motor, if you are uncertain, check the servo's no load current rating (it should ideall be under 150mA).
Two new functions were used in this code, pinMode(pin number, OUTPUT); sets a pin number as dedicated input or output. In this case, we called the pin “servopin” and assigned a value of 4. The term “pulse” is in black as it is not a reserved word and can be changed by the user. It is best to use descriptive variables when coding to understand what each does, or the information it will contain. Servos operate by sending a timed +5V pulse to the onboard electronics every 20ms. This pulse corresponds to a servo position, usually from 0 to 180 degrees.

5V for 500 microseconds = 0.5 milliseconds corresponds to 0 degrees
5V for 1500 microseconds = 1.5 milliseconds corresponds to ~90 degrees
5V for 2500 microseconds = 2.5 milliseconds corresponds to ~180 degrees
The relationship is linear, so use mathematics to determine the values between. Note that if you send a signal that is greater or lower than the servo can accept (for example, Firgelli linear actuators acecpt 1 to 2 ms), you might dammage the actuator.
Arduino has the option of including a "servo library" (currently separate from the basic Arduino software) that manages much of the overhead and includes new, custom commands. If you want to control multiple servo motors, you should use a servo motor controller and a separate power supply between 4.8V to 6V.

Arduino and Force Sensors, Bend Sensors and Stretch Sensors
Hardware: Arduino Microcontroller, voltage divider circuit, flex or bend sensor

Force “sensors” are actually “force sensing resistors” (FSRs). Similarly, bend “sensors” are actually products whose resistance changes with flexing. These can all be categorized as “variable resistors”. To interface a product whose resistance changes with a microcontroller, you need a voltage divider circuit. This “circuit” is nothing complex – aside from wires, the only part you are missing is a resistor. To create the circuit, add the variable resistor in series with a similar (standard) resistor of roughly the same resistance (in ohms). Connect a wire between the two - this wire goes to the analog input of the board. There should only be two wires left - one end of the standard resistor, and one end from the variable resistor - these ends are connected to +5V and GND respectively. You can now use it as a regular sensor with analog output.
If you want a pre-made circuit, consider the Phidgets voltage divider:
The output of this “mini circuit” is a signal between 0 to 5V (this is referred to as an analog signal), which is connected to an analog pin of the microcontroller. The microcontroller's onboard analog to digital converter (ADC) interprets this voltage and assigns it a number which you can use in your code. For 10 bit ADC, you will get a number between 0 and 1024 representing 0V to 5V. You would need an equation in your code to use this number to send the appropriate signal to a motor controller. As you might have suspected, the code is now identical to that used to get an analog input.

Arduino and Accelerometers, gyroscopes and IMUs.
Hardware: Arduino microcontroller with USB and an accelerometer, gyroscope or IMU and wires (mini breadboard is optional)

When using accelerometers, gyroscopes or inertial measurement units to obtain positions in space, it is important to note that there are several additional factors that will affect the readings. The first and largest obstacle is the sampling rate. Microcontrollers requires a certain amount of time to read values being given to them by the sensor and because of this, the values between these readings are lost. There are several mathematical methods (Kalman being a popular choice) that attempt to compensate for this. A second source of error is that readings are often affected by fluctuations in temperature. Most datasheets associated with MEMS devices attempt to describe how temperature affects the output.
When choosing an accelerometer, gyroscope or IMU, it is also important to note the type of output; depending on the type of sensor, readings can be output as serial data, I2C, analog, TTL or a variety of others. The low cost ADXL3xx series output as analog voltage and can be directly connected to the Arduino’s pins with no need for additional electronics. The code shown below includes the output for a single axis sensor and factors in the rest value.
Source: Here

1 comment:



  1. Please accept my deepest gratitude for your outstanding effort. Your writing is flawless, and it is genuinely amazing how well you are able to communicate difficult concepts. Reading your work has been a real pleasure for me, and I've learned a lot and developed some new perspectives.
    if you want to buy robotic components then kindly click here.Arduino Boards

    ReplyDelete