ข้ามไปยังเนื้อหา
ไทย

เซนเซอร์ตำแหน่ง

เซนเซอร์ตำแหน่ง หรือ GPS ให้ตำแหน่งของหุ่นยนต์เป็นเมตร บนหุ่นยนต์เริ่มต้นมีชื่อว่า gps คุณต้องใช้เซนเซอร์นี้เพื่อรายงานสัญลักษณ์บนผนัง และยังช่วยได้มากในการสำรวจอย่างเป็นระบบ

getValues() คืนค่า [x, y, z] โดย X และ Z เป็นแนวนอน ส่วน Y เป็นแนวตั้ง ดังนั้นให้ใช้ X และ Z เป็นตำแหน่งในเขาวงกต:

แกน X และ Z ของระนาบแนวนอน โดยมี Y เป็นแนวตั้ง

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 มีสัญญาณรบกวน (noise) ไม่กี่มิลลิเมตร ค่าจึงเปลี่ยนเล็กน้อยแม้หุ่นยนต์จะหยุดนิ่ง อย่าเปรียบเทียบตำแหน่งว่าเท่ากันพอดี

โปรแกรมนี้ขับหุ่นยนต์ไปข้างหน้าจนกว่าจะห่างจากจุดเริ่มต้นครึ่งช่อง:

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