Search This Blog

Loading...

Sep 9, 2011

iPhone Accelerometer Example.

This example shows how use accelerometer in iPhone.


You can download source code from here Download.

1. Code for .h file.

#import

@interface AccelerometerExampleViewController : UIViewController {
  
    UISlider *slider;
}

@end


2. Code for .m file.

#import "AccelerometerExampleViewController.h"

@implementation AccelerometerExampleViewController


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
  
    UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
    accel.updateInterval = 0.05f;
    accel.delegate = self;
  
    slider = [[UISlider alloc] initWithFrame:CGRectMake(10, 200, 300, 20)];
    slider.minimumValue = -1;
    slider.maximumValue = 1;
    [self.view addSubview:slider];
}


- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    NSLog(@"(%.02f, %.02f, %.02f)", acceleration.x, acceleration.y, acceleration.z);
    slider.value = acceleration.x;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
    [slider release];
    [super dealloc];
}

@end