Here is the code I've written so far. I am making a circuit with a couple of motors and 3 sensors. My plan is for the PIR Motion sensor, distance sensor, and photoresistor to tell the motors to stop when they're triggered. When I set the if proximity = LOW, the LED lights up whether I move the sensor or not. But when it's set to HIGH, the LED won't light up even if motion is detected. I've tested it separately from the rest of the code and it doesn't do this. Is there something wrong with how I've got my simultaneous loops?
int inches = 0;
const int ledPin1=11; // blue LED
const int ledPin3 = 9; // red LED
const int servoPin = 4; // blade motor
const int MOTION_PIN = 2; // Pin connected to motion detector
const int ledPin2 = 10; // green LED
const int photoPin = 3; // photoresistor connected to digital pin 2
const int motorPin = 13; // motor for the wheels connected to digital pin 13
int cm = 0;
long readUltrasonicDistance(int triggerPin, int echoPin) // setting up the distance sensor, this code is pre-set up along with the circuit
{
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(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
} // long
void setup()
{
Serial.begin(9600); // loop time
pinMode(ledPin1, OUTPUT); // sets the blue LED as an output
pinMode(ledPin3, OUTPUT);
pinMode(MOTION_PIN, INPUT);
pinMode(ledPin2, OUTPUT);
pinMode(servoPin, OUTPUT); // blade
pinMode(photoPin, INPUT); // light sensor
pinMode(motorPin, OUTPUT); // wheels
} // end setup
void loop() {
dist();
motion();
}
void dist()
{
// measure the ping time in cm
cm = 0.01723 * readUltrasonicDistance(7, 7);
// convert to inches by dividing by 2.54
inches = (cm / 2.54);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.println("cm");
if (cm<150) // if an object (another person) approaches within 1.5 meters
{
digitalWrite(ledPin1, HIGH); // turn on the blue LED, symbolically represents roomba reaction to go around or stop
} // end loop
}
void motion()
{
int proximity = digitalRead(MOTION_PIN);
Serial.println(proximity);
if (proximity == HIGH) // If the sensor's output goes high, motion is detected
{
Serial.println("Motion detected!");
digitalWrite(ledPin2, HIGH);
}
}
ledPin2refers to pin 10, not pin 2 ... it makes more sense to name it something likegreenPin– jsotola Nov 18 '20 at 21:47