0

My goal is to store the variable in the for loop as an array rather than as a single 'ultrasoundValue'. Can some one help me structure the code?

I have this code:

int ultraSoundSignalPins[] = {5,7}; 
int tx = 4;
char *pingString[] = {"Ping1 ","Ping2 "}; // just something to print to             indicate direction

void setup()
{
 Serial.begin(9600);
}

void loop()
{

 unsigned long ultrasoundValue;
 for(int i=0; i < 2; i++)
 {
   ultrasoundValue = ping(i);
   Serial.print(pingString[i]);
   Serial.print(ultrasoundValue);
   Serial.print("cm, ");    
   delay(500);

 }
} 

//Ping function
unsigned long ping(int i)
{
 unsigned long echo;

 pinMode(ultraSoundSignalPins[i], OUTPUT); // Switch signalpin to output
 pinMode(tx, OUTPUT);          
 digitalWrite(ultraSoundSignalPins[i], LOW); // Send low pulse
 digitalWrite(tx, LOW); 
 delayMicroseconds(2); // Wait for 2 microseconds
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Send high pulse
 digitalWrite(tx, HIGH);
 delayMicroseconds(5); // Wait for 5 microseconds
 digitalWrite(ultraSoundSignalPins[i], LOW); // Holdoff
 pinMode(ultraSoundSignalPins[i], INPUT); // Switch signalpin to input
 digitalWrite(ultraSoundSignalPins[i], HIGH); // Turn on 0pullup resistor
 echo = pulseIn(ultraSoundSignalPins[i], HIGH); //Listen for echo
 return (echo / 29.1); //convert to CM then to inches
}
0
0

Make ultrasoundValue an array and use i as the index to it? Just like you have with all your other arrays?

You obviously know how to use arrays, since you have already been using them throughout your code.

1

You don't even have to add any lines, just modify a couple!

unsigned long ultrasoundValue [2]; //creates an array of unsigned longs of size 2

...and inside your for loop:

ultrasoundValue[i] = ping(i);

It appears you are acquiring 2 separate ultrasound values. If you'd like to store multiple sets of these 2 values, you could use a two-dimensional array:

unsigned long ultrasoundValue [10][2]; //an array of 10 pairs of long unsigned values

...and you could modify your for loop to have a pair of nested for loops:

 for (int i = 0; i < 10; i++)
 {
   for (int j = 0; j < 2; j++)
   {
      ultrasoundValue[i][j] = ping(j);
      //do whatever else
   }
 } 

Not the answer you're looking for? Browse other questions tagged or ask your own question.