You are on page 1of 7

Intro IMU/MATLAB

IMU-1

Arduino Refresher and IMU/MATLAB Interfacing Introduction


Learning Objectives: The student who successfully completes this lab will be able to: Regain their working knowledge of how to use the Arduino IDE Acquire and integrate third-party libraries into the development environment Understand the basics of the communications mechanisms (I2C and RS-232/UART) between the Arduino and 9DOF IMU board, and Arduino and PC Use MATLAB to acquire and process information logged by the Arduino's Serial connection

Components:
Qty. 1 1 1 1 Item A PC with a MATLAB license and Arduino IDE installed Arduino microcontroller board (Atmel ATmega(c)-based Uno or Mega) USB cable Pololu 9DOF IMU board (MinIMU-9 v2 Gyro, Accelerometer, and Compass)

Introduction
The product page for the IMU from Pololu that we're using for this lab is http://www.pololu.com/catalog/product/1268. This product overview page contains a wealth of practical information about how the board works as well as providing links to Arduino libraries and examples/demos to facilitate its use. The board itself contains two MEMS sensor chips on the board (gyro and accelerometer/magnetometer/temp-sensor) and support circuitry to allow it to interface to our 5V microcontroller hardware1. This IMU uses I2C/IIC (which only Atmel refers to as two-wire interface, TWI), which is one of the popular standards used to connect devices, like our IMU sensor board, up to a microcontroller. We'll only present enough information about I2C here so that you can get a grasp for how/why it works. For more detail, consult either Wikipedia, or the NXP/Philips specification for the I2C standard. The IMU board will eventually be connected to an azimuth-elevation positioning stage, so that one may apply closed-loop control to the positioning of the device (in this case a camera, I believe) on which it is mounted. By using the IMU one should be able to monitor the device's rotation, tilt and absolute angular positioning (w.r.t magnetic north) in 3-dimensional space.

Background
As stated above, the product page actually provides a sound introduction to functioning of the IMU board, its interfacing to the Arduino, and the software required to demonstrate a sample use of the device. References to the datasheet for both of the ST Microelectronics MEMS sensors on-board

1 Very few MEMS sensors operate at 5V, but at 3.3V instead. Interfacing to 5V systems usually involves both taking care of the differences in both power supply and I/O voltage levels. Eric B. Wertz & SJSU Dept. of Mechanical Engineering Rev 0.1.4 06SEP2013

Intro IMU/MATLAB

IMU-2

are also provided. The product page should be understood in its entirety and the datasheets at least reviewed before venturing too far into this laboratory exercise. I2C I2C requires only two I/O lines called SCL and SDA, which are for clock and data respectively2. These two lines go to every I2C in your system and are used to send data bi-directionally. No additional I/O pins are needed to connect (ideally) up to 127 devices, making it incredibly pin cheap. All devices synchronize their access on the bus clock signal CLK which is generated by the MCU's hardware I2C peripheral circuitry, and exchange data on the data line. Devices detect contention on the data line themselves so that multiple devices can co-exist on just one data line. Both lines are pulled-up to VCC when not used and pulled down by either the master or slave for binary signal exchange to occur. Each connected device must have its own address on this shared-bus system. This address may be either hardcoded for a particular device, or may be partially configurable by tying address configuration pins on the IC high or low to determine its unique address. This configurability allows more than one of the same type of device to be connected to the same bus concurrently (for instance, multiple temperature sensors, or I/O expanders). The magic of data exchange is handled by the I2C interface circuitry in the connected device(s) and almost always managed by a hardware I2C peripheral in the MCU, usually at 100k or 400k bits-per-second. Although it is possible to bitbang I2C using software in the MCU, it's usually a last resort. This isn't generally necessary because at least one I2C peripheral bus is supported in most modern MCUs. Nevertheless, there are one or more software libraries for the Arduino that can do this, if necessary. Communicating with the MCU's I2C peripheral is done through configuration and use of a relatively small number of dedicated I/O registers. Through these local MCU registers read and write data commands traverse the bus to get at the registers in the connected device. Every device lists its registers and their corresponding functions in its datasheet. Using I2C on the Arduino is made easier through the use of the Wire library. Refer to the Wire library in the Arduino Reference for more information on how it's used (http://arduino.cc/en/reference/wire). However, the demo code from Pololu wraps the calls to the Wire library/object's methods in other helper functions specific to the IMU, so it's not necessary to know too much (yet) about how it and I2C works, as long as you start with the demo code. If you were to acquire a different IMU (or any other I2C chip) without some type of Arduino sample code or library, you'd have to start digging into the Wire library yourself. Loading the IMU software pregame It is assumed that the Arduino IDE has been properly installed on whichever machine you will be using for this lab. If not, you must do this now. Follow the instruction on the Arduino website carefully, as you can easily get your machine into an Arduino-repellent state by not getting the required drivers installed properly. It is recommended to use the most recent 1.0.x (not the 1.5.x !3)

