Randomness with motion sensor

hi there!
very new to arduino and coding but i'm trying to program lights for my graduation work at art university and what i’d like it to do is (i think) not tooooo complicated but maybe i just don’t know enough lol

but basically, this is my set up:

  • arduino uno r3
  • hc-sro4 motion sensor
  • string of led light bulbs (5v)
  • external power supply

the function i need is for the arduino to program the light bulbs to slowly glow in and out on a dim brightness but when motion is detected, i need the light bulbs to either;
randomly
glow brighter and stay on for 10 seconds
or
glow dimmer and turn off for 10 seconds
to then return back to the slow glow in and out until motion is detected again, continuing a loop

i hope that doesn’t sound too complicated lol

i have so far gotten the code to make my lights glow in and out but have only managed to get the lights to turn brighter when motion is detected

i’d like some help to

  1. make the lights stay on for 10 seconds before returning to the glowing in & out
  2. add the random factor of either glowing brighter and staying on or glowing dimmer and turning off

if this isn't possible, let me know! just trying my luck :slight_smile:
thank u anyways for reading this!

here is the code:::


#include <NewPing.h>

// Pin connections
const int trigPin = 2;         // Trigger pin of HC-SR04 connected to Arduino digital pin 2
const int echoPin = 3;         // Echo pin of HC-SR04 connected to Arduino digital pin 3
const int ledPin = 9;          // LED pin connected to Arduino digital pin 9



// Variables
NewPing sonar(trigPin, echoPin);
int brightness = 0;
int fadeAmount = 5;    // Delay between brightness steps in milliseconds
int fadeDelay = 30;
int motionThreshold = 10; // Distance threshold for motion detection in centimeters

bool motionDetected = false;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // Measure the distance using the ultrasonic sensor
  unsigned int distance = sonar.ping_cm();
  
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  
  // Check if motion is detected
  if (distance > 0 && distance <= 20) {
    motionDetected = true;
  } else {
    motionDetected = false;
  }
  
  // Control the LED light
  if (motionDetected) {
    digitalWrite(ledPin, HIGH);  // Turn on the LED at full brightness
  } else {
    analogWrite(ledPin, brightness);  // Fade the LED
    
    brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(20);
}


}

How does the ultrasonic sensor sense motion?

This is totally possible, a recommendation would be using,
randomSeed(analogRead(A5)); // Can be any analog pin.
to get more random output.

Will need a few more conditions to make it work, get the random number and check to see if more or less then what you want.

If it was me, I would use an Infared sensor for motion detection.

I'd also check out a Microwave motion detector to see if it suits the project.

I've used an electronic anemometer to detect motion in a room, worked well.

4 Likes

it's a distance sensor! if i know what you mean! it uses sonic waves to measure the distance because i basically need it to be triggered when someone walks past the sensor

ok!! thank u!!
sorry if i sound silly but where do i put that part of the code?

because i tried just the normal random() function and put it here::

if (distance > 0 && distance <= 20) {
    motionDetected = true;
  } else {
    motionDetected = false;
  }

but nothing happened

Be careful with your design. Most clothing and live people are very good at absorbing sound, not reflecting it.

1 Like

With any sensor it makes sense, cough, to start with a very simple sketch just to see what gets reported as you move about, in this case, the detection area.

Just get the distance and print it in a loop. Watch the numbers spill and see what it is detecting and what it is not.

The rest of the logic can be perfected using a pushbutton as a proxy for in range versus not in range.

Then combine the two working parts.

Not to throw more cabbage into the soup, so to speak, but you might take a brief moment to see if another kind of sensor would be a better fit.

PIR motion detectors work well. A similar experiment can be conducted. PIR can be aimed and constrained by use of opaque materials forming cones of "vision".

a7

3 Likes

What did you put there?

Like this maybe?
Motion detected:
True: increase brightness by random
False do normal stuff.

Why do you need a separate if?
Maybe change digitalWrite to:

analogWrite(ledPin, random(min,max))

Note: not tested may have bugs.

Just put it in setup as it only needs to be called once.
It is just used to make the random output more unpredictable.

Use

some_variable = random(min, max);

