Parking Assistant -- Code Assistance

All,

I am very new at writing code; I would like someone with more experience to look my sketch over and provide me with some advice on how I could have improved my sketch. I have included a schematic of everything that I am using in my project.

The main idea of the project is to assist you when you are parking your car in the garage. It uses a ultrasonic distance detector (HC-SR04) to check the distance of an approaching car. The RGB LED changes from Green(pull forward), Yellow(Slowly pull forward), Red(Stop) & flashing Red (to backup).

The second part of the project controls a LED Strip using a LDR (photocell) and a PIR to detect motion. The LED strip is to provide enough light to get in and out of your vehicle. We all know that the garage door opener has a dimly lit light bulb and doesn't help much.

**I would like to say thank you in advance for your assistance in helping me gain more experience in writing code. I am a guy that learns by doing.

#include <NewPing.h>            //include the NewPing library

 //parking system I/O pins
int rLED = 5;
int gLED = 6; 
int buttonPin = 7;
int echo = 10;
int trigger = 11;
int garageDoor = 2;  // garage door switch, HIGH if garage door is open; LOW if garage is closed

//LED strip lighting system I/O pins
int motionPin = 12; // input from PIR motion sensor
int lightPin = analogRead(A1);  // input from LDR voltage divider circuit; 2-2.9V = dark, 3-5V = enough light 
int ledPin = 3; //pin feeding TIP122
int onboardLED = 13 //onboard LED for some debugging
int motionPin = 12   //PIR connection

 //variables
 int distance = 0;
 int set = 0;
 int upper = 0;             
 int lower = 0;
 int range = 3;                                   //range is +/- so it is double the value in inches
 int count = 0;
 boolean lastButton = LOW;          //keep track of button status
 boolean currentButton = LOW;
 int previous = 0;                              //keep track of distances to identify when car is parked
 int current = 0; // current distance 

 int fadeSpeed 10 //adds dimming & fading effect to LED Strip
 int led = 0; // PWM status of LED Strip
 int motion = LOW; // status of PIR
 float lightVolts = lightPin*(5.0/1023.0) // converts analog reading (0-1023) to a voltage (0-5 Volts)
 int timer = 180000; // timer to turn off the lights after 3 min (180seconds) after last PIR activation
 int light; // status of LDR


 NewPing sonar(0, 1, 500);       //constructor for NewPing sonar(triggerPin, echoPin, max_CM)

 void setup()
 {
 pinMode(gLED, OUTPUT);
 pinMode(rLED, OUTPUT);
 pinMode(buttonPin, INPUT);
 pinMode(garageDoor, INPUT);
 pinMode(ledPin, OUTPUT);
 pinMode(onboardLED, OUTPUT);
 pinMode(motionPin, INPUT);
 pinMode(lightPin, INPUT);

Serial.begin(9600); //initialize serial communication at 9600 bits per second
 }
 void loop()
 {
   distance = sonarPing_in();                  //detect distance in inches
   if(distance == 0) distance = 500;          //if no distance is read, set at max distance
   current = distance;                                
  
   delay(100);                                             // this slows the program down a little bit
  
   currentButton = debounce(lastButton);            //reads button status and performs debounce  
   if(lastButton == LOW && currentButton == HIGH)          //when button pushed, set desired distance for parking
   {
     set = distance;                                //new variable for distance measured
     flashGreen();                                  //flicker green LED 3 times
     flashGreen();
     flashGreen();
   }
  
   lastButton = currentButton;            //reset button status
  
   upper = set + range;                        //  +/- inch tolerance range 
   lower = set - range; 
  
   if(distance <= upper && distance >= lower)            //within set area, stop!
   {
     //distance fluctuates some resulting in false movement detection
     if(current == previous || current == previous + 1 || current == previous - 1 )
     {
       count++;                           //increase count if car has not moved
     }
     else
     {
       count = 0;                          //resent count if there is a significant change in distance
     }
    
     // turn the parking system off if the garage door is closed
     {
if(garageDoor == LOW)       
off();
      }
     else
     {
       red();                                   // within range, stop. red LED on
     }
    
   }
   if(distance > upper)
   { 
     count = 0;         //if car moves slow enough, it may never reset the count in above code, we reset again, just in case
                                        
     if(distance >= set+120)              //sensor becomes inaccurate at distances much further than 120 inches
     {                                                   //no car in garage turn LED off 
       off();
     }                                              
     if(distance < set+120 && distance > set+50)                  //car is detected
     {                                                                                           //if distance is less than set + 120 inches and greater than set +50 inches
       green();
     }
     if(distance <= set+50 && distance > upper)          //within 50 inches of set distance, slow down
     { 
       yellow();
     } 
   }
   if(distance < lower)                                                           //car is too close, you must back up
   {
     count = 0;                                                                         //same situation for if car moves very slowly
     flashRed();
   }
  
   previous = distance;                                                        //update distances
 }                                                                                            //end of loop

 //debounce method to correct for voltage spikes that cause unexpected behavior
 boolean debounce(boolean last)
 {
   boolean current = digitalRead(buttonPin);
   if (last != current)
   {
     delay(5);
     current = digitalRead(buttonPin);
   }
   return current;
 }

 //color methods;
 void green()
 {
    digitalWrite(rLED, LOW);                 //because HIGH = LED is on & LOW = LED is off
    digitalWrite(gLED, HIGH); 
 }
 void red()
 {
   digitalWrite(gLED, LOW);   
   digitalWrite(rLED, HIGH);
 }
 void yellow() // uses PWM to make yellow
 {
   digitalWrite(rLED, 250); 
   digitalWrite(gLED, 100);
 }
 void flashRed()
 {
   digitalWrite(gLED, LOW);                     //flash red LED
   digitalWrite(rLED, HIGH);
   delay(100);
   digitalWrite(rLED, LOW);
   delay(100);
 }
 void flashGreen()
 {
   digitalWrite(rLED, LOW);
   digitalWrite(gLED, HIGH);                  //quick green LED flash when button pushed
   delay(50);
   digitalWrite(gLED, LOW);
   delay(50);
 }
 void off()
 {
   digitalWrite(gLED, LOW);                  //turn off the LED
   digitalWrite(rLED, LOW);
 }
 void ledstrip()
{
  light = analogRead(lightPin); //read light levels
  Serial.print("Light Level: "); 
  Serial.println(lightVolts);  //send LDR voltage to serial
  motion = digitalRead(motionPin); //read motion from PIR
 
  Serial.print("Motion: "); 
  Serial.println(motion);  //send motion state to serial
  Serial.println(led);
 
  if(lightVolts <= 3.0) && (motion == HIGH)) //if motion detected and  lightPin is below 3 volts
     { 
    while (led; 255) // if the LED strip is below full brightness
{ 
      led++; //increment fade up to full power
      analogWrite(LEDPin, led); //write change to LED control Pin into TIP122
      delay(fadeSpeed); 
      }
   }   
  else if((motion == 0) &amp;&amp; (led; 0)) { //otherwise if motion not detected and led value is on, fade down
    delay(timer)
    led--; 
    analogWrite(LEDPin, led);
    delay(fadeSpeed);
     }
 
