// Define pins
const int buttonPin = 3; // Nút bấm kết nối với pin 3
const int pirPin = 5; // Cảm biến PIR kết nối với pin 5
const int relayPin = 6; // Relay điều khiển thiết bị (bơm nước) kết nối với pin 6
const int potPin = A0; // Potentiometer kết nối với chân A0
const int ledPin = 7; // LED kết nối với pin 7
const int buzzerPin = 12; // Buzzer kết nối với pin 12
const int stepperPins[] = {8, 9, 10, 11}; // Chân điều khiển động cơ bước
// Variables
int ledState = LOW; // Trạng thái LED (tắt)
int pirState = LOW; // Trạng thái cảm biến PIR
int lastPirState = LOW; // Trạng thái cảm biến PIR trước đó
int buttonState = LOW; // Trạng thái nút bấm
int lastButtonState = LOW; // Trạng thái nút bấm trước đó
int potValue = 0; // Giá trị đọc từ potentiometer
unsigned long lastDebounceTime = 0; // Thời gian lần cuối debounce
unsigned long debounceDelay = 200; // Độ trễ debounce cho nút bấm
void setup() {
// Set pin modes
pinMode(buttonPin, INPUT);
pinMode(pirPin, INPUT);
pinMode(relayPin, OUTPUT);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Set stepper motor pins as output
for (int i = 0; i < 4; i++) {
pinMode(stepperPins[i], OUTPUT);
}
}
void loop() {
// Read button state with debounce
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis(); // Reset debounce timer
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
ledState = !ledState; // Toggle LED state
digitalWrite(ledPin, ledState);
}
}
}
lastButtonState = reading;
// Read PIR sensor state
pirState = digitalRead(pirPin);
// If motion is detected, turn on the LED and buzzer
if (pirState == HIGH && lastPirState == LOW) {
digitalWrite(ledPin, HIGH); // Turn on the LED
digitalWrite(buzzerPin, HIGH); // Turn on the buzzer
digitalWrite(relayPin, HIGH); // Turn on the pump
lastPirState = HIGH;
}
// If no motion is detected, turn off the LED and buzzer
else if (pirState == LOW && lastPirState == HIGH) {
digitalWrite(ledPin, LOW); // Turn off the LED
digitalWrite(buzzerPin, LOW); // Turn off the buzzer
digitalWrite(relayPin, LOW); // Turn off the pump
lastPirState = LOW;
}
// Read potentiometer value (for controlling light brightness or other features)
potValue = analogRead(potPin);
// Control the stepper motor (example: rotate based on potentiometer)
int motorSpeed = map(potValue, 0, 1023, 0, 255);
stepperMotorControl(motorSpeed);
}
// Function to control the stepper motor
void stepperMotorControl(int speed) {
static unsigned long lastStepTime = 0; // Thời gian bước cuối
unsigned long currentTime = millis();
if (speed > 0 && currentTime - lastStepTime >= (1000 / speed)) { // Điều khiển tốc độ
// Rotate the stepper motor (4 steps in a cycle)
for (int i = 0; i < 4; i++) {
digitalWrite(stepperPins[i], HIGH);
delay(10); // Adjust delay for motor speed
digitalWrite(stepperPins[i], LOW);
}
lastStepTime = currentTime;
}
}