After struggling for few days i decided to post my problem online:
I'm using ultrasonic sensor to measure distance. My goal is to when the distance is >90 a smiley is displayed on my 8x8 led matrix display and when distance is <90 (cm) a - smiley is displayed. The distance measurement works fine but the problem is when i add the if( distance <= 90 ); For some reason when ever i add the if statement my ultrasonic sensor starts displaying about 5cm (1-10) and thus showing
- smiley.
Can someone take a look and tell me what I'm doing wrong and why do i start getting wrong readings?
#include "LedControl.h"
LedControl lc=LedControl(12,11,10,2);Â // Pins: DIN, CLK, CS
int echo = 3;
int trig = 2;
int beep = 7;Â // currently not used
int led = 5;
float pingTime;Â Â
float distance;
float speedOfSound = 1.236;
byte smiley1[]{
B00000000,
B01100110,
B01100110,
B00000000,
B00000000,
B01000010,
B00111100,
B00000000,
};
byte smiley2[]{
B00000000,
B01100110,
B01100110,
B00000000,
B00111100,
B01000010,
B01000010,
B00111100,
};
void setup(){
 Serial.begin(9600);
 pinMode(echo, INPUT);
 pinMode(trig, OUTPUT);
 pinMode(beep, OUTPUT);
 pinMode(led, OUTPUT);
Â
 lc.shutdown(0,false); // Wake up display
 lc.setIntensity(0,1); // Set intensity level
 lc.clearDisplay(0); // Clear Display
}
void Smiley1(){
 for (int i = 0; i < 8; i++) {
  lc.setRow(0, i, smiley1[i]);
 }
}
void Smiley2(){
 for (int i = 0; i < 8; i++) {
  lc.setRow(0, i, smiley2[i]);
 }
}
void loop(){
 digitalWrite(trig, LOW);
 delayMicroseconds(2000);
 digitalWrite(trig, HIGH);
 delayMicroseconds(10);
 digitalWrite(trig, LOW);
 pingTime = pulseIn(echo, HIGH);
 pingTime = pingTime / 1000000.;
 pingTime = pingTime / 3600.;
 distance = speedOfSound * pingTime;
 distance = distance / 2;
 distance = distance * 100000000;
 Serial.print(distance);
 Serial.println(" cm");
 if( distance <= 90 ){
  Smiley2();
  digitalWrite(led, HIGH);
 }
 else{ Smiley1(); }
Â
 delay(5);
 digitalWrite(led, LOW);
}
PS It works fine without the if statement, if i remove it i get the right distance reading.