iPhone accelerometer source code
By Erling Ellingsen on August 28, 2007Here's some code to initialize the accelerometer to run at full speed. Pass the desired sample rate (in Hz) to the initialize function. Go wild!
[updated 9/3: fixed typo]
#include <IOKit/IOKitLib.h> #include <CoreFoundation/CoreFoundation.h>
typedef struct {} *IOHIDEventSystemRef;
typedef struct {} *IOHIDEventRef;
float IOHIDEventGetFloatValue(IOHIDEventRef ref, int param);void handleHIDEvent(int a, int b, int c, IOHIDEventRef ptr) {
int type = IOHIDEventGetType(ptr);
if (type == 12) {
float x,y,z;
x = IOHIDEventGetFloatValue(ptr, 0xc0000);
y = IOHIDEventGetFloatValue(ptr, 0xc0001);
z = IOHIDEventGetFloatValue(ptr, 0xc0002);
// do whatever you need to do with the gravity
ballSetAccel(x, y);
}}
#define expect(x) if(!x) { printf("failed: %s\n", #x); return; }void initialize(int hz) {
mach_port_t master;
expect(0 == IOMasterPort(MACH_PORT_NULL, &master));int page = 0xff00, usage = 3;
CFNumberRef nums[2];
CFStringRef keys[2];
keys[0] = CFStringCreateWithCString(0, "PrimaryUsagePage", 0);
keys[1] = CFStringCreateWithCString(0, "PrimaryUsage", 0);
nums[0] = CFNumberCreate(0, kCFNumberSInt32Type, &page);
nums[1] = CFNumberCreate(0, kCFNumberSInt32Type, &usage);
CFDictionaryRef dict = CFDictionaryCreate(0, (const void**)keys, (const void**)nums, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
expect(dict);IOHIDEventSystemRef sys = (IOHIDEventSystemRef) IOHIDEventSystemCreate(0);
expect(sys);CFArrayRef srvs = (CFArrayRef)IOHIDEventSystemCopyMatchingServices(sys, dict, 0, 0, 0);
expect(CFArrayGetCount(srvs)==1);io_registry_entry_t serv = (io_registry_entry_t)CFArrayGetValueAtIndex(srvs, 0);
expect(serv);CFStringRef cs = CFStringCreateWithCString(0, "ReportInterval", 0);
int rv = 1000000/hz;
CFNumberRef cn = CFNumberCreate(0, kCFNumberSInt32Type, &rv);int res = IOHIDServiceSetProperty(serv, cs, cn);
expect(res == 1);res = IOHIDEventSystemOpen(sys, handleHIDEvent, 0, 0);
expect(res != 0);
}
TrackBack
TrackBack URL for this entry:
http://blog.medallia.com/cgi-bin/mt/mt-tb.cgi/29
Comments
OMG! this is greatnews! imagine apps that would...
1.Flip through pictures using hand movements
2.PONG!
3.Racing games iphone as the steering wheel ?
4.Motion activated ALarm for iphone theft ??
Why don't you post the apps you have? I want a Steve Jobs bobblehead. :-D
Do have any demo apps?
Hey could you post one of the apps from your demos.
This is awesome. Thanks for sharing the source code! Can't wait to see some real applications which utilize it.
Could you imagine iAlertU for the iPhone? lol
Seriously, if you'd release that maze/ball game, that would be awesome.
Question: Where do these IO functions come from?
IOHIDEventSystemCopyMatchingServices
IOHIDServiceSetProperty
IOHIDEventSystemOpen
Are they iPhone specific? Or hidden away somewhere in IOKit?
I did a search of IOKit at Aple's site and there is no sign of them.
Ken: I don't know. They are either iPhone specific or new in Leopard. I noticed that they also replaced the irregular IOConnectMethodScalarIScalarO family of calls with a cleaner IOConnectCallMethod. I'd be surprised if this doesn't show up in Leopard, thought it's weird that no references to the functions can be found anywhere. Maybe the NDAs for the early-access programs are really strict, what do I know?
Where do you type in these cods?
Erling: You're using them in your init function so you're linking against something. A lib from the iPhone dev kit at iphone.fiveforty.net?
Ken: The armgcc will pick up the names directly from /Sys/Lib/FW/IOKit.fw/IOKit; just add '-framework IOKit' to the command line.
benny: if you're still reading this, you need to be a programmer to do much with those "cods".
It's called source code and it 's used by programmers to help make new programs using their computers. So you don't type the codes into the iPhone.
Very cool I see some crazy apps coming...
work on Ibeer
Wow, this is rather cool :) . I'd love to see this turned into a performance meter like the g-tech (http://www.gtechpro.com/)
The iPhone might struggle with the processing and resolution of the data from the accelerometer, but it might be an interesting exercise to see if it could be used as such!
Sweet. Do you think you could release source for a full application that would use this? Even the ball demo would help a lot - I've been trying to make some games of my own, but I can't get the whole timed-run-loop thing working.
Just wondering, is this any use to developers making web apps, or do programs that use this stuff have to run natively on the iphone? An iPhonesaber would be the ONLY reason I can see jailbreaking my phone. That way I can pick up all the hot girls at the next gaming con.
Hello again
As an exercise, I'm attempting to turn your example code into an IPhoneAccelerometer Cocoa class and have a few more questions.
IOHIDEventSystemOpen exists no where on the internet except this blog. Could you post the prototype?
Was your handleHIDEvent function conjured out of thin air? Or is there some prototype in a header file somewhere indicating the callpack arguments and return type?
The type "12" in your handleHIDEvent callback was derived through hacking I guess?
The offsets 0xc0000, 0xc0001, 0xc0002 used in IOHIDEventGetFloatValue were also hacks?
Also...
Your prototype
void handleHIDEvent(int a, int b, int c, IOHIDEventRef ptr)
defines arguments a, b, c but never uses them is that because you don't know what they do? Or are those variables used your demo apps?
Hi,
Nice demos, I was hoping for something like this to come out, especially the bouncing coins/balls one.
I've managed to compile the code and I'm getting some weird results. For one the line
res = IOHIDEventSystemOpen(sys, handleHIDEvent, 0, 0);
expect(res == 0);
comes out with an error. I've modified your catching macro to print out what the result was and I get '1' as the returned value..
Any ideas?
I then get a couple of calls to my handler, but I'm guessing I should get a call on each sample? so if I set sample rate to 100 hz it would be 100 calls/sec..
What rates (hz) have you tried with success?
Cheers,
Chris
Excellent work!
How did you know about the IOHIDEvent* functions in the first place? Where do they come from?
Kudos,
//MrSolo
I can't believe you all are buying this. Why hasn't he posted the apps and build instructions? Because it's FAKE!
Pocket Wii? Sounds dirty.
The datasheet for the accel chip reveals it supports tap detection in three directions. Wonder if this can be accessed somehow as it is quite handy for interfacing tricks.
The maximum sample rate is 400Hz.
aethr
Hey, I'm trying to compile this code but I keep getting a compiler error which is telling me that it has an undefined symbol "_ballSetAccel." Any suggestions of what I'm missing or doing wrong here?
I've already got it linking to the IOKit and I have no problems compiling the IO related stuff, but its the ballsetaccel thats giving me fits.
Ken: yes, it's all guesswork.
Chris, you're right -- it should nonzero. I mistranscribed my code. I have updated the code above.
sword: replace that function with whatever you want.
Ahhh, silly me. Thank you so much, Erling! I'm going to be using this code as part of a program I'm making entitled iSabre that will make your phone sound like a lightsabre as you swing it around! The perfect tool for the perfect awkward battle!
sword: To get the audio snappy enough, you'll want to have a look at Brian Whitman's audio stuff: http://variogr.am/latest/?p=25
how do u compile the code
Where do you put the sorce code?
looks very nice, and your app makes excellent use of it :)
however, i can't see how this works.
I dont have the IOHIDEventSystemRef and IOHIDEventRef types in any of the headers, but need them because otherwise the signatures of IOHIDEventGetType etc will contain anonyous params. if i typedef the Refs as void*, the linker will complain about missing functions IOHIDEventGetType etc, even though i did -framework IOKit and -F${HEAVENLY}/System/Library/Frameworks?
any idea? cheers m8 :)
/looploop
hehe nevermind that... turns out it works fine if you do the declaration inside an extern "C" {} block... (only needed if using c++ linkage)
:)
When compile i receive this error and can not solve it:
/usr/local/bin/arm-apple-darwin-ld: Undefined symbols:
_main
collect2: ld returned 1 exit status
make: *** [ac] Error 1
OMG this is Amazing i cant wait to see all the apps people come up with! THIS IS NEW THE POCKET WII