Skip to content

Instantly share code, notes, and snippets.

@attilavago
Last active January 2, 2017 21:57
Show Gist options
  • Save attilavago/5970bc18267c30f193ed352b837cf070 to your computer and use it in GitHub Desktop.
Save attilavago/5970bc18267c30f193ed352b837cf070 to your computer and use it in GitHub Desktop.
This test demonstrates using the IR sensor
/// EV3 Infrared Sample
/// The robot advances forward until the infrared sensor detects a nearby obstacle.
/// It then stops, plays a tone, and displays a message for two seconds.
/// Note that this can be done more accurately using the ultrasonic sensor.
import RobotKit
// Constants to adjust.
let infraredSensorPort = 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 infrared sensor at the given port.
guard let sensor = robot.infraredSensor(atPort: infraredSensorPort) else {
fatalError("Can't find the infrared 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 relatively close by an obstacle.
sensor.waitUntilProximityIs(.lessThanOrEqualTo, threshold: 0.15)
// 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