Ultrasonic sensor and IF statement

I have worked on this since the previous inquiry for some help. The goal is to have the LED blink quicker when an object gets closer to the sensor- (PART A) IF nothing is closer than 150 cm, the goal was to have it pulse ot thob like a mac start button (PART B) The program runs fine when an object is within 150cm, then once an object is outside of 150cm it will throb, BUT the serial monitor seems to stop or slow down making return to the PART A of the code slow and glitchy.. I'd like it to be a little more responsive and seemless.
Some construtive input is very welcome. Thank you

/*
* EZ rangefinder Distance Sensor
* prints distance and changes LED flash rate
* depending on distance from sensor
* if sensor range is greater than 150cm then LED "throbs" like apple computer
*/

const int sensorPin = 5;
const int ledPin = 6; //pin connected to LED

long value = 0;
int cm = 0;
int inches = 0;

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

void loop()
{
  value = pulseIn(sensorPin, HIGH);
  cm = value / 58;   // pulse width is 58 microseconds per cm
  Serial.print(cm);
  Serial.print(',');
  
  digitalWrite(ledPin,HIGH);
  delay(cm * 5);  //each centimeter adds 10 milliseconds delay
  digitalWrite(ledPin, LOW);
  delay( cm * 5);
  delay(20);

  if(cm > 150)
     for(int i = 0; i<360; i++){
     //convert 0-360 angle to radian (needed for sin function)
     float rad = DEG_TO_RAD * i;
 
    //calculate sin of angle as number between 0 and 255
     int sinOut = constrain((sin(rad) * 128) + 128, 0, 255);
 
    analogWrite(ledPin, sinOut);
 
    delay(10);
     }
 
}

Is there a reason for all those delays, especially the 3.6 seconds delay if cm > 150 ?

I suggest you look the "blink without delay" example, it could help :slight_smile:

I suggest you look the "blink without delay" example, it will help

There, I fixed that for you.

1 Like