標籤:ios ev3 機器人 藍芽
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!
【iOS與EV3混合機器人編程系列之7】通過藍芽控制EV3