Ultrasonic Sensor LED Randomly Flashing

Hey guys!

I’m pretty much a newbie to arduino and a complete newbie to this forum so sorry if this question isn’t proper. Anyways, I’m trying to make a project using an ultrasonic sensor, a gps module, a temperature sensor, and an lcd. The temperature gets the temperature and prints it to an lcd. I have an ultrasonic sensor that flashes an led when something gets too close. And I print gps data like long, lat, and time. This is my code

//temp & humidity sensor & gps module library
#include <Adafruit_HTU21DF.h>
#include <TinyGPS++.h>

#include <Wire.h>
#include "U8glib.h"
#include <SoftwareSerial.h>

U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);  // I2C / TWI 
Adafruit_HTU21DF htu = Adafruit_HTU21DF();

static const int RXPin = 5, TXPin = 4;
static const uint32_t GPSBaud = 9600;

const int trigPin = 2;
const int echoPin = 3;

// defines variables
long duration;
int distance;
int tempc;
int tempf;
int hum;
unsigned long starttime;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

//temp display function
void temp(void) {

  //temp
  u8g.setFont(u8g_font_profont22);
  u8g.setPrintPos(70, 35);
  u8g.print(tempf);
  u8g.setPrintPos(18, 35);
  u8g.print(tempc);

  //degree
  u8g.setFont(u8g_font_profont12);
  u8g.drawStr(94, 25, "o");
  u8g.drawStr(42, 25, "o");

  //celcius / fahrenheit 
  u8g.setFont(u8g_font_profont17);
  u8g.drawStr(103, 35, "F");
  u8g.drawStr(51, 35, "C");

  //seperating lines
  u8g.drawLine(17, 40, 111, 40);
  u8g.drawLine(64, 40, 64, 20);

  //humidity
  u8g.setFont(u8g_font_profont22);
  u8g.setPrintPos(50, 60);
  u8g.print(hum);
  u8g.drawStr(73, 60, "%"); 

}

//check distance
void checkDis(){
    
    // Clears the trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    // Calculating the distance
    distance= duration*0.034/2;

    if (distance<14){
      digitalWrite(12, HIGH);
      
    }
    else{
      digitalWrite(12, LOW);
    }

}

void setup(){
  Serial.begin(9600);
  ss.begin(GPSBaud);
  
  // rotate lcd
  u8g.setRot180();

  //define pins
  pinMode(trigPin, OUTPUT); 
  pinMode(echoPin, INPUT);

  //led pin
  pinMode(12, OUTPUT);

  //find sensor
  Serial.println("HTU21D-F test");
  if (!htu.begin()) {
    Serial.println("Couldn't find sensor!");
    while (1);
  }
}


void loop(){

  //get temp & humidity
  tempc = round(htu.readTemperature());
  tempf = round((tempc * 1.8) + 32);
  hum = round(htu.readHumidity());

  //check distance
  checkDis();

  // get gps data
  while (ss.available() > 0){
    gps.encode(ss.read());
    if (gps.location.isUpdated()){
      String ampm;
      Serial.print("Speed in km/h = "); 
      Serial.println(gps.speed.kmph());
      Serial.print("Latitude= "); 
      Serial.print(gps.location.lat(), 6);
      Serial.print(" Longitude= "); 
      Serial.println(gps.location.lng(), 6);
      Serial.println(gps.time.hour(), 6);
      int hr = gps.time.hour() - 5;
      int what = gps.time.hour();
      int mi = gps.time.minute();
      
      if (hr<12 and hr>0){ 
        if(hr==0){
          hr = 12;
        }
        ampm = "AM";
      }
      else if (hr==12){
        ampm = "PM";
      }
      else if (hr>12){
        
        hr = hr-12;
        ampm = "PM";
      }
      else if (hr<0){
        int savehr = hr;
        hr = 12 + savehr;
        ampm = "PM";
      }
      else{
        
      }

      Serial.print(hr); 
      Serial.print(":");
      if (mi>9){
        Serial.print(mi); 
        Serial.print(" ");
      }        
      else{
        Serial.print("0");
        Serial.print(mi);
        Serial.print(" ");
      }
      Serial.println(ampm);
    }
  }
 
  //display temp
  u8g.firstPage();  
  do {  
    u8g.drawLine(0, 12, 130, 12);
    temp();
  } while( u8g.nextPage() );


}

The problem is, my led flashes randomly. It stays on when i put something in front of the sensor, but when it doesn’t sense anything, it just randomly flashes. I don’t know if this has anything to do with the GPS sensor because that doesn’t print at regular intervals. Any help on this would be great! Feel free to ask for any clarification.

I recommend you to print distance to Serial Monitor, so you can get a better idea of what’s happening:

    if (distance<14){
      digitalWrite(12, HIGH);
      Serial.print("distance: ");
      Serial.println(distance);     
    }

When pulseIn times out (no echo was received by the ultrasonic sensor), it returns 0. But your code doesn’t correctly handle that eventuality.

I just tried that. it sometimes prints 9 for some reason. When I try it by itself however, it works fine and doesn't have this error.

Hi, Have you tried the NewPIng library to get your ultrasonic readings?

Tom... :)