Accessing the compass programmatically

Now that the device is connected, you'll need to configure access via the software. Following are the steps:

  1. In order to access the compass capability, you'll need to enable the I2C library on Raspberry. The first step in enabling the analog-to-digital converter (ADC) is to enable the I2C interface. The I2C interface is a synchronous serial interface and provides more performance than an asynchronous Rx/Tx serial interface. The SCL data line provides a clock while the data flows on the SDA line. The bus also provides addressing so that more than one device can be connected to the master device at the same time. To enable this bus, run sudo raspi-config and select the 8 Advanced Options, as follows:

    Accessing the compass programmatically

  2. Then go to the A7 I2C selection and enable the I2C, as shown in the following:
    Accessing the compass programmatically
  3. Make all the selections to enable the I2C interface and load the library, and then reboot Raspberry Pi.
  4. You'll also need to edit the /etc/modules file and add the following two lines:
    Accessing the compass programmatically
  5. Reboot Raspberry Pi. Install the I2C toolkit by typing sudo apt-get install i2c-tools. You can see whether I2C is enabled by typing sudo i2cdetect -y 1, and then you should see something like this:
    Accessing the compass programmatically

You can see the device at 1e. Now you can communicate with your digital compass. Here are the steps:

  1. You'll need to create a Python program. Before you create your Python code, you need to install the SMBus capability to access I2C. This can be done by typing sudo apt-get install python-smbus.
  2. Now reboot Raspberry Pi and create the following Python code:
    Accessing the compass programmatically
  3. Run the code by typing python compass.py, and you should see the following:
    Accessing the compass programmatically
  4. The last step is to create a python file and function that can be imported into your tracked vehicle python program. Here is the python code:
    Accessing the compass programmatically

Note

Now you can add direction to your project! As you move the device around, you can query the bearing value to see the direction of your tracked vehicle. Make sure that you position your compass away from your electronics, otherwise their magnetic fields may cause distortion on your compass measurements.

The program we just saw is a basic program. If you go to http://think-bowl.com/raspberry-pi/i2c-python-library-3-axis-digital-compass-hmc5883l-with-the-raspberry-pi/, you can find more about the other features that are available with this library. Now, you can add the compass capability with just a few lines of code to your tracked robot control program.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.171.121