Sunday, 18 August 2013

HOW TO MAKE ROBOTS? Lesson 4 Extended: Arduino Tutorial - Robotshop Blog

Lesson 1 Hardware:

  1. Computer / Laptop or Netbook
  2. Arduino Microcontroller
  3. USB to Serial Adapter (if your microcontroller does not have a USB port)
  4. Appropriate USB cable (Arduino boards draw power from the USB port – no batteries yet)
The popularity of Arduino is steadily increasing and it is fast becoming the microcontroller of choice for students, hobbyists and smaller companies. Many different electronics PCB manufacturing companies are jumping on the bandwagon and producing their own variations of the boards, as well as “shields” (additional circuits that fit directly on top of many Arduino boards to increase their functionality) and accessories. 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, and these 5 minute tutorials are based around it.

Downloading / Installing Arduino Software

  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. It is convenient to 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 named “Arduino”), 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 on the desktop to start the software.

The Arduino Software Interface

The Arduino interface is pretty “bare-bones”. When you load the software, the first screen you will see is a white window (shown below) with several different shades of blue and blue-green as border.  Arduino projects are called “sketches” and when you start a new sketch, several additional files are also created.
“Newest: Arduino Interface (as of Q1 2012)
The main headings are “File” “Edit” “Sketch” “Tools” “Help” and several shortcut icons beneath “Verify”, “Upload”, “New”, “Open”, “Save”, and at the far right, the “Serial Monitor”. Note that all these icons are also available from the main menus.

“Older” Arduino Interface
The main headings are “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 5 Minute Tutorials
To connect to your board,
  1. Launch the Arduino software by double-clicking the Arduino icon
  2. Plug one end of the USB into the Arduino and the other end into your computer.
  3. Your computer should detect the new device and tell you if it has installed correctly. At this time, two things can happen; if you have an older board using an FTDI chip (ex. Duemilanove based), Windows should detect it and you’re good to go to the next step. If you have a board which uses an ATMega chip to convert USB to serial (for example the UNO), you will need to install the drivers manually.
  4. Take a look at your board’s main processor chip (usually found between the pin headers) to see which you have. It will likely be the ATMega168, ATMega328, or a more powerful ATMEga640. ATMega1280 etc
  5. In the software, select “Tools” -> “Board” -> You will get a list of possible boards. 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.
  6.  In the software, select “Tools” -> “Serial Port” -> COM # (note that if you have several COM ports, you will need to go to Device Manager to see which COM port is assigned to your board.
You’re now ready to start coding!

Lesson 2 Hardware:

  1. Computer / Laptop or Netbook
  2. Arduino Microcontroller
  3. USB to Serial Adapter (if your microcontroller does not have a USB port)
  4. Appropriate USB cable (Arduino boards draw power from the USB port – no batteries yet)
The Arduino language is CASE SENSITIVE: a capital letter is not the same as a lower case letter. The following code represents the minimum in order for a program to compile:
Arduino 5 Minute Tutorials
The “void 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 “void loop()” section is the part of the code that loops back onto itself and is the main part of the code. In the Arduino examples, this is called “Bare Minimum” under File-> Examples -> Basics. 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
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 at the beginning of every line. Comments are used used to explain the code textually. Good code always has a lot of comments.*/

Serial Communication

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 to communicate at a baud rate of 2400, but your transmitter is transmitting at a different rate (for example 9600), the data you get will not make sense. To set the baud rate, use the following code:
void setup() {
Serial.begin(9600);
}
9600 is a good baud rate to start with. 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:
Arduino 5 Minute Tutorials
Verify the program by pressing the “verify” button (looks like a “play” button in order version or a check sign in Arduino 1.0); 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) and capitalization.
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 in the old software, or what looks like a magnifying glass in the new software). When you select the serial monitor, make sure the baud rate selected is the same as in your program. If you want to save all your programs, we suggest creating a new folder called “reference” and save this program as Hello World.

Blink LED Program

Connect the board to the computer if it is not already connected. In the Arduino software go to File ->  Examples -> Basics -> Blink LED. The code will automatically load in the window, ready to be transferred to the Arduino. Ensure you have the right board chosen in Tools -> Board, and have the right COM port as well under Tools -> Serial Port. If you are not sure which COM port is connected to the Arduino, (on a Windows machine) go to Device Manager under COM & Ports.
Press the “Upload” button and wait until the program says “Done Uploading”. You should see the LED next to pin 13 start to blink. Note that there is already a green LED connected to most boards – you don’t necessarily need a separate LED.

Understanding Blink LED Code

From Lesson 2 you will recognize the basic code void setup(){} and void loop(){}. You will also recognize the green commented sections. The three new lines of code you have not seen before are:
pinMode(13, OUTPUT);
This sets pin 13 as an output pin. The opposite, being INPUT, would have the pin wait to read a 5V signal. Note that the ‘M’ is capitalized. A lower case ‘m’ would cause the word “pinmode” to not be recognized.
digitalWrite(13, HIGH); and digitalWrite(13, LOW);
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. Note that the ‘W’ is capitalized.
delay(1000);
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). Note that during a delay, the microcontroller simply waits and does not execute any additional lines of code.

Special Note

Pin 13 incorporates a resistor with the LED, whereas none of the other digital pins have this feature. If you want to connect one or more LEDs to the other digital pins, you need to add a resistor in series with the LED.

Lesson 3 Hardware:

  1. Computer / Laptop or Netbook
  2. Arduino Microcontroller
  3. USB to Serial Adapter (if your microcontroller does not have a USB port)
  4. Appropriate USB cable (Arduino boards draw power from the USB port – no batteries yet)
  5. Potentiometer (rotary or linear) Example: DFRobot Rotation Sensor
  6. Optional secondary LED.
Open the sample sketch “AnalogInput” under File -> Examples -> Analog. The comments section has been reduced below to make the code clearly visible.
We see several new lines of code here:
int sensorPin = A0;
The “int” is short for “integer”. The name “sensorPin” was chosen only to describe what the variable represents; “sensor pin”. The fact that the ‘P’ is capitalized makes it easier to see that it is actually two words, since spaces cannot be used. The integer “sensor pin” is equal to A0, where “A0″ is Analog pin 0 on the Arduino. On its own, “A0″ is not a reserved term. However, when used in context, the system recognizes it as analog pin 0. The line must be ended with a semicolon. By declaring a variable in the setup, you can use the term, which in this case is “sensorPin”, throughout the code instead of “A0″. There are two main benefits to this:
1) It makes the code more descriptive
2) If you want to change the value of the variable, you only need to do it in one place.
sensorValue = analogRead(sensorPin);
This line uses the term “analogRead” in order to read the voltage of an analog pin. Most Arduino microcontrollers use 10 bit analog (voltage) to digital (numeric) conversion, which is 210 possible numbers = 1024. Therefore a voltage of 0V corresponds to a numeric value of 0. A voltage of 5V corresponds to a numeric value of 1024. Therefore a value of 3V would correspond to a numeric value of:
3/5 =x/1024, x = 3*1024/5 = ~614
Alternatively you could have written: sensorValue = analogRead(A0);
int ledPin = 13;
Once again, the term “ledPin” is not a reserved word in Arduino, it was chosen to describe which pin was connected to the LED. The value “13″ is a normal value, but just like “A0″, when used in context represents pin 13.
int sensorValue = 0;
The term “sensorValue” is not a reserved term either.
Connect the potentiometer to pins A0, 5V and GND. The middle (wiper) lead is the one to connect to the analog pin and the voltage varies on this pin. The orientation of the other two pins does not matter. The other option is to connect the potentiometer to pins A0, A1 and A2. However, you will need to add the following code under void setup():
digitalWrite (A1, LOW);
digitalWrite (A2, HIGH);
This sets the corresponding pins to 0V (GND) and 5V (PWR). Once the potentiometer is connected, upload this sketch 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. Correspondingly, the LED will blink with a faster or shorter delay.
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 read:
int sensorpin = 5;
If the system does not work, check the syntax and ensure the code uploads correctly. Next, check the connections to the potentiometer ensuring that the middle lead goes to the correct pin, and the other pins are powered at 0V and 5V. 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. If the resistance is erratic, you need a new potentiometer.
Now what if you want to see the value yourself? Take a look at the code above and write it in the Arduino interface as a new sketch. Some new code you will see is:
Serial.println(sensorValue);
This sends the value contained in the variable “sensorValue” serially via the USB plug and digital pin 1. Verify, then upload this sketch to your Arduino. Once it is done, press on the “magnifying glass” located towards the top right of the window. This is the “Serial monitor” and monitors communications being sent and received by the Arduino. Here you must verify that the Baud rate is also 9600, or else you will see garbage.
If you did not want the values to appear on a new line every time, you could write
Serial.print(sensorValue);

Lesson 4 Hardware:

  1. Computer / Laptop or Netbook
  2. Arduino Microcontroller
  3. USB to Serial Adapter (if your microcontroller does not have a USB port)
  4. Appropriate USB cable (Arduino boards draw power from the USB port – no batteries yet)
  5. IR Distance sensor (preferably Sharp) and corresponding cable
  6. Push button and corresponding cables to connect to Arduino

Infrared distance sensors are useful for measuring distances without actually touching 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) so you can attach wires.
  1. Connect the red wire to +5V on the Arduino
  2. Connect the black wire to Gnd on the Arduino
  3. Connect the yellow wire to an analog pin on the Arduino (in this case we chose A2)

