Use mBot with iOS (Swift)

For iOS developers, we have a Swift framework to control mBots (through Bluetooth) with iOS devices.

Link to API Documentation

Download and Import

You may download the framework at the following link:

http://appinventor.makeblock.com/Makeblock.framework.zip

After downloading, unzip and drag the Makeblock framework file to your project folder, and that’s it.

In the files that use this framework, add the following import instruction at the beginning:

import Makeblock

The source code of the framework is available. There is a “DemoProject” project in the workspace. You may want to look at it.

Connect to the mBot through Bluetooth

First, you need to let your phone discover Bluetooth devices from the environment. Run the following code will do the work.

let connection = BluetoothConnection()

connection.onAvailableDevicesChanged = { devices in
if let bluetoothDevices = devices as? [BluetoothDevice] {

// do something with bluetooth devices

}
}

Every Bluetooth Device instance has .name and .distance (the distance from the iPhone/iPad to that device). You can then display them in a UITableView or similar places for users to choose which to connect to.

Before connecting to a device, it’s usually useful to setup a callback that will execute when a Bluetooth device is connected. Things to be done here include jumping to a new UIViewController or start sending commands to the robot:

connection.onConnect = {

            // do something after you connected to the robot you choose

}

After that, you may want to connect to a Bluetooth device:

connection.connect(device)

After the robot is connected, you need to get the handle of a robot using the connection you made (this can be done before the actual connection happens):

let mbot = MBot(connection: connection)

Control the robot with Makeblock API

MBot class provides a series of APIs to play with the robot. Here are some examples:

(More available at the API Documentation)

mbot.moveForward(255) tell the robot to move forward in a certain speed (0-255)
mbot.moveBackward(255) tell the robot to move backward in a certain speed
mbot.turnLeft(255) tell the robot to turn left in a certain speed
mbot.turnRight(255) tell the robot to turn right in a certain speed
mbot.stopMoving(255) tell the robot to stop moving
mbot.setRGBLED(.left, red: 255, green: 0, blue: 0) set the color of mBot’s on-board LEDs. the first parameter takes .left, .right and .all to decide which LED should display the color you want
mbot.setBuzzer(.C4, duration:.half)  play a musical note using the on-board buzzer of mBots.
mbot.getUltrasonicSensorValue() { value in

// do something with the value

}

 read values from the ultrasonic sensor connected. You may specify a port which the sensor is connected to or use .Port3 as the default. Since reading a sensor value is a asynchronous action, you need to provide a callback of what you will do to the sensor value you fetched.