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);
  // Sets the trigger pin to HIGH state for 10 microseconds
  digitalWrite(triggerPin, HIGH);
  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(ledPin2, OUTPUT);
  pinMode(servoPin, OUTPUT); // blade
  pinMode(photoPin, INPUT); // light sensor
  pinMode(motorPin, OUTPUT); // wheels
} // end setup

void loop() {


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("in, ");
  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);
  if (proximity == HIGH) // If the sensor's output goes high, motion is detected
        Serial.println("Motion detected!");
        digitalWrite(ledPin2, HIGH);

  • you are adding multiple layers of confusion to your code ... ledPin2 refers to pin 10, not pin 2 ... it makes more sense to name it something like greenPin
    – jsotola
    Nov 18 '20 at 21:47
  • So, proximity is always LOW, which means MOTION_PIN is always 0. Maybe your PIR sensor isn't connected to pin 2, or maybe it needs a pull-up or pull-down resistor on its data pin.
    – ocrdu
    Nov 19 '20 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.