โค๊ดตู้ปากกาพอรันแล้วเซอโวค้างยังไม่ำด้กดปุ่มมีวิธีแก้ไหมครับ

#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <Servo.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // ใช้ที่อยู่ I2C เป็น 0x27
Servo myservo;
int coin = 2;  // ใช้ pin 2 สำหรับตรวจจับเหรียญ (ต้องรองรับ Interrupt)
int count = 0;
int credit = 0;
bool isCounter = false;
void setup() {
    pinMode(coin, INPUT_PULLUP);  // ตั้งค่า pin coin เป็น INPUT_PULLUP เพื่อใช้การตรวจจับการเปลี่ยนแปลงจาก LOW เป็น HIGH
    myservo.attach(4);  // กำหนด pin เซอร์โว
    myservo.write(0);  // ตั้งค่าเซอร์โวให้หยุดที่ตำแหน่งเริ่มต้น
    delay(500);  // ให้เวลาสำหรับการเริ่มต้นของเซอร์โว
    
    Wire.begin();  // เริ่มต้นการสื่อสาร I2C
    
    lcd.begin(16, 2);  // กำหนดขนาดของ LCD เป็น 16x2
    lcd.backlight();
    lcd.clear();
    delay(500);  // ให้เวลาสำหรับการเริ่มต้น LCD
    
    lcd.setCursor(0, 0);  // ตั้งตำแหน่งเริ่มต้นของข้อความ
    lcd.print("Insert Coin!");  // ข้อความแรก
    lcd.setCursor(0, 1);  // ตั้งตำแหน่งที่สอง
    lcd.print("5 Baht");  // ข้อความที่สอง
    attachInterrupt(digitalPinToInterrupt(coin), doCounter, FALLING);  // ตั้งค่า Interrupt สำหรับนับเหรียญ
}
void loop() {
    if (isCounter) {
        isCounter = false;
        credit += 5;  // เพิ่มเครดิตทุกครั้งที่หยอดเหรียญ
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Credit: ");
        lcd.print(credit);
        lcd.print(" Baht");
        delay(1000);
    }
    
    if (credit >= 5) {  // เงื่อนไขนี้จะทำให้เซอร์โวทำงานเฉพาะเมื่อเครดิต >= 5
        dispenseItem();
    }
}
void doCounter() {
    isCounter = true;
    count++;
}
void dispenseItem() {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Delivering...");
    
    myservo.write(0);  // หมุนเซอร์โวไปที่ตำแหน่ง 180 (เปิด)
    delay(1000);  // รอให้เซอร์โวหมุน
    myservo.write(0);  // หมุนเซอร์โวกลับที่ตำแหน่ง 0 (ปิด)
    delay(1000);  // ให้เวลาเซอร์โวในการหยุด
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Item delivered!");
    lcd.setCursor(7, 1);
    lcd.print("Thank You");
    delay(2000);
    
    lcd.clear();
    lcd.setCursor(2, 0);
    lcd.print("Insert Coin!");
    lcd.setCursor(5, 1);
    lcd.print("5 Baht");
    
    credit = 0;  // รีเซ็ตเครดิต
    count = 0;   // รีเซ็ตจำนวนเหรียญที่หยอด
}
แสดงความคิดเห็น
โปรดศึกษาและยอมรับนโยบายข้อมูลส่วนบุคคลก่อนเริ่มใช้งาน อ่านเพิ่มเติมได้ที่นี่