i recently tried to use a PIR sensor and ultrasonic sensor that if activated at the same time move the servos as the given specs. Can you guys find what's wrong with my code?
#include <Servo.h>
Servo servo1, servo2;
#define pirPin 2
#define pinServo1 3
#define pinServo2 9
int cm;
int pirStat;
int pos1, pos2;
long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(5);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}
void setup()
{
Serial.begin(115200);
pinMode(pirPin, INPUT);
servo1.attach(pinServo1);
servo2.attach(pinServo2);
}
void loop(){
pirStat = digitalRead(pirPin);
cm = 0.01723 * readUltrasonicDistance(5, 6);
if (pirStat == HIGH ){
if (cm <= 10){
pos1 = 90;
pos2 = -90;
servo1.write(pos1);
servo2.write(pos2);
delay(1);
}
if(cm > 10){
pos1 = 0;
pos2 = 0;
servo1.write(pos1);
servo2.write(pos2);
delay(1);
}
}
if (pirStat == LOW){
pos1 = 0;
pos2 = 0;
servo1.write(pos1);
servo2.write(pos2);
delay(1);
}
}
yes I actually had checked my wiring and it didn't had any mistake. Then I simulated it on tinkercad but my code only move 1 servo with the desired specs.
I don't know if -90 works. I don't care if -90 or +1000000 works. That is not important.
The parameter for the angle can be 0 ... 180. That's all you have to know.
Do you see what I did here ? Use the library function as described in the documentation. Sometimes wrong values are ignored, sometimes wrong values are replaced by a limit and sometimes it can cause undefined behaviour. Let's not go there, follow the documenation.
When the project is powered on, and the Arduino sketch does a servo.attach(), then it defaults to its middle position. That is 90 degrees. So it defaults to 90.
@andrewtim I haven't used this software before, but you can try to change servo1.write(90); to servo1.write(180); maybe it will work. I've done something similar before, I use actual motors and try servo1.write(180); and it works.