Go Down

Topic: Using multiple PING ultrasonic sensors to light up LEDs (Read 70 times) previous topic - next topic

hamithepenguin

Hello, I have been working on using multiple ultrasonic sensors that light up LEDs, but have been failing.
The following is my code:

const int pingPins[] = {7,8};
char*pingString[] = {"1","2"};
int L[] = {2,3,4,5};

void setup() {
  int i;
  Serial.begin(9600);
  for (i=0; i<4; i++){
    pinMode(L,OUTPUT);
  }
}
//Ping function
unsigned long ping(int index)
{
 unsigned long echo;

 pinMode(index, OUTPUT); // Switch signalpin to output
 digitalWrite(index, LOW); // Send low pulse
 delayMicroseconds(2); // Wait for 2 microseconds
 digitalWrite(index, HIGH); // Send high pulse
 delayMicroseconds(5); // Wait for 5 microseconds
 digitalWrite(index, LOW); // Holdoff
 pinMode(index, INPUT); // Switch signalpin to input
 digitalWrite(index, HIGH); // Turn on pullup resistor
 echo = pulseIn(index, HIGH); //Listen for echo
 return (echo / 58.138); //convert to CM

void loop()
{
  unsigned long ultrasoundValue;
  for(int i=0; i < 4; i++){ //loops from i=0 to i = 3
    ultrasoundValue=ping(i); //saves ultrasoundValue as the value of ping(i)
    Serial.print(pingString);
    Serial.print(ultrasoundValue); //prints value
    Serial.print("cm, ");
    delay(50); //repeats every 50 milliseconds
    if(ping(i)<50){
      digitalWrite(L,HIGH);
  }
   
  Serial.println();
  delay(50);
}

}


I am using Tinkercad, but I don't see the LEDs turning on. Could you please find my mistake?

UKHeliBob

Please follow the instructions on posting code in Read this before posting a programming question unless the majority of your code is meant to be in italics and for the array index to be apparently missing
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

blh64

You only have 2 pins defined for your pings, but you iterate from 0...3 in loop

Normally with a ultrasonic sensor you have a ping pin and an echo pin and they are not the same but your code uses the same pin.  What sensor are you using?

Go Up