Lewati ke konten
Bahasa Indonesia

Sensor lokasi

Sensor lokasi, atau GPS, memberikan posisi robot dalam meter. Pada robot pemula, namanya gps. Kamu membutuhkannya untuk melaporkan penanda dinding, dan sensor ini sangat membantu untuk menjelajah secara sistematis.

getValues() mengembalikan [x, y, z]. X dan Z adalah sumbu horizontal, dan Y vertikal, jadi gunakan X dan Z untuk posisi di labirin:

Sumbu X dan Z pada bidang horizontal, dengan Y vertikal

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
gps = robot.getDevice("gps")
gps.enable(timeStep)
while robot.step(timeStep) != -1:
x, y, z = gps.getValues() # In meters. X and Z are horizontal, Y is vertical.
print("x:", round(x, 3), "z:", round(z, 3))

GPS memiliki derau (noise) beberapa milimeter, jadi nilainya sedikit berubah bahkan saat robot diam. Jangan pernah membandingkan apakah dua posisi sama persis.

Program ini membuat robot maju sampai berjarak setengah ubin dari tempat awalnya:

from controller import Robot
import math
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
gps = robot.getDevice("gps")
gps.enable(timeStep)
leftWheel = robot.getDevice("left wheel motor")
rightWheel = robot.getDevice("right wheel motor")
leftWheel.setPosition(float("inf"))
rightWheel.setPosition(float("inf"))
robot.step(timeStep) # Step once, so that the GPS has a value
startX, _, startZ = gps.getValues()
leftWheel.setVelocity(3.0)
rightWheel.setVelocity(3.0)
while robot.step(timeStep) != -1:
x, _, z = gps.getValues()
distance = math.sqrt((x - startX) ** 2 + (z - startZ) ** 2)
print("Distance from the start:", round(distance, 3), "m")
if distance > 0.06: # Half a tile
leftWheel.setVelocity(0)
rightWheel.setVelocity(0)
break