Created
January 2, 2017 22:07
-
-
Save attilavago/0f6b462db69852df2412faa56049f75a to your computer and use it in GitHub Desktop.
This test demonstrates measuring distance in cm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// EV3 Ultrasonic Sensor Sample | |
/// The robot advances forward until the ultrasonic sensor detects an object within 50 cm. | |
/// It then stops, plays a tone, and displays a message for two seconds. | |
import RobotKit | |
// Constants to adjust. | |
let ultrasonicSensorPort = EV3InputPort.one | |
let motorsPorts: EV3OutputPorts = [.A] | |
// Initializes a new EV3Robot instance through which all device communication happens. | |
let robot = try EV3Robot() | |
// Provides access to the ultrasonic sensor at the given port. | |
guard let sensor = robot.ultrasonicSensor(atPort: ultrasonicSensorPort) else { | |
fatalError("Can't find the ultrasonic sensor!") | |
} | |
// Provides access to the motors at the given ports. | |
let motors = robot.motors(atPorts: motorsPorts) | |
// Drives the motors forward simultaneously at 40% speed. | |
motors.setSpeed(40) | |
// Keeps on driving forward until we're <= 50 cm from an obstacle. | |
sensor.waitUntilDistanceIs(.lessThanOrEqualTo, threshold: 0.5) | |
// Stops the motors and applies the brakes. | |
motors.stop(applyBrakes: true) | |
// Plays a 1000 Hz tone for 0.5 seconds. | |
robot.sound.playTone(frequency: 1000, duration: 500) | |
// Clears the window and displays a message for 2 seconds. | |
robot.window.clear() | |
robot.window.drawText("Mission accomplished!", fontSize: .small, at: Point(x: 2, y: 60), color: .black) | |
wait(seconds: 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment