Phát hiện vật cản với Arduino và SRF05
Trong bài học này, chúng ta sẽ tìm hiểu cách sử dụng Mô-đun Cảm biến Siêu âm, Động cơ Servo với bo mạch Arduino để tạo ra một hệ thống phát hiện vật cản.
Khi mô-đun cảm biến siêu âm hoạt động, nó sẽ phát ra một âm báo động và nhấp nháy đèn LED đỏ nếu phát hiện chướng ngại vật trong phạm vi cảm biến của nó. Nếu không phát hiện chướng ngại vật, cho thấy trạng thái an toàn, đèn LED xanh sẽ sáng.
Kết Nối Chung:
LED với arduino:
- Kết nối cực âm của LED chân gnd arduino, và cực dương của LED kết nối với chân 3, 4 của Arduino.
Động Cơ Servo:
- GND Kết nối với chân gnd arduino
- vcc Kết nối với chân 5v arduino
- Chân tín hiệu Kết nối với chân 12 của Arduino.
Loa Kêu Thụ Động (Passive Buzzer)
- +: Kết nối với chân 2 của Arduino.
- -: Kết nối với bus nguồn âm trên bảng mạch.
Mô-đun Cảm Biến Siêu Âm
- Trig: Kết nối với chân 11 của Arduino.
- Echo: Kết nối với chân 10 của Arduino.
- GND: Kết nối với bus nguồn âm trên bảng mạch.
- VCC: Kết nối với bus nguồn đỏ trên bảng mạch.
Viết Mã:
#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Servo and ultrasonic sensor settings
Servo radarServo;
const int trigPin = 11;
const int echoPin = 10;
const int servoPin = 12;
// LED and buzzer (active buzzer controlled via digitalWrite)
const int redLed = 3;
const int greenLed = 4;
const int buzzer = 2;
// Initialize the LCD (16x2). Check the I2C address (commonly 0x27 or 0x3F)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Settings
const int alertDistance = 20; // Alarm triggers if distance is less than 20cm
const unsigned long updateInterval = 20; // Servo update interval (ms)
// Variables for smooth scanning
int currentAngle = 0;
int increment = 1; // Increase or decrease angle by 1 degree each update
unsigned long lastServoUpdate = 0;
// Variable to count consecutive detections under threshold
int triggerCount = 0;
// Enum to record state (for updating LCD only when state changes)
enum RadarState { EMPTY, WARNING };
RadarState lastState = EMPTY;
void setup() {
// Initialize servo
radarServo.attach(servoPin);
// Initialize ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize LED and buzzer pins
pinMode(redLed, OUTPUT);
pinMode(greenLed, OUTPUT);
pinMode(buzzer, OUTPUT);
// Initialize LCD
lcd.init();
lcd.backlight();
lcd.clear();
// Set initial status: LCD shows "Area is Empty", green LED on
lcdSetEmpty();
setNormalState();
}
void loop() {
unsigned long currentMillis = millis();
// If not in alarm mode, update servo position smoothly
if (currentMillis - lastServoUpdate >= updateInterval) {
lastServoUpdate = currentMillis;
// Update servo position
radarServo.write(currentAngle);
// Every 5 degrees, perform ultrasonic distance measurement
if (currentAngle % 5 == 0) {
float distance = getDistance();
if (distance < alertDistance) {
triggerCount++; // Count consecutive detections under threshold
} else {
triggerCount = 0; // Reset counter if measurement is safe
}
// Trigger alarm only if detected three times consecutively
if (triggerCount >= 5) {
if (lastState != WARNING) {
lastState = WARNING;
lcdSetWarning();
}
alertMode();
triggerCount = 0; // Reset counter after alarm mode
}
else {
if (lastState != EMPTY) {
lastState = EMPTY;
lcdSetEmpty();
setNormalState();
}
}
}
// Update angle for smooth scanning
currentAngle += increment;
if (currentAngle >= 180) {
currentAngle = 180;
increment = -1;
} else if (currentAngle <= 0) {
currentAngle = 0;
increment = 1;
}
}
}
// Measure distance using the ultrasonic sensor (returns distance in cm)
float getDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH, 30000); // Wait for a maximum of 30ms
float distance = duration * 0.034 / 2; // Calculate distance (cm)
return distance;
}
// Alarm mode: if an object is detected, halt servo and continuously alarm
void alertMode() {
// Turn off green LED while in alarm mode
digitalWrite(greenLed, LOW);
// Keep alarming until the object is removed
while (getDistance() < alertDistance) {
// Flash red LED and activate the active buzzer (producing continuous beeps)
digitalWrite(redLed, HIGH);
digitalWrite(buzzer, HIGH);
delay(100);
digitalWrite(redLed, LOW);
digitalWrite(buzzer, LOW);
delay(100);
}
// When safe, exit alarm mode and update status
lcdSetEmpty();
setNormalState();
lastState = EMPTY;
}
// Set normal status: green LED on, red LED and buzzer off
void setNormalState() {
digitalWrite(greenLed, HIGH);
digitalWrite(redLed, LOW);
digitalWrite(buzzer, LOW);
}
// LCD display "Area is Empty" centered on the first line; clear the second line
void lcdSetEmpty() {
lcd.clear();
// "Area is Empty" has 14 characters; center calculates as (16-14)/2 = 1
lcd.setCursor(1, 0);
lcd.print("Area is Empty");
lcd.setCursor(0, 1);
lcd.print(" ");
}
// LCD display warning message: first line "WARNING!!", second line "Foreign Body" centered
void lcdSetWarning() {
lcd.clear();
// "WARNING!!" has 9 characters; center calculates as (16-9)/2 ≈ 4
lcd.setCursor(4, 0);
lcd.print("WARNING!!");
// "Foreign Body" is printed starting at column 2 (as requested)
lcd.setCursor(2, 1);
lcd.print("Foreign Body");
}