Arduino with a KXPS5 Accelerometer Eval Board
After reading my latest Make: magazine, there was a great article by a guy who made a simple spectrometer from an Arduino. I'd paid scant attention to this open source board in the past, not realising it was a complete development environment. It can be used on my laptop or on my Mac too.
I did a search on UK ebay and found this shop selling Diecimilas for 15 quid! I ordered one, a protoshield and an LCD shield (the shield idea is so cool). I've got an ethernet shield on the way! Right! First up, a 3-axis accelerometer evaluation board I've had lying around without use for ages.
The Wire library is, umm, confusing to say the least, but after reading Keith's Electronic Blog on Arduino I2C, it all became clear. Bugger me, it worked first time! The picture shows the KXPS5 linked directly to the Arduino's 3.3V supply and A4 (SDA) and A5 (SCL). The screen behind is showing the 12 bit values of X, Y and Z. Code below if you want it.
Reading the datasheet for the ATmega168 on the train home was an eye opener. More than one work register! Insane! I have nothing but praise for the Arduino. What would've been a world of pain using a PIC was a walk in the park. I did it all in a couple hours on one evening. 10/10.
/*
* Read the X, Y, Z registers from the KXPS5 continually and put
* their hex values out on the serial link. Using I2C on A4,A5.
* Keith Marsh http://www.keithmarsh.com/
* Free for any use whatsoever
* Thanks to Keith's Electronics Blog
* http://www.neufeld.newton.ks.us/electronics/?p=241
*/
#include <Wire.h>
#define KXPS5_ADDR (0x18)
#define KXPS5_XOUT_H (0x00)
#define KXPS5_RESET_WRITE (0x06)
#define KXPS5_CTRL_REGC (0x0C)
#define KXPS5_CTRL_REGB (0x0D)
void setup()
{
Serial.begin(9600);
Wire.begin();
// Set the KXPS5 up
Wire.beginTransmission(KXPS5_ADDR);
Wire.send(KXPS5_CTRL_REGB);
Wire.send(0xC0); // CLKhld:B7 = 1, Enable:B6 = 1, FFIen:B1 = 0
Wire.endTransmission();
// Reset it
Wire.beginTransmission(KXPS5_ADDR);
Wire.send(KXPS5_RESET_WRITE);
Wire.send(0xCA); // Super special secret reset code
Wire.endTransmission();
}
void loop()
{
int x,y,z;
// Output the XH register address and read 6 values from there (incl)
// Each axis value is 12 bits, all Hi and top 4 from Lo.
//
Wire.beginTransmission(KXPS5_ADDR);
Wire.send(KXPS5_XOUT_H);
Wire.endTransmission();
Wire.beginTransmission(KXPS5_ADDR);
Wire.requestFrom(KXPS5_ADDR, 6);
if (Wire.available()) {
x = Wire.receive() << 4;
} else {
x = 0xf0ad;
}
if (Wire.available()) {
x |= Wire.receive() >> 4;
}
if (Wire.available()) {
y = Wire.receive() << 4;
} else {
y = 0xabc;
}
if (Wire.available()) {
y |= Wire.receive() >> 4;
}
if (Wire.available()) {
z = Wire.receive() << 4;
} else {
z = 0x123;
}
if (Wire.available()) {
z |= Wire.receive() >> 4;
}
Wire.endTransmission();
Serial.print(x, HEX);
Serial.print(' ');
Serial.print(y, HEX);
Serial.print(' ');
Serial.println(z, HEX);
}
- Login to post comments