2 Since our system will not be electrically isolated (which is fairly typical), a GND connection must also be shared between the MCU and IMU boards. 3 Currently the 1.5.x versions of the Arduino software are intended to be used with the Arduino Due. As of 1.5.2, the software still works poorly enough on that platform that I wouldn't trust using it on non-Due platforms, even if it were supported. Multiple 1.0.x releases have happened since 1.5.2 came out, so it has to be out-of-date for ATmega-based Arduinos. Eric B. Wertz & SJSU Dept. of Mechanical Engineering Rev 0.1.4 06SEP2013

Intro IMU/MATLAB

IMU-3

version of the IDE, namely 1.0.5 at the time of this writing. As of 1.0.5, the Arduino IDE comes with a software installer, which makes installation a little more elegant than in the past. Each of the two Arduino library ZIP files from Pololu must be unpacked and placed (correctly) into your MyDocuments/Arduino/libraries4 directory so that the Arduino IDE can find them. Hopefully you remember the guidance I gave in ME106 about the issues around installing third-party libraries on your machine. If case you don't... the bottom line is you should never be changing the contents of the directory tree of software that you downloaded from arduino.cc and installed on your machine. The (only) place that you should be making changes is in your home directory's Arduino user directory (on Windows this is MyDocuments\Arduino). This is the directory subtree in which your sketches go (your Sketchbook), as well as any libraries you pick up that support hardware that you're using. Libraries go into MyDocuments\Arduino\libraries, a directory that you may have to create if you don't have one already once you start installing some. By keeping all of the files that you rely on in MyDocuments\Arduino, you make it a trivial exercise to both upgrade from one Arduino software version to the next which happens every few months. It also makes it easy to pick up all of your code pieces from one machine and get them going on another -- like back-and-forth from your PC and the E135 lab machines. I'm not sure that I've ever had to make changes in my installed software directory -- all supplementary files (libraries, sketches, etc.) should be added made in your Arduino working directory. In case you don't remember, never figured out, or never knew, the Arduino IDE will only be able to find libraries that are in place when it first starts up. If you later install more libraries you have to shut down all IDE windows and restart. The contents of your (File->) Sketchbook may behave the same way, although you can always use (File->) Open to open new sketches at any time. Loading the IMU software Unless we have a single ZIP file for you to unpack right into your Arduino directory, you should download the two libraries (L3G and LSM303) and the MinIMU9AHRS application as described in this section. Any single ZIP file that we may or may not have for you has all of the directories correctly located relative to your home Arduino directory, saving you have to download and mangle their individual contents. Start by downloading the three ZIP files for the libraries and the application from Pololu's product page (these should be clickable links): L3G, LSM303 and MinIMU9AHRS. Unpacking the ZIP files afterwards requires removing all of the superfluous directory levels that get created when extracting them into MyDocuments/Arduino/libraries. Basically, you need to take the bottom-most directory and drag it up into the libraries directory. After you do this you can/should delete the other (nearly) empty directories that contained that directory. The end product must, according to Arduino law, use the same name for the directory containing source .ino file as the .ino file itself. Each ZIP file also contains a .textile file which appears to be some type of documentation file that's not directly readable. I've been throwing mine away and have been referencing the documentation from the GitHub directory from which the ZIP files are downloaded. So, for instance, if you download a library called Foo to support the new Foomatic hardware thingama-jig that you just bought, the path to the primary library code that you got should ultimately end

4 For legibility I generally exclude the stupid space in My Documents, but it's nevertheless there on your computer. Eric B. Wertz & SJSU Dept. of Mechanical Engineering Rev 0.1.4 06SEP2013

Intro IMU/MATLAB

IMU-4