to get the random number.
Or do it like @anon92864395 if that is alright.

Since there are only two options when motion is detected I'd suggest you don't even need the random function. You could just check the low bit of millis() to see if it's true or false and go from there.

pseudocode:

if(motionDetected){
  if(bitRead((millis(),0){
    doOneThing // if bit is on
  }
  else doOtherThing // if bit is off
}

The randomness is introduced by the person triggering the sensor at some unknown, unpredictable time.

1 Like

Help with code - any bugs you notice?
Is this related?

yes! this is the same project - i have changed the code quite a bit from here though!
since i was able to figure out the randomness :slight_smile:

hey there!

for my art university graduation project, i am building a light installation using an arduino uno r3, motion sensor hc-sro4 and a string of led lights.

the code is meant to make the leds pulsate/glow (bright to dark) until motion is detected and either turns the lights to full brightness or turns them off based on a random function.

the project is about the probability of luck which is why i need the randomness function to either turn the lights on / off.

the problem im having though is that sometimes when the lights come back on from being completely off, they flicker very very fast instead of pulsate?
i'm not sure if this is a coding error or if my wiring is wrong.

does anyone know why this could be happening?
because it only happens sometimes when the pulsating is meant to start again.

#include <NewPing.h>

// Pin connections
const int trigPin = 2;
const int echoPin = 3;
const int ledPin = 9;

// Variables
NewPing sonar(trigPin, echoPin);
int brightness = 0;
int fadeAmount = 5;
int fadeDelay = 30;
int motionThreshold = 50;  // Adjust as necessary
bool motionDetected = false;
unsigned long motionTime;
const unsigned long interval = 7000;  // 10 seconds interval
bool isDimmed = false;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  unsigned int distance = sonar.ping_cm();

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  if (distance > 0 && distance <= motionThreshold) {
    if(!motionDetected) { // Only trigger if motion was not already detected
      motionDetected = true;
      motionTime = millis();  // Capture the time when motion was detected
      isDimmed = random(0, 2);  // Randomly decide to dim or brighten
      if(isDimmed) {
        brightness = 0;  // Dim the light
      } else {
        brightness = 255;  // Brighten the light
      }
      analogWrite(ledPin, brightness);
    }
  } else if (motionDetected && ((millis() - motionTime) > interval)) {  // If motion was detected and 10 seconds have passed
    motionDetected = false;
  }

  if(!motionDetected) {
    brightness = brightness + fadeAmount;
    analogWrite(ledPin, brightness); // Fade the LED

    // reverse the direction of the fading at the ends of the fade:
    if (brightness <= 0 || brightness >= 255) {
      fadeAmount = -fadeAmount;
    }
    delay(fadeDelay);
  }
}

thank you for your time <3333

i have this code too that i worked on with some help but it doesn't really work either
does it seem any better/worse?

#include <NewPing.h>

// Pin connections
const int trigPin = 2;         // Trigger pin of HC-SR04 connected to Arduino digital pin 2
const int echoPin = 3;         // Echo pin of HC-SR04 connected to Arduino digital pin 3
const int ledPin = 9;          // LED pin connected to Arduino digital pin 9



// Variables
NewPing sonar(trigPin, echoPin);
int brightness = 0;
int fadeAmount = 5;    // Delay between brightness steps in milliseconds
int fadeDelay = 50;
int motionThreshold = 10; // Distance threshold for motion detection in centimeters
int choise = 0; //Number for deciding wheter light gets brighter or darker

bool motionDetected = false;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // Measure the distance using the ultrasonic sensor
  unsigned int distance = sonar.ping_cm();
  
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  
  // Check if motion is detected
  if (distance > 0 && distance <= 100) {
    motionDetected = true;
  } else {
    motionDetected = false;
  }
  
  // Control the LED light
  if (motionDetected) {
    choise = random(2);
    if (choise == 0) {
      digitalWrite(ledPin, HIGH);  // Turn on the LED at full brightness
      delay(9000); // Light stay high for 1 second
      } 
    else {
    analogWrite(ledPin, 0); //Dimmed light(do change value difficult to know how dim this is without seeing)
    delay(9000); // Light dim for 1 second before turning off
    digitalWrite(ledPin, LOW); //Light off
    }
  }
  else {
    analogWrite(ledPin, brightness);  // Fade the LED
    
    brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 240) {
    fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(35);
}


}```

hey there!

for my art university graduation project, i am building a light installation using an arduino uno r3, motion sensor hc-sro4 and a string of led lights.

the code is meant to make the leds pulsate/glow (bright to dark) until motion is detected and either turns the lights to full brightness or turns them off based on a random function.

the project is about the probability of luck which is why i need the randomness function to either turn the lights on / off.

the problem im having though is that sometimes when the lights come back on from being completely off, they flicker very very fast instead of pulsate?
i'm not sure if this is a coding error or if my wiring is wrong.

does anyone know why this could be happening?
because it only happens sometimes when the pulsating is meant to start again.

#include <NewPing.h>

// Pin connections
const int trigPin = 2;
const int echoPin = 3;
const int ledPin = 9;

// Variables
NewPing sonar(trigPin, echoPin);
int brightness = 0;
int fadeAmount = 5;
int fadeDelay = 30;
int motionThreshold = 50;  // Adjust as necessary
bool motionDetected = false;
unsigned long motionTime;
const unsigned long interval = 7000;  // 10 seconds interval
bool isDimmed = false;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  unsigned int distance = sonar.ping_cm();

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  if (distance > 0 && distance <= motionThreshold) {
    if(!motionDetected) { // Only trigger if motion was not already detected
      motionDetected = true;
      motionTime = millis();  // Capture the time when motion was detected
      isDimmed = random(0, 2);  // Randomly decide to dim or brighten
      if(isDimmed) {
        brightness = 0;  // Dim the light
      } else {
        brightness = 255;  // Brighten the light
      }
      analogWrite(ledPin, brightness);
    }
  } else if (motionDetected && ((millis() - motionTime) > interval)) {  // If motion was detected and 10 seconds have passed
    motionDetected = false;
  }

  if(!motionDetected) {
    brightness = brightness + fadeAmount;
    analogWrite(ledPin, brightness); // Fade the LED

    // reverse the direction of the fading at the ends of the fade:
    if (brightness <= 0 || brightness >= 255) {
      fadeAmount = -fadeAmount;
    }
    delay(fadeDelay);
  }
}

thank you for your time <3333

You are turning the brightness for nearly completely of to fully on.

2 Likes

so turning the brightness from completely off to fully on causes it to flicker? is that because of the current?
since i'm unsure of why it only does it sometimes

i have this code too that i worked on with some help but it doesn't really work either

#include <NewPing.h>

// Pin connections
const int trigPin = 2;         // Trigger pin of HC-SR04 connected to Arduino digital pin 2
const int echoPin = 3;         // Echo pin of HC-SR04 connected to Arduino digital pin 3
const int ledPin = 9;          // LED pin connected to Arduino digital pin 9



// Variables
NewPing sonar(trigPin, echoPin);
int brightness = 0;
int fadeAmount = 5;    // Delay between brightness steps in milliseconds
int fadeDelay = 50;
int motionThreshold = 10; // Distance threshold for motion detection in centimeters
int choise = 0; //Number for deciding wheter light gets brighter or darker

bool motionDetected = false;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // Measure the distance using the ultrasonic sensor
  unsigned int distance = sonar.ping_cm();
  
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  
  // Check if motion is detected
  if (distance > 0 && distance <= 100) {
    motionDetected = true;
  } else {
    motionDetected = false;
  }
  
  // Control the LED light
  if (motionDetected) {
    choise = random(2);
    if (choise == 0) {
      digitalWrite(ledPin, HIGH);  // Turn on the LED at full brightness
      delay(9000); // Light stay high for 1 second
      } 
    else {
    analogWrite(ledPin, 0); //Dimmed light(do change value difficult to know how dim this is without seeing)
    delay(9000); // Light dim for 1 second before turning off
    digitalWrite(ledPin, LOW); //Light off
    }
  }
  else {
    analogWrite(ledPin, brightness);  // Fade the LED
    
    brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 240) {
    fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(35);
}


}```

does this seem any better?