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

เซนเซอร์วัดระยะ

เซนเซอร์วัดระยะจะวัดระยะห่างเป็นเมตร ถึงวัตถุชิ้นแรกที่อยู่ด้านหน้า ได้ไกลสุด 0.8 เมตร หุ่นยนต์เริ่มต้นมีเซนเซอร์นี้สามตัว ได้แก่ leftDist, frontDist และ rightDist ซึ่งหันไปทางซ้าย ด้านหน้า และขวา

เซนเซอร์วัดระยะสามตัวมองจากด้านบน หันไปทางซ้าย ด้านหน้า และขวา

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
frontDist = robot.getDevice("frontDist") # Get the sensor by name
frontDist.enable(timeStep) # Enable it
while robot.step(timeStep) != -1:
print("Front:", round(frontDist.getValue(), 3), "m")

ช่อง (tile) หนึ่งช่องกว้าง 12 ซม. ดังนั้นเมื่อหุ่นยนต์อยู่กลางช่อง ผนังที่อยู่ด้านข้างจะห่างประมาณ 5 ซม. โปรแกรมนี้ตรวจสอบเซนเซอร์ทั้งสามตัว และพิมพ์ว่าตัวใดเห็นผนัง:

from controller import Robot
robot = Robot()
timeStep = int(robot.getBasicTimeStep())
# Keep the sensors in a dictionary, to use them by name
sensors = {}
for name in ["leftDist", "frontDist", "rightDist"]:
sensors[name] = robot.getDevice(name)
sensors[name].enable(timeStep)
WALL = 0.07 # Closer than 7 cm counts as a wall next to the robot
while robot.step(timeStep) != -1:
walls = [name for name, sensor in sensors.items() if sensor.getValue() < WALL]
print("Walls:", walls)

เซนเซอร์วัดระยะจากตำแหน่งที่ติดตั้งอยู่บนหุ่นยนต์ ไม่ใช่จากจุดกึ่งกลางของหุ่นยนต์ ลองพิมพ์ค่าออกมาเมื่ออยู่ข้างผนัง เพื่อเลือกค่าเกณฑ์ (threshold) ของคุณเอง