up in MyDocuments\Arduino\libraries\Foo\Foo.ino. Often you will get a ZIP file containing source code that has an extra level of directory level in it that you manually have to eliminate. For example, when you unpack L3G-master.zip into the libraries directory, what you'll be left with is something like L3G-master/L3G/*. Take the L3G directory and drag (move) it up into libraries, after which you can/should delete L3G-master and everything below it. The sample Arduino sketch (MinIMU-9-Arduino-AHRS) ZIP file should be unpacked into the same directory as the libraries except that the destination directory should ultimately be MyDocuments/Arduino. You should note that there is a .py file lurking around, and I just put it into the same directory as the sample sketch's .ino source files, for lack of a better place. This file is a Python program that runs on the PC that uses the serial output from the Arduino to produce a graphical visualization, as shown on Pololu's product page. In the end, you should have a directory structure that looks like this: My Documents/ Arduino/ libraries/ L3G/ examples/ *.cpp, *.h, ... LSM303/ *.cpp, *.h, ... MinIMU9AHRS/ *.ino, *.py, ... Calibration Almost all sensors require some type of calibration, unless the manufacturer has gone to (relatively) extraordinary lengths to ensure that it works under all specified circumstances. For sensors that have a linear response in the desired operating range, getting two points to work is generally all that it takes to calibrate a sensor. Given a straight line in the X-Y plane, two points are necessary to determine both the slope and the Y-intercept for a given X. Unique (re-) calibrations may be required, however, at the temperature, pressure, humidity, or other ambient condition(s) in effect during the period of time in which the sensor is required to operate. The mark of a good sensor solution is the ease or infrequency of calibration, through thoughtful software and/or hardware design. Calibration of the IMU, for the purposes of this lab, is necessary for scrubbing the acceleration values that we will be reading from the accelerometer. Some calibration is performed at the (IC manufacturer's) factory, and internally the accelerometer handles variances in temperature by correcting outputs with an internal temperature sensor, but we'll have to take care of the rest. We'll be calibrating our sensor with the help of our local g, the earth's acceleration due to gravity, to normalize our sensor's output. This is done by observing the maximum and minimum values for all three axes, knowing that each should represent +1g and -1g at some point in its rotation, and hence produce some well-known

Eric B. Wertz & SJSU Dept. of Mechanical Engineering

Rev 0.1.4

06SEP2013

Intro IMU/MATLAB

IMU-5

values for its output at those points. Since these particular sensors are suppoed to be linear across their range, a simple linear scaling factor will be applied to the values reported by the device5. Question: Given the sensor characteristics documented in the datasheet for the LSM303, should we expect to have to scale output values from min_x...max_x, min_y...max_y, etc. or min_x...0, 0...max_x, min_y...0, 0...max_y, etc.? That is, is the reported zero-value guaranteed to be good, with all deviations to be scaled correspondingly? Why or why not? Performing the accelerometer calibration The LSM303 library comes with three example programs, one of which is Calibrate. We'll be using this to calibrate the accelerometer functions of the IMU. This program works simply by recording the maximum and minimum values read from each of the three axes of the accelerometer, remembering each. The idea is to rotate the IMU through all angles so that each axis reaches both its minimum and maximum values at some point. When completed one should then know the output values representing +1g and -1g along each axis. With this information any output values can be mapped to real acceleration values. You should note that what is going on here is more akin to compensating for the sensor's output errors rather than calibrating per se. This could be considered software calibration rather than hardware calibration of the sensor. Nonetheless, given the flexibility of software, it's often easier to (essentially) signal process the output rather than require some type of hardware calibration to be performed. Before connecting up hardware to the Arduino, it's always best to upload known (hopefully) safe code into the Arduino, because potentially anything could be on it from whatever it was last used for. After uploading Calibrate, unplug your Arduino and connect-up the IMU as follows: IIMU board VIN GND SDA SCL Uno board VIN GND A4 A5 Arduino Mega board VIN GND SDA(20) SCL(21)

Ensure that any unused wires connected to the IMU don't short to anything else by putting some electrical tape on them. At this point you should be able to plug in your Arduino and it should start to run. Open the Serial Console to view its output. Rotate the IMU through all of its orientations until none of the min and max values for any axis change any longer. You should see both the instantaneous values for all three axes as well as the three pairs of high and low-watermarks of accelerometer values. Action: Record these six values for your accelerometer, as they will be immediately below. Running the demo The calibration values that you generated with Calibrate are intended to be used in the demo sketch, MinIMU9AHRS, as described in its documentation. It should be fairly obvious where your

5 ME106 students should remember that there's a function in the Arduino library that makes mapping from one range of numbers to another particularly easy. Eric B. Wertz & SJSU Dept. of Mechanical Engineering Rev 0.1.4 06SEP2013

Intro IMU/MATLAB

IMU-6