Arduino 5 Minute Tutorials
Arduino 5 Minute Tutorials
Since the sensor is connected to the analog input of the Arduino, the code is identical to that of the potentiometer:
Arduino 5 Minute Tutorials
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 a solid object or wall, the values should change between 0 to 1023. You can now read values and use them within your code. Check the range for yoursensor (not all sensors can read from zero cm); note that some sensors have a minimum distance – although it is always listed in the specifications, try to find it by experimentation. To convert the values to actual distances (in cm or inches), consult the user guide of the sensor.

Arduino and Push Buttons

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 push button is used to turn on the LED connected to pin 13. The line
digitalWrite(ledPin, status);
turns the ledPin (in this case assigned to digital pin 13) HIGH (1) or LOW (0) depending on the status variable. We initially set the status to be low (0).

Arduino 5 Minute Tutorials

Lesson 5 Hardware:

  1. Computer / Laptop or Netbook
  2. Arduino Microcontroller
  3. USB to Serial Adapter (if your microcontroller does not have a USB port)
  4. Appropriate USB cable (Arduino boards draw power from the USB port – no batteries yet)
  5. Standard servo motor (current consumption <50mA)
  6. Pin headers / cables
Controlling a servo motor directly from the Arduino is quite easy. However, 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. When powering the servo directly from the Arduino board:
  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

Arduino 5 Minute Tutorials
Alternatively, you can plug the servo’s wire into three adjacent pins, and set the pin connected to the red lead to “HIGH” and the pin connected to the black lead to “LOW”. If you want to use a more powerful servo, or if you want to connect it to a separate power supply, you would connect the battery / power supply’s red (5V) and black (GND) wires to the servo’s red and black wires, and connect the signal wire to the Arduino. Note that you also need to connect the batter’s GND line to the Arduino’s GND pins (“common ground”).
Arduino 5 Minute Tutorials
pinMode(pin number, OUTPUT);
This sets a pin number as dedicated input or output. In this case, we called the pin “servopin” and assigned it 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 (usually between 500us and 2500us) to the onboard electronics, which is repeated every ~20ms. This pulse corresponds to a servo position, usually from 0 to 180 degrees.
  • 5V for 500 microseconds = 0.5 milliseconds and corresponds to 0 degrees
  • 5V for 1500 microseconds = 1.5 milliseconds and corresponds to 90 degrees
  • 5V for 2500 microseconds = 2.5 milliseconds and corresponds to 180 degrees
  • The relationship is linear, so use mathematics to determine the pulse which corresponds to a given angle. Note that if you send a signal that is greater or lower than the servo can accept (for example, Firgelli linear actuators accept 1 to 2 ms), you might damage the actuator.
Another option for controlling servos is to use the Arduino “servo library” (previously separate from the basic Arduino software, it is now included with V1.0). The servo library 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.

Lesson 6 Hardware:

  1. Computer / Laptop or Netbook
  2. Arduino Microcontroller
  3. USB to Serial Adapter (if your microcontroller does not have a USB port)
  4. Appropriate USB cable (Arduino boards draw power from the USB port – no batteries yet)
  5. Standard servo motor (current consumption <50mA)
  6. Pin headers / cables
  7. Bend /stretch sensor and/ or Force 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.
Arduino 5 Minute Tutorials
If you want a pre-made circuit, consider the Phidgets voltage divider:
Arduino 5 Minute Tutorials
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 themicrocontroller. The microcontroller’s on-board analog to digital converter (ADC) interprets this voltage and assigns it a number which you can use in your code. For 10 bit ADC (210), 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.
To get sample code, open the Arduino software and go to File -> Examples -> Analog -> AnalogInOutSerial
The video above shows a bend sensor connected to an Arduino, and the Arduino is connected to a small servo motor. The analog value associated with the flex sensor is read by the Arduino, and that value is converted to a rough position. You would merge the Analog example code with the servo code, and add a single line to convert the 0 to 1024 value to 0 to 180 degrees. It is easy to see how, with many of these sensors, you can create a data glove which controls a robotic hand.

