JinhaKangLAB / Arudino-Codes

0 stars 0 forks source link

SimpleFinal #4

Open JinhaKangLAB opened 1 year ago

JinhaKangLAB commented 1 year ago

include

// Define pin connections const int presenceSensorPin = A0; const int vacuumPin = 3; const int blowerPin = 2;

// Define variables to control timing unsigned long presenceStartTime = 0; const unsigned long vacuumDuration = 10000; // 30 seconds in milliseconds const int distanceThreshold = 40; // Set distance threshold for human presence in centimeters

void setup() { // Initialize pins pinMode(presenceSensorPin, INPUT); pinMode(vacuumPin, OUTPUT); pinMode(blowerPin, OUTPUT);

// Make sure vacuum and blower are off at startup digitalWrite(vacuumPin, HIGH); digitalWrite(blowerPin, HIGH); }

void loop() { // Read presence sensor value bool presence = isHumanPresent(); bool presenceUnder30=isPresenceUnder30();

if (presence) { // Human presence detected digitalWrite(blowerPin, HIGH); // Turn off the blower

if(presenceUnder30){ digitalWrite(vacuumPin, LOW); // Turn on the vacuum }else{ digitalWrite(vacuumPin, HIGH); // Turn on the vacuum } } else { // No human presence detected digitalWrite(vacuumPin, HIGH); // Turn off the vacuum digitalWrite(blowerPin, LOW); // Turn on the blower }

Serial.println(presence); } // Function to convert the analog sensor value to distance in centimeters int getDistance(int sensorValue) { // The following equation is specific to the GP2Y0A41SK0F sensor float distance = 2076.0 / (sensorValue - 11.0); return (int)distance; }

bool isPresenceUnder30() { bool presence = isHumanPresent();

if(presence) { // Store the start time of presence if (presenceStartTime == 0) { presenceStartTime = millis(); } // Check if the vacuum has been on for 30 seconds if (millis() - presenceStartTime >= vacuumDuration) { return false; }else{ return true; } }else{ // Reset presence start time presenceStartTime = 0; } } // Function to check if a human is present based on the IR sensor reading bool isHumanPresent() { int presenceSensorValue = analogRead(presenceSensorPin); int distance = getDistance(presenceSensorValue);

if (distance <= distanceThreshold) { return true; } else { return false; } }