Hello, I've quite litteraly 0 notions in arduino but I need to do a school projet. basically I'm using multiple HC-SR04 so I wanted to create a function to initialise and use them all
int ultrason(int echoPin, int trigPin)
{
// defines variables
long duration;
int distance;
void setup()
{
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
Serial.begin(9600); // Starts the serial communication
}
void loop()
{
// 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;
// Prints the distance on the Serial Monitor
// Serial.print("Distance: ");
// Serial.println(distance);
return (distance);
}
}
this is the code I wrote, I took an exemple on google and changed it a bit. I keep having the error "a function-definition is not allowed here before '{' token".
int ultrason(int echoPin, int trigPin){
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
long duration;
int distance;
// 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;
// Prints the distance on the Serial Monitor
// Serial.print("Distance: ");
// Serial.println(distance);
return (distance);
}
got it working ! I assume when I was re-initialising the serial it was causing problems
An Arduino sketch always has a setup() (runs once) and loop() (runs forever) functions... but you can create your own functions... they should be called from either setup or loop.
This conclusion is completely wrong
void myFunction {
// function myFuncB is inside function myFunction
void myFuncB {
....} // end of function myFuncB
} // end of function myFunction
and this is what does not work
it has to be this way
void myFunction {
} // end of function myFunction
// function myFuncB is outside function myFunction
void myFuncB {
} // end of function myFuncB
Please look at the NewPing library for HC-SR04 ultrasonic.
It will make your code easier and tidier and it has a 3 sonic sensor code as an example.
The Library does most if the distance calcs for you.