calibration values need to go in the source code. Compile and upload the code to your Arduino, and open the Serial Console to view the output... which will likely look like a stream of garbage. Garbled output is usually the result of one of two issues, either the baud rate isn't correct between the two devices, or the output is binary rather than printable ASCII characters. In this case, it's the former. This is because the sample sketch sets the Serial Console baud rate (bit rate, essentially) from the default (9600) to 115200 using Serial.begin(). See if you can find this in the code (anyone having used the Arduino before should know where it's likely to be found). To change the baud rate in the Serial Console to match this, you must already have it open. Open it again, and use the pulldown in the bottom-right corner to choose 115200. Whenever the Serial Console is opened (or the baud rate changed, apparently), it resets the Arduino. Once this happens and the baud rate is set correctly, you should be able to see the output of the Arduino sketch properly. Tilting the IMU should produce some obvious changes in the content of the output. Action: Try to find the orientation of the board that produces 0,0,0 for the reported X,Y,Z angles. Determine which changes in orientation produce positive and negative angles along each axis. Do your expectations regarding the orientation of the board and the reported values match? Running the Visualization demo At the present time we do not have Python and the other required software detailed below installed on the E135 lab machines. However, if you are using your own laptops for the lab, feel free to try to get the visualization running. Only one attempt has been made to try this to date, on a very old WinXP machine, and the visualization program crashes. However, this isn't to say that it's known not to work, but rather that the versions of Python and support libraries are incompatible with the program, or perhaps even something else is going on that's not currently understood. We encourage you to try if you have the means to do so, as well as the time at the end of the lab. For the time being, skip this section of the lab. To run the 3D visualization program on your PC (and perhaps Mac?), you must have Python 2 installed. Python 2 is not the most recent version of Python, and isn't 100% backward compatible with Python 3, the current version of the language. Since you're unlikely to have any version of Python installed on your Windows machine, you will have to download and install it. Not only that, but this program depends on some other Python libraries, and those too must be downloaded and installed. In order, download and install the following files:
http://www.python.org/download/releases/2.7.5/ http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32 -218.win32-py2.7.exe/download http://sourceforge.net/projects/pyserial/files/pyserial/2.5/pyserial2.5.win32.exe/download http://sourceforge.net/projects/vpythonwx/files/6.05-release/VPython-Win32-Py2.7-6.05.exe/download

FIXME: Describe how to launch the Python program, and the COM port change that must be made in the source file. Capturing Arduino ASCII Output in MATLAB Learning Python is beyond the scope of what is expected in ME 190, so we're going to try to capture the data from the Arduino with Matlab and make use of it there. To do so, rather than using
Eric B. Wertz & SJSU Dept. of Mechanical Engineering Rev 0.1.4 06SEP2013

Intro IMU/MATLAB

IMU-7

the Serial Monitor built into the Arduino IDE, we're going to capture the output data directly using a Matlab program running on the PC, and at first, simply display it there instead. Reading information from a serial port isn't terribly different than reading information from a file, similar to how you probably did so in ME30. Ultimately you are just reading a stream of bytes from "somewhere". In the case of textual data it's ASCII text (rather than pure binary data), is often lineoriented, and perhaps has some extra formatting thrown in for readability (comma, space or tabseparated columns, etc.). Instead of reading data from a file, you're going to be reading it from a device -- in this case a COM (serial COMmunications port) on the PC. In addition to the name of the COM port, the program opening it needs to know the speed and options that the party on the other end of the COM port is also expected to be using6. While we're not going into too many of the details of COM (RS-232 standard) communications here, suffice it to say that the parameters other than speed (bit rate) that you need to know are 8,N,1, which stand for 8-bits, no parity, and 1 stop bit. There parameters are dictated by the Arduino side and must be adhered to by the other end of the connection, the (program running on the) PC. Also, as noted above, the data rate is 115200, rather than the default of 9600. This 115200,8,N,1 configuration information, along with the name of the COM port that is currently being used to talk to the Arduino, is all that you need to know to start getting data in, similar to reading data from a file. #serialPort new = serial('com9', 'baudrate', 115200, 'terminator' 'CR'); FIXME: Investigate Mathworks forum resource at http://www.mathworks.com/matlabcentral/fileexchange/26711-interacting-with-an-arduino-usingthe-matlab-serial-commands/all_files for guidance about collecting and plotting data.

6 This is exactly the same type of configuration (agreement) that must be performed between the Arduino and the Serial Console, above. The only difference is that your program is capturing this ASCII data, rather than simply displaying it as the Serial Console does. Eric B. Wertz & SJSU Dept. of Mechanical Engineering Rev 0.1.4 06SEP2013

You might also like