else 
 {
  delay(1000); // delays 1 sec if motion is still detected and repeats till motion not detected
  Serial.println("delay");
  }
}

sethmoening:
... provide me with some advice on how I could have improved my sketch.

Have you tried to compile it yet?

A reasonable method would be to modularize it, getting it to do its discreet components separately, first.

you have quite a few funky things in your code...

else if((motion == 0) &amp;&amp; (led; 0))

should it read as below??

else if((motion == 0) && (led; 0))

sethmoening:
should it read as below??

else if((motion == 0) && (led; 0))

the key is to get it to compile, first.

Once you get there you can start to see what's happening (or not).

did you ever declare distance?

distance = sonarPing_in();                  //detect distance in inches

and where is the sonarPing_in() function declared?

Not sure if I did. I think my plan was to use distance as a variable. As to where the vehicle currently is.

I am focusing on getting each of the 2 functions to work.

First... The LDR and PIR control of the 12 V LED strip.

I have most of it worked out, but once the Motion == 1 && the LDR <= 300 (reading from the Serial) the loop seems to stop. The Serial prompts stop and the ledPin stays on.

//LED strip lighting system I/O pins
int motionPin = 12;     // input from PIR motion sensor
int lightPin = A2;  // input from LDR voltage divider circuit; 2-2.9V = dark, 3-5V = enough light 
int ledPin = 3;   //pin feeding TIP122
int onboardLED = 13;   //onboard LED, can be used for debugging

 //variables
 int distance = 0;
 int set = 0;
 int upper = 0;             
 int lower = 0;
 int range = 3;                                   //range is +/- so it is double the value in inches
 int count = 0;
 boolean lastButton = LOW;          //keep track of button status
 boolean currentButton = LOW;
 int previous = 0;                              //keep track of distances to identify when car is parked
 int current = 0;   // current distance 

 int fadeSpeed = 10;   //adds dimming & fading effect to LED Strip
 int led = 0;   // PWM status counter of LED Strip
 int motion = 0;  // status of PIR
 int timer = 5000;    // timer to turn off the lights after 3 min (180seconds) after last PIR activation
 int light;   // status of LDR

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);    //initialize serial communication at 9600 bits per second
 pinMode(ledPin, OUTPUT);
 pinMode(onboardLED, OUTPUT);
 pinMode(motionPin, INPUT);
 pinMode(lightPin, INPUT);


}

void loop() {
  // put your main code here, to run repeatedly:
{
  light = analogRead(lightPin); //read light levels
  Serial.print("Light Level: "); 
  Serial.println(light);  //send Light Level to serial
  motion = digitalRead(motionPin); //read motion from PIR
 
  Serial.print("Motion: "); 
  Serial.println(motion);  //send motion state to serial
  Serial.print("LED PWM: "); 
  Serial.println(led);
  delay(1000);
  
  if ((light <= 300) && (motion == 1))    //if motion detected and  lightPin is below 3 volts
     { 
    while (led) 255;  // if the LED strip is below full brightness
{ 
      led++; //increment fade up to full power
      analogWrite(ledPin, led);     //write change to LED control Pin into TIP122
      delay(fadeSpeed); 
      }
     }
//else if (light >= 301)
 //{ 
   // led--; 
    //analogWrite(ledPin, led);
    //delay(fadeSpeed);
   //  }  
  else if ((motion == 0) && (led == 255))  //otherwise if motion not detected and led value is on, fade down
   { 
    delay(timer);
    led--; 
    analogWrite(ledPin, led);
    delay(fadeSpeed);
     }  
else 
 {
  delay(1000);    // delays 1 sec if motion is still detected and repeats till motion not detected
  Serial.println("delay");
  }
 }
}

If led is ever non-zero, this will execute forever:

    while (led) 255;  // if the LED strip is below full brightness

The 255 does not belong, and neither does the semicolon.

You probably intended:

    while (led)  // if the LED strip is below full brightness

but since led is an int, this will still execute for a long time. led will have to increment up to 32767, then roll over to 0 before the while loop will end. You need to rethink this.

I was attempting to bring the PWM to 255 if the following is met:

if led <=255 && light <=300 && motion == 1

I need to figure out how to start the fade down sequence once motion == 0 after the delay(timer)

Thanks for your assistance!

sethmoening wrote (in part):

I was attempting to bring the PWM to 255 if the following is met:

if led <=255 && light <=300 && motion == 1

so perhaps you intended:

    led=0 ;
    while (led<255)  // if the LED strip is below full brightness

The issue here is that the while loop contains a delay(fadespeed) statement. Not much can happen during delay(...), so this may make you unhappy later on. For now, it is OK.

Thanks for the help.

After I did some research into what the different structures (if/else, While, and the like) operated, I was able to make the changes that I needed.

I got it operating as intended.

//LED strip lighting system I/O pins
int motionPin = 12;     // input from PIR motion sensor
int lightPin = A2;  // input from LDR voltage divider circuit; 2-2.9V = dark, 3-5V = enough light 
int ledPin = 3;   //pin feeding TIP122
int onboardLED = 13;   //onboard LED, can be used for debugging

 //variables
 int distance = 0;
 int set = 0;
 int upper = 0;             
 int lower = 0;
 int range = 3;                                   //range is +/- so it is double the value in inches
 int count = 0;
 boolean lastButton = LOW;          //keep track of button status
 boolean currentButton = LOW;
 int previous = 0;                              //keep track of distances to identify when car is parked
 int current = 0;   // current distance 

 int fadeSpeed = 10;   //adds dimming & fading effect to LED Strip
 int led = 0;   // PWM status of LED Strip
 int motion = LOW;  // status of PIR
 int timer = 5000;    // timer to turn off the lights after 3 min (180seconds) after last PIR activation
 int light;   // status of LDR

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);    //initialize serial communication at 9600 bits per second
 pinMode(ledPin, OUTPUT);
 pinMode(onboardLED, OUTPUT);
 pinMode(motionPin, INPUT);
 pinMode(lightPin, INPUT);

//LED strip lighting system I/O pins
int motionPin = 12;     // input from PIR motion sensor
int lightPin = A2;  // input from LDR voltage divider circuit; 2-2.9V = dark, 3-5V = enough light 
int ledPin = 3;   //pin feeding TIP122
int onboardLED = 13;   //onboard LED, can be used for debugging

 //variables
 int distance = 0;
 int set = 0;
 int upper = 0;             
 int lower = 0;
 int range = 3;                                   //range is +/- so it is double the value in inches
 int count = 0;
 boolean lastButton = LOW;          //keep track of button status
 boolean currentButton = LOW;
 int previous = 0;                              //keep track of distances to identify when car is parked
 int current = 0;   // current distance 

 int fadeSpeed = 10;   //adds dimming & fading effect to LED Strip
 int led = 0;   // PWM status counter of LED Strip
 int motion = 0;  // status of PIR
 int timer = 5000;    // timer to turn off the lights after 3 min (180seconds) after last PIR activation
 int light;   // status of LDR

void setup() // setup code here, to run once:
{
 Serial.begin(9600);    //initialize serial communication at 9600 bits per second
 pinMode(ledPin, OUTPUT);
 pinMode(onboardLED, OUTPUT);
 pinMode(motionPin, INPUT);
 pinMode(lightPin, INPUT);
}

void loop() {
  // main code here, to run repeatedly:
{
  light = analogRead(lightPin); //read light levels
  Serial.print("Light Level: "); 
  Serial.println(light);  //send Light Level to serial
  motion = digitalRead(motionPin); //read motion from PIR
 
  Serial.print("Motion: "); 
  Serial.println(motion);  //send motion state to serial
  Serial.print("LED PWM: "); 
  Serial.println(led);
  delay(1000);
  
  if ((light <= 300) && (motion == 1))    //if motion detected and  light level is below 300
     { 
    while (led < 255)  // if the LED strip is below full brightness
      { 
      ++led; //increment fade up to full power
      analogWrite(ledPin, led);     //write change to LED control Pin into TIP122
      delay(fadeSpeed); 
      }
     }
  else
   { 
   while (led > 0)  // if the LED strip is above zero
    {
    --led; 
    analogWrite(ledPin, led);
    delay(fadeSpeed);
    }
   }  

 
 }
}

All,

I was trying to use the following code to get both parts of my program to work.

I created "modules" for each color feedback for the RGB LED after the void loop().

I am getting an error that says I didn't declare flashgreen().

Am I missing something here?

Thanks again for your assistance!!

#include <NewPing.h>                  //include the NewPing library

 //parking system I/O pins
int rLED = 5;     // PWM pin output
int gLED = 6;       // PWM pin output
int buttonPin = 7;    // has a 10K pull-down resistor connected to ground
int echo = 10;
int trigger = 11;
int garageDoor = 2;     // garage door switch, HIGH if garage door is open; LOW if garage is closed
// has a 10K pull-down resistor connected to ground

//LED strip lighting system I/O pins
int motionPin = 12;     // input from PIR motion sensor
int lightPin = analogRead(A1);  // input from LDR voltage divider circuit; 2-2.9V = dark, 3-5V = enough light 
int ledPin = 3;   //pin feeding TIP122
int onboardLED = 13;   //onboard LED, can be used for debugging

 //variables
 int distance = 0;
 int set = 0;
 int upper = 0;             
 int lower = 0;
 int range = 3;                                   //range is +/- so it is double the value in inches
 int count = 0;
 boolean lastButton = LOW;          //keep track of button status
 boolean currentButton = LOW;
 int previous = 0;                              //keep track of distances to identify when car is parked
 int current = 0;   // current distance 

 int fadeSpeed = 10;   //adds dimming & fading effect to LED Strip
 int led = 0;   // PWM status of LED Strip
 int motion = LOW;  // status of PIR
 int timer = 180000;    // timer to turn off the lights after 3 min (180seconds) after last PIR activation
 int light;   // status of LDR

 NewPing sonar(11, 10, 500);       //constructor for NewPing sonar(triggerPin, echoPin, max_CM)

 void setup()
 {
 pinMode(gLED, OUTPUT);
 pinMode(rLED, OUTPUT);
 pinMode(buttonPin, INPUT);
 pinMode(garageDoor, INPUT);
 pinMode(ledPin, OUTPUT);
 pinMode(onboardLED, OUTPUT);
 pinMode(motionPin, INPUT);
 pinMode(lightPin, INPUT);

Serial.begin(9600);   //initialize serial communication at 9600 bits per second
 }
void loop()
{         //beginning of main loop
  
  {           //beginning of “LED Strip” sub-loop
    light = analogRead(lightPin); //read light levels
    Serial.print("Light Level: "); 
    Serial.println(light);  //send Light Level to serial
    motion = digitalRead(motionPin); //read motion from PIR
 
    Serial.print("Motion: "); 
    Serial.println(motion);  //send motion state to serial
    Serial.print("LED PWM: "); 
    Serial.println(led);
    delay(1000);
  
    if ((light <= 300) && (motion == 1))    //if motion detected and  light level is below 300
      { 
      while (led < 255)  // if the LED strip is below full brightness
          { 
          ++led; //increment fade up to full power
          analogWrite(ledPin, led);     //write change to LED control Pin into TIP122
          delay(fadeSpeed); 
          }
        }
    else
      { 
      while (led > 0)  // if the LED strip is above zero
          {
          --led; 
          analogWrite(ledPin, led);
          delay(fadeSpeed);
        }
    } 
  }           //end of “LED Strip” sub-loop 

  distance = sonar.ping_in();                      //detect distance in inches
    if(distance == 0) distance = 500;           //if no distance is read, set at max distance
    current = distance;                                
  
    delay(100);                                             // slows the program down
  
//    currentButton = debounce(lastButton);            //reads button status and performs debounce  
    if(lastButton == LOW && buttonPin == HIGH)          //when button pushed, set desired distance for parking
      {       //beginning of “set distance” sub-loop
      set = distance;                                //new variable for distance measured
      flashGreen();                                  //flicker green LED 3 times
      flashGreen();
      flashGreen();
   
      lastButton = currentButton;            //reset button status
  
      upper = set + range;                        //  +/- inch tolerance range 
      lower = set - range; 
      }       //end of “set distance” sub-loop
  
    if(distance <= upper && distance >= lower)            //car is parked in the set distance (+/- 6 inches)
      {     //beginning of “distance variance” sub-loop 
        //distance fluctuates some resulting in false movement detection
        if(current == previous || current == previous + 1 || current == previous - 1 )
          {
            count++;                           //increase count if car has not moved
        }
     
      else
          {
            count = 0;                          //resent count if there is a significant change in distance
          }
      }       //end of “distance variance” sub-loop
          

  {       //beginning of “visual feedback” sub-loop
  if(distance < set+120 && distance > set+48 && garageDoor == LOW)                  //car is detected
            //if distance is < set + 120” (10 ft) and > set + 48” (4 ft)
    {                                                                                 
    green();        // car is approaching, turn on the yellow LED
      }
  else if(distance <= set+50 && distance > upper && garageDoor == LOW)          //within 48” (4 ft) of set distance
                // slow down turn on the yellow LED
      { 
        yellow();
      } 
  else if(distance <= upper && distance >= lower && garageDoor == LOW)            //car is in the set distance (+/- range)
    {
    red();        // within range, stop and turn on the red LED
    }
  else if(distance < lower && garageDoor == LOW)                                         //car is too close, you must back up
      {
      count = 0;                                                                         
      flashRed();
      }
  else
      {
    off();
    }

    previous = distance;                                                        //update distances
  }       //end of “visual feedback” sub-loop

 
/*
        //debounce method to correct for voltage spikes that cause unexpected behavior
{       //beginning of “debounce” sub-loop
  boolean debounce(boolean last)
    {
      boolean current = digitalRead(buttonPin);
      if (last != current)
      {
      delay(5);
      current = digitalRead(buttonPin);
   
  return current;
  }       //end of “debounce” sub-loop
*/
 //RGB color methods;
void green()
  {
    digitalWrite(rLED, LOW);                 //because HIGH = LED is on & LOW = LED is off
    digitalWrite(gLED, HIGH); 
  }
void red()
  {
    digitalWrite(gLED, LOW);   
    digitalWrite(rLED, HIGH);
  }
void yellow()     // uses PWM to make yellow
  {
    digitalWrite(rLED, 250); 
    digitalWrite(gLED, 100);
  }
void flashRed()
  {
    digitalWrite(gLED, LOW);                     //flash red LED
    digitalWrite(rLED, HIGH);
    delay(100);
    digitalWrite(rLED, LOW);
    delay(100);
  }
 void flashGreen()
  {
    digitalWrite(rLED, LOW);
    digitalWrite(gLED, HIGH);                  //quick green LED flash when button pushed
    delay(50);
    digitalWrite(gLED, LOW);
    delay(50);
  }
 void off()
  {
    digitalWrite(gLED, LOW);                  //turn off the LED
    digitalWrite(rLED, LOW);
  }
   



}

I didn't declare flashgreen

But you did declare flashGreen

I know that I declared all of the "LED Mode" loops. That's what I don't get.

Should I declare that part of the code in the setup?

C++ is case sensitive.

That being said, flashGreen is declared and used in the posted code.
flashgreen does NOT appear in the posted code.

If there is still a problem, please post the code (via copy and paste, in code tags), and the COMPLETE error message (via copy and paste, in code tags).

Thanks!

To post code and/or error messages:

  1. Use CTRL-T in the Arduino IDE to autoformat your code.
  2. Paste the autoformatted code between code tags (the </> button)
    so that we can easily see and deal with your code.
  3. Paste the complete error message between code tags (the </> button)
    so that we can easily see and deal with your messages.

Before posting again, you should read the three locked topics at the top of the Programming Questions forum, and any links to which these posts point.

Good Luck!

Thank you so much!!

Its always the simple little details that can throw a wrench in the works. lol