The Center of learning aids to develop Thai education to international

50th Anniversary

การเขียนโปรแกรมด้วย Python (Sensor Control)

การเขียนโปรแกรมด้วย Python กับ LEGO Education

 

ในบทก่อนหน้านี้ คุณได้ทดลองใช้ตัวแปร (Variables) และการสุ่มตัวเลข (Random Numbers) เพื่อควบคุมมอเตอร์ และไฟ (Light) แล้ว ในบทนี้คุณจะได้เรียนรู้การใช้ค่าที่อ่านได้จากเซนเซอร์ เพื่อควบคุมการทำงานของมอเตอร์

เริ่มต้นโดยเชื่อมต่อมอเตอร์เข้ากับพอร์ต A และ Force Sensor เข้ากับพอร์ต B จากนั้นทดลองรันโปรแกรมด้านล่าง

 

การเชื่อมต่อมอเตอร์เข้ากับพอร์ต A และ Force Sensor เข้ากับพอร์ต B

 

 

 

import force_sensor
import motor
from hub import port

# Store the force of the Force Sensor in a variable.
force = force_sensor.force(port.B)

# Print the variable to the Console.
print(force)

# Run the motor and use the variable to set the velocity.
motor.run(port.A, force)

 

 

 

ลองกด Force Sensor ขณะที่โปรแกรมกำลังทำงาน คุณอาจสังเกตเห็นว่าไม่มีการเปลี่ยนแปลงเกิดขึ้นมากนัก โชคดีที่โปรแกรมตัวอย่างนี้ใช้ฟังก์ชัน print() ซึ่งเป็นฟังก์ชันที่มีอยู่แล้วใน Python เพื่อแสดงค่าของตัวแปร force บนหน้าต่าง Console ทำให้คุณสามารถตรวจสอบ และระบุสาเหตุของปัญหาได้ง่ายขึ้น

 

 

 

Writer : Pacharee Wongcherngyoot
Matawee Waesalaemae
CODE : 80D45678

฿ 34,500