Lesson 7 Hardware:

  1. Computer / Laptop or Netbook
  2. Arduino Microcontroller
  3. USB to Serial Adapter (if your microcontroller does not have a USB port)
  4. Appropriate USB cable (Arduino boards draw power from the USB port – no batteries yet)
  5. Analog accelerometer, gyroscope and/or IMU
  6. Connectors (between the IMU and the Arduino
Accelerometers, gyroscopes and IMUs are incredibly useful little sensors which are being integrated more and more into the electronics devices around us. These sensors are used in cell phones, gaming consoles such as the Wii wireless remote control, toys, self-balancing robots, motion capture suits and more. Accelerometers are used mainly to measure acceleration and tilt, gyroscopes are used to measure angular velocity and orientation and IMUs (which combine both accelerometers and gyroscopes) are used to give a complete understanding of a device’s acceleration, speed, position, orientation and more.
Arduino 5 Minute Tutorials
When choosing an accelerometer, gyroscope or IMU, it is also important to consider the type of output; depending on the type of sensor, readings can be output as:
  • Serial data (Tx pin)
  • I2C (SDA, SCL)
  • Analog
  • TTL
  • others…
In this tutorial we’re only going to cover analog output. The code shown below includes the output for a single axis sensor and factors in the rest value.
Arduino 5 Minute Tutorials

Accelerometer

Accelerometers measure acceleration in one to three linear axes (x, y, z). A single axis accelerometer can measure acceleration in whichever direction it is pointed. This may be good for a rocket, an impact, a train or other scenario where the device really moves in one basic direction. Knowing the acceleration and time, you can use mathematics to find the distance traveled by the object. There are fewer and fewer single and double axis accelerometers on the market because a triple axis accelerometer can do so much more. Thanks to low manufacturing costs the three axes accelerometers are not much more expensive than single or double.
Acceleration due to gravity is a constant and is in fact measurable using an accelerometer. When placed parallel to the ground, acceleration due to gravity would only be “felt” by one axis. However, when tilted, this acceleration would appear as components of two (or three) axes. You can get an idea of how to use an accelerometer to measure tilt here and here.
Connect the accelerometer to the Arduino; each output pin goes to one of the analog pins on the Arduino, the Vin pin goes to the 5V pin on the Arduino (read the user guide to ensure the Vin pin is 5V as opposed to 3.3V), and connect the GND pin to the GND pin on the Arduino. Note that there is no need for additional electronics! Next, open the sample sketch File -> Examples -> Sensors -> ADXL3xx. Upload to the Arduino and see the values change.
In order to choose the right accelerometer, consider the maximum linear acceleration the sensor will be subjected to. If you are planning to add an accelerometer to a small mobile robot, you will likely use a 2g accelerometer (even that is likely overkill), whereas if you are attaching it to a rocket, a 16g accelerometer is likely a better choice. When connected to a 10 bit ADC, the 2g accelerometer will have an accuracy of 2 / 1024 = 0.002g, and the 16g accelerometer will have and accuracy of 16 / 1024 = 0.0156. Therefore if you only need a range of 2g, but purchase a 16g accelerometer, you will only have about 128 possible readings, instead of the full 1024. Conversely, if you choose a 2g accelerometer when you really needed a 16g, you will get a lot of “maximum (1024) “readings since the acceleration is “off the scale”.

Gyroscope

Gyroscopes measure angular velocity in α, β, γ (see image below). Gyroscopes can be used to help with stabilization and well as changes in direction and orientation. Unlike accelerometers, gyroscopes do not have a fixed reference, and only measure changes. To choose the right gyroscope for your needs, consider the maximum angular rate of change (degrees per second) your product will be subjected to. A remote control will likely rotate at less than 1 rotation per minute (360 degrees per second), while a rocket tumbling out of the sky may be rotating at 1500 degrees per second. When connected to the same microcontroller (10 bit for example), the 360 degree/s gyro will have an accuracy of 360 / 1024 = 0.35 deg/s, whereas the 1500 deg/s gyro will have an accuracy of 1500 / 1024 = 1.46 deg/s. Therefore if you chose a 1500 deg/s gyro when you only needed a 360 deg/s gyro, you will only get about 245 readings as opposed to 1024.
Courtesy: Wikipedia

IMU

An IMU (Inertial Measurement Unit) usually consists of an accelerometer and gyroscope and is used to measures an object’s orientation, velocity etc. Often additional sensors (magnetic, temperature) are included to improve accuracy. The number of “degrees of freedom” indicates the number of different axes measured by the chip. For example, combining a three axis accelerometer with a two axis gyroscope would be consider a 3+2 = 5 DoF IMU.

Additional Considerations

When using accelerometers, gyroscopes or inertial measurement units (IMUs) to obtain positions in space, it is important to note that there are several additional factors that will affect the readings, the main obstacle being the sampling rate. Microcontrollers require a certain amount of time to read values being provided to them by the sensor, and because of this, the values between these readings are lost. There are several mathematical methods (a Kalman filter 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 micro-electro-mechanical systems (MEMS) attempt to describe how temperature affects the output.
Want to learn more? Start with the material put out for free by Analog Devices, makes or many MEMS acceleromters, gyroscopes and other sensors.

Socializer Widget By Blogger Yard
SOCIALIZE IT →
FOLLOW US →
SHARE IT →

0 comments: