Hi, everyone.
There's no error with my sketch, but my project doesn't seem to work as intended. My hardware works just fine when I do the functions separately (one file for each function), but when I put them together (like the code below), nothing happened. So, I don't know what I might have missed. I've read the "Demonstration code for several things at the same time" but I don't understand it and I'm not really sure if it has anything to do with what I am doing.
#define echoPin 11
#define trigPin 10
#define servo 9
#define IR 8
#define relay 7
#define motor 6
#include <Servo.h>
Servo myservo;
int pos = 0;
float duration, distance;
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motor, OUTPUT);
pinMode(relay, OUTPUT);
pinMode(IR, INPUT);
myservo.attach(servo);
Serial.begin (9600);
}
void loop()
{
motionMotor();
waterRelay();
servoIR();
}
void motionMotor()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) * 0.0343;
Serial.print("Distance = ");
if (distance >= 100 || distance <= 2)
{
digitalWrite(motor, LOW);
Serial.println("Out of range");
}
else {
digitalWrite(motor, HIGH);
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
delay(500);
}
void waterRelay()
{
int val = analogRead(A0);
if (val >= 400 && val <= 499)
{
digitalWrite(relay, LOW);
{
Serial.print("water pump off ");
Serial.println(val);
delay(500);
}
}
if (val >= 500 && val <= 599)
{
digitalWrite(relay, HIGH);
{
Serial.print("water pump on ");
Serial.println(val);
delay(500);
}
}
if (val >= 600 && val <= 650)
{
digitalWrite(relay, LOW);
{
Serial.print("water pump off ");
Serial.println(val);
delay(500);
}
}
}
void servoIR()
{
myservo.write(0);
if (digitalRead(IR) == HIGH)
{
myservo.write(180);
delay(3000);
myservo.write(0);
delay(1000);
}
}
With this, I attached a screenshot of the serial monitor (5 seconds interval between the lines),
Please help me. Thank you.
