Created
April 22, 2026 10:50
-
-
Save woodif/abb16ffa4feebcb050ed0d12738dffbc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <Wire.h> | |
| #include <SparkFun_VL53L5CX_Library.h> // ต้องติดตั้งไลบรารีนี้ก่อน | |
| // กำหนดขา I2C สำหรับ ESP32 | |
| #define SDA_PIN 21 | |
| #define SCL_PIN 22 | |
| // สร้างออบเจกต์สำหรับเซ็นเซอร์ | |
| SparkFun_VL53L5CX myImager; | |
| VL53L5CX_ResultsData measurementData; // ตัวแปรเก็บค่าที่อ่านได้ | |
| void setup() { | |
| Serial.begin(115200); | |
| delay(1000); | |
| Serial.println("\n--- เริ่มต้นการทำงาน VL53L5CX ---"); | |
| // เริ่มต้น I2C ด้วยขาที่กำหนด | |
| Wire.begin(SDA_PIN, SCL_PIN); | |
| // ตรวจสอบการเชื่อมต่อเซ็นเซอร์ | |
| // หมายเหตุ: VL53L5CX ใช้เวลาเริ่มต้นระบบ (โหลดเฟิร์มแวร์) นานกว่าเซ็นเซอร์ทั่วไปเล็กน้อย | |
| Serial.println("กำลังเชื่อมต่อเซ็นเซอร์ กรุณารอสักครู่..."); | |
| if (myImager.begin() == false) { | |
| Serial.println("❌ ไม่พบเซ็นเซอร์ VL53L5CX! กรุณาตรวจสอบสาย I2C (SDA=21, SCL=22)"); | |
| while (1); // หยุดการทำงานถ้าไม่พบเซ็นเซอร์ | |
| } | |
| Serial.println("✅ เชื่อมต่อเซ็นเซอร์สำเร็จ!"); | |
| // ตั้งค่าความละเอียดเป็น 4x4 โซน (สามารถตั้งเป็น 8x8 ได้ แต่ Serial Monitor จะดูยาก) | |
| myImager.setResolution(4 * 4); | |
| // เริ่มการวัดระยะ | |
| myImager.startRanging(); | |
| Serial.println("--- พร้อมแสดงผลค่าระยะทาง (มิลลิเมตร) ---"); | |
| } | |
| void loop() { | |
| // ตรวจสอบว่าเซ็นเซอร์มีข้อมูลชุดใหม่พร้อมให้อ่านหรือยัง | |
| if (myImager.isDataReady() == true) { | |
| // ดึงข้อมูลมาเก็บไว้ใน measurementData | |
| myImager.getRangingData(&measurementData); | |
| // พิมพ์ค่าระยะทาง (มิลลิเมตร) ออกมาเป็นรูปแบบตาราง 4x4 | |
| for (int y = 0; y <= 3; y++) { | |
| for (int x = 0; x <= 3; x++) { | |
| int zone = y * 4 + x; // คำนวณหาหมายเลขโซน | |
| Serial.print(measurementData.distance_mm[zone]); | |
| Serial.print("\t"); // เว้นช่องไฟด้วย Tab | |
| } | |
| Serial.println(); // ขึ้นบรรทัดใหม่เมื่อครบ 1 แถว (4 ค่า) | |
| } | |
| Serial.println("--------------------------------"); | |
| } | |
| // หน่วงเวลาเล็กน้อยเพื่อไม่ให้ข้อมูลไหลเร็วเกินไป | |
| delay(100); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment