I need help with my code.

For Adafruit customers who seek help with microcontrollers

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
pieterdekunder
 
Posts: 7
Joined: Sun Nov 10, 2013 1:34 pm

I need help with my code.

Post by pieterdekunder »

I need some help with this code. It is supposed to light the LEDs up at certain distances, and display the distance on a lcd.
The lcd part works but I cant get the leds to work.I think it has something to do with the If Else statements, but I cant find the problem. Here is the code I have written.

Code: Select all

//DistanceMeter with LEDs
//Made by Pieterdekunder

#define TRIGGER_PIN  12 
#define ECHO_PIN     11
#define MAX_DISTANCE 200

#include <NewPing.h>
#include <Wire.h>  
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  Serial.begin(115200);
  lcd.begin(16,2);   

  for(int i = 0; i< 3; i++)
  {
    lcd.backlight();
    delay(250);
    lcd.noBacklight();
    delay(250);
  }
  lcd.backlight(); 
}

void loop() {
  lcd.setCursor(0,0);  
  unsigned int uS = sonar.ping();
  lcd.print("Distance:");{
  lcd.setCursor(10,0);
  lcd.print(" ");
  lcd.print(uS / US_ROUNDTRIP_CM);
  lcd.println("cm  ");
  }
  
  if (uS / US_ROUNDTRIP_CM > 50)
  { 
  digitalWrite(13, HIGH);
}
  
  else if (uS / US_ROUNDTRIP_CM >= 100)
  {
  digitalWrite(13, HIGH);
  digitalWrite(8, HIGH);
}
  
  else
  {
  digitalWrite(13, HIGH);
  digitalWrite(8, HIGH);
  digitalWrite(7, HIGH);
}
  
}
P.S. Im not very experienced with coding.
Im sorry if I posted this in the wrong category, because I couldnt find a coding category.

User avatar
Franklin97355
 
Posts: 23911
Joined: Mon Apr 21, 2008 2:33 pm

Re: I need help with my code.

Post by Franklin97355 »

Code: Select all

if (uS / US_ROUNDTRIP_CM > 50)
If it's greater than 50 LED 13 turns on and then the if statement ends so the else statements are never evaluated.

Locked
Please be positive and constructive with your questions and comments.

Return to “Microcontrollers”