博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【iOS与EV3混合机器人编程系列之7】通过蓝牙控制EV3
阅读量:4124 次
发布时间:2019-05-25

本文共 2334 字,大约阅读时间需要 7 分钟。

1 前言

在这个系列之前的博客中,我研究觉得在iOS未越狱的情况下,无法使用蓝牙来控制EV3,编写类似Commander的程序。但,最近和网友的研究发现,通过External Accessory 来实现蓝牙的传输比想象的简单。MFI协议的问题比想象的容易很多,关键在于我们可以获取EV3的MFI协议字符串。接下来让我们看看是怎么实现的。
开源代码:

2 具体代码实现

首先Apple官方有个关于External Accessory的demo 叫EAdemo,大家可以下下来,然后在plist文件中改一下协议字符串,如下:
然后运行一下,我们就可以直接连上EV3了。
有了这个基础,我们研究一下实现原理。
Step 1:添加ExternalAccessory.Framework 
这一步显而易见。
Step 2:连接到EV3
- (void)connectEV3{    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accessoryDidConnect:) name:EAAccessoryDidConnectNotification object:nil];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accessoryDidDisconnect:) name:EAAccessoryDidDisconnectNotification object:nil];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sessionDataReceived:) name:EADSessionDataReceivedNotification object:nil];    [[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];    self.sessionController = [EADSessionController sharedController];    accessoryList = [[NSMutableArray alloc] initWithArray:[[EAAccessoryManager sharedAccessoryManager] connectedAccessories]];    NSLog(@"accessory list:%@",accessoryList);    if(accessoryList != nil){        [self.sessionController setupControllerForAccessory:[accessoryList firstObject]                                         withProtocolString:@"COM.LEGO.MINDSTORMS.EV3"];       isConnected = [self.sessionController openSession];            }}
- (void)accessoryDidConnect:(NSNotification *)notification {    NSLog(@"EV3 did connect!");    EAAccessory *connectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];    [self.sessionController setupControllerForAccessory:connectedAccessory                                   withProtocolString:@"COM.LEGO.MINDSTORMS.EV3"];    isConnected = [self.sessionController openSession];        }
在这里我也直接使用了EADemo上的代码来分析。
由于官方例子的EADSessionController把数据传输这部分内容做得很好,我们直接拿来用就好了。
基本过程就是创建实例,建立controller,然后openSession。
Step 3:控制EV3
直接使用之前已经编写好的EV3DirectCommander来实现
简单的例子如下:
- (IBAction)go:(id)sender {    if (isConnected) {        NSData *data = [EV3DirectCommander turnMotorAtPort:EV3OutputPortB power:50];        [[EADSessionController sharedController] writeData:data];        isGo = YES;    }}

3 为什么用蓝牙?

显然之前用Wifi得买额外设备,还得连wifi太麻烦,直接用蓝牙省事很多,可以做得更好的效果!嘿嘿,大家可以自己搞个Commander了!更强大的Commander!
你可能感兴趣的文章
最短路径算法
查看>>
python函数式编程—高阶函数练习题
查看>>
GPON技术学习(五)----------ONU七种状态
查看>>
EPON技术学习
查看>>
EPON和GPON的比较
查看>>
PPPoE报文格式及交互详解
查看>>
python面向对象编程全解
查看>>
Linux驱动程序简介
查看>>
构造和运行模块
查看>>
Vim的基础入门
查看>>
用户空间和内核空间
查看>>
驱动程序操作的三个内核数据结构(file_operations、file、inode)
查看>>
字符设备驱动程序快速参考
查看>>
Linux并发控制
查看>>
RGB颜色对照表
查看>>
Linux下编译器搜索头文件路径
查看>>
Linux驱动ioctl的使用
查看>>
C语言结构体末端定义空数组
查看>>
gdb调试的基本命令
查看>>
利用socket raw抓包
查看>>