锐单电子商城 , 一站式电子元器件采购平台!
  • 电话:400-990-0325

每天都有心得之IOS加速度传感器的使用

时间:2022-11-05 15:00:00 14加速度传感器3110加速度传感器

下面介绍一下IOS基本使用加速传感器,给出程序代码供参考!

简介

基于加速度传感器x、y用z三个方向检测设备位置的变化。

设备相对于地面的位置可以通过加速度传感器知道。

以下实例代码需要在真实设备上运行,不能在模拟器上工作。

实例步骤

1.创建一个简单的视图应用程序

2、在ViewController.xib中添加三个标签,并创建一个ibOutlets分别为:xlable、ylabel和zlabel

3.更新如下所示ViewController.h

#import   @interface ViewController : UIViewController {     IBOutlet UILabel *xlabel;     IBOutlet UILabel *ylabel;     IBOutlet UILabel *zlabel;  } @end

4.更新如下所示ViewController.m

#import "ViewController.h"  @interface ViewController ()  @end  @implementation ViewController  - (void)viewDidLoad {     [super viewDidLoad];     [[UIAccelerometer sharedAccelerometer]setDelegate:self];     //Do any additional setup after loading the view,typically from a nib }  - (void)didReceiveMemoryWarning {     [super didReceiveMemoryWarning];     // Dispose of any resources that can be recreated. } - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:   (UIAcceleration *)acceleration{     [xlabel setText:[NSString stringWithFormat:@"%f",acceleration.x]];     [ylabel setText:[NSString stringWithFormat:@"%f",acceleration.y]];     [zlabel setText:[NSString stringWithFormat:@"%f",acceleration.z]]; }  @end

输出

当我们在iPhone该应用程序在设备中运行,输出结果如下。

如图所示,加速度传感器已成功实现,可根据x、y用z三个方向检测设备位置的变化。

锐单商城拥有海量元器件数据手册IC替代型号,打造电子元器件IC百科大全!

相关文章