Posts Tagged “code”

This mini project shows how to connect the Sparkfun Compass Module (SKU SEN-07915) to both the Arduino Uno and the Arduino Mega 2560. As these two Arduino boards are 5V devices, and the Compass Module is a 3.3V module, the I2C bus must be translated. This is done using the Logic Level Converter from Sparkfun (SKU BOB-08745).

To help, included here are two diagrams of the wiring needed. Note that the Mega has specific I2C pins available while the Uno uses Analog pin 4 for SDA and Analog pin 5 for SCL. SDA is the data line, and SCL is the clock line.

The Arduino has pull up resistors built in and the Compass Module has them as well so there is no need to add them in this case.

Both the wiring diagrams and the code will read the compass module twice per second and send it out via serial to the computer where it can be viewed by a serial aware program like the serial viewer in the Arduino software.

Wiring up the Uno, connect the following:

  • +5V and GND connects from the UNO to the “hv” side of the level converter
  • +3.3V and GND connects from the UNO to the “lv” side of the level converter
  • Connect Analog pin A4 from the UNO to Ch1 TXO on the level converter
  • Connect Analog pin A5 from the UNO to Ch2 TXO on the level converter
  • +3.3V from the UNO also connects to the VCC on the compas module
  • GND from the UNO connects to the GND on the compas module
  • SDA on the compas module connects to Ch1 TXI on the level converter
  • SCL on the compas module connects to Ch2 TXI on the level converter

See the following picture for details

Compass - Uno

How to wire the compass module to the Arduino Uno via the level shifter from Sparkfun
Wiring up the Uno, connect the following:

  • +5V and GND connects from the MEGA to the “hv” side of the level converter
  • +3.3V and GND connects from the MEGA to the “lv” side of the level converter
  • Connect  pin 21 SCL from the MEGA to Ch1 TXO on the level converter
  • Connect pin 20 SDA from the MEGA to Ch2 TXO on the level converter
  • +3.3V from the UNO also connects to the VCC on the compas module
  • GND from the UNO connects to the GND on the compas module
  • SDA on the compas module connects to Ch1 TXI on the level converter
  • SCL on the compas module connects to Ch2 TXI on the level converter

See the following picture for details

How to wire the compass to the Mega 2560

How to wire the Sparkfun Compass Module to the Arduino Mega 2560

The source code.

And here is the code, inspired by the code posted by Vaibhav Bhawsar. Note the source is the same for both boards.

#include <Wire.h>              // Where all the routines for controlling
                               //    the I2C bus are
int HMC6352 = 0x42;            // device address from the data sheet
int slaveAddress;              // variable to hold the slave address
int ledPin = 13;               // LED on the Arduino board
boolean ledState = false;      // state of the LED for the flash routine
byte headingFromCompass[2];    // array to store the two byte data from compass
int i;                         // array element id
int heading;                   // calculated heading for printing

void setup()
{
  slaveAddress = HMC6352 >> 1;   // The wire library only wants the 7 most significant
                                  //   bits of the address.
  Serial.begin(9600);            // Start Serial, change baud rate to suit
  pinMode(ledPin, OUTPUT);       // Set the LED pin as output to show program is running
  Wire.begin();                  // Initialise the Two Wire Interface (I2C)
}

void loop()
{
  ledState = !ledState;
  if (ledState)
  {
    digitalWrite(ledPin,HIGH);
  }
  else
  {
    digitalWrite(ledPin,LOW);
  }

Wire.beginTransmission(slaveAddress);
  Wire.send(0x41);                          // Send the Get Data command
  Wire.endTransmission();
  delay(10);                                // The HMC6352 needs 70us delay
  Wire.requestFrom(slaveAddress, 2);        // Request 2 bytes of data (MSB then LSB)
  i = 0;                                    // This is used as the array element pointer for
                                            //   data
  while(Wire.available() && i < 2)          // We're receiving data
  {
    headingFromCompass[i] = Wire.receive(); // Put the data into the array element
    i++;                                    // increment for the next data piece
  }
  heading = headingFromCompass[0]*256 + headingFromCompass[1];  // Combine MSB and LSB
  // Change the following output to suit your application
  Serial.print("Heading: ");
  Serial.print(int (heading / 10));     // The whole number part of the heading
  Serial.print(".");
  Serial.print(int (heading % 10));     // The fractional part of the heading
  Serial.println(" degrees");
  delay(500);
}

 

Comments No Comments »

If your using a different linker file than what comes with the compiler you will need to set the /p option for the linker to specify your processor manually. For some reason v3.38 doesn’t pick this up automatically. If this is not done, the following error message will probably be recieved:

Error – Device not specified. Use /p option to specify a device.

Setting the /p option is simple, click ‘Project – Build Options – Project’, go to the MPLINK Linker tab. Then check the ‘Use Alternate Settings’ check box.

The default string will look like:

/m”$(BINDIR_)$(TARGETBASE).map” /w /o”$(BINDIR_)$(TARGETBASE).cof”

Change this to:

/m”$(BINDIR_)$(TARGETBASE).map” /w /p18F2450  /o”$(BINDIR_)$(TARGETBASE).cof”

using your processor instead of the /p18F2450 in the above example. Note, there is no space between the p and the 1. It’s just the font makes it look like there is.

Comments No Comments »

Had the need to create some strings in the form of an array of hex codes for the charachters the other day which was a little cumbersom, so put together some quick php code to do it for me. So thought I’d share it with you. You can access it at http://electronics.trev.id.au/str2hex.php. Just enter your string and click convert.

Comments No Comments »

Well I’m going to run with the PIC24 for the time being and use the Microcontrollers – From Assembly Language to C Using the PIC24 Family book, but jumping to chapter 8 as the assembly language is not what I want at the moment. It’s learning about C and the PIC24. Anyway, as I’m using the Explorer 16 board, I’m going to share the differences in the sample code that should apply. This is the first installment for chapter 8.

My first observation is the author hasn’t identified the file names of the examples in his book and as his book doesn’t include the full text of the samples, it’s a bit of guess work to find them. So I’ll help you along your way. The first example on page 258 is called “ledflash_nomacros” and it’s in the chap8 folder.

One thing you need to do with all the examples when using the Explorer16 board is define the macro EXPLORER16_100P either in the include/pic24_all.h file or it must be added to the MPLAB project (Use Project->Build Options-> Project, click on the MPLAB C30 tab, and in Macro Definitions click ‘Add’, and add EXPLORER16_100P). Where it makes sense, I’m going to use the macro definition to keep the original code in tact while adding specific changes for the Explorer 16 board.

Note: the PIM I’m using is the PIC24FJ128GA010 100pin PIM (Microchip part number MA240011).

So here is the source for main() for this exercise. The rest of the file should remain the same.

void a_delay(void) {
  uint16 u16_i,u16_k;
  // change count values to alter delay
  for (u16_k=1800; --u16_k;) {
    for (u16_i = 1200 ; --u16_i ; );
  }
}
int main(void) {
  configClock();    //clock configuration
  /********** GPIO config **********/
#if defined(EXPLORER16_100P)
// For the explorer 16, we're not going to use the open drain as the LED is
// wired from ground through a current limit resistor direct to pin 91 of
// the PIC24FJ128GA010
  _TRISA6 = 0;         //Config RB15 as output
  _LATA6 = 0;          //RB15 initially low
  while (1) {           //infinite while loop
    a_delay();          //call delay function
    _LATA6 = !_LATA6;  //Toggle LED attached to RB15
  } // end while (1)
#warning using Explorer16 code
#else // not EXPLORER16_100P
#ifdef _ODB15          //PIC24F CPU header files define this instead of ODCB15
  _ODB15 = 1;          //enable open drain
#else
  _ODCB15 = 1;          //enable open drain
#endif
  _TRISB15 = 0;         //Config RB15 as output
  _LATB15 = 0;          //RB15 initially low
  while (1) {           //infinite while loop
    a_delay();          //call delay function
    _LATB15 = !_LATB15;  //Toggle LED attached to RB15
  } // end while (1)
#warning NOT using Explorer16 code
#endif  //#if defined(EXPLORER16_100P)
}

When you open the project file (.mcp) for this exercise you will notice the linker script in the linker scripts section of the files explorer. You need to delete this one. No need to add another one as MPLAB will pick up the right one automatically if you have used the default install.

You will notice in this code segment I’ve added a couple of warning messages for the compiler to see what parts of the code it compiles. You can have them in or take them out. They are there just to make sure the compiler is doing what is expected.

Now if you try and use DEBUG as per the default project, you will see a number of failures and the program wont run. The first will be a pop up message:

  • ICDWarn0046:  Because clock switching is enabled, MPLAB ICD 2 requires the user to cycle target power after a program operation.

And then a message in the output window:

  • ICD0083: Debug:  Unable to enter debug mode.  Please double click this message for more information.

I chose to ignore and change to a RELEASE build to see it working. Do this by following these steps:

  1. Change the DEBUG drop down to RELEASE
  2. Select a programmer (Programmer – Select Programmer). I’m using the MPLAB ICD2 so the rest talks about what happens with the ICD2.
  3. Rebuild all (Ctrl+F10)
  4. When you get the BUILD SUCCEEDED message, program the device (Programmer – Program). You will get the ICDWarn0046 message, just click OK.
  5. When you get the “MPLAB ICD 2 ready for next operation”, disconnect the ICD2 and watch your program run. The LED second from left will flash at about once per second.

Comments No Comments »