I need help with coding a program based on ultrasound sensor

Hello everyone. don't judge me i'm a beginner in c programming.
So the project I'm working on is based on an ultrasound sensor attached to machine that calculate the distance between it and the wall behind, and based on the results if the distance is less than 15 cm i need it to cut the machine to not work ( Arduino output 0V) other than that, the machine should be powered on. So i have came up with this code and haven't tested it yet, and i need to know if it's logical and if it can work as it supposed to.
Thanks.
' ' '

<
#define echoPin 6
#define trigPin 7
#define autoclavePin 13
long duration;
int distance;

void setup(){
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(autoclavePin, OUTPUT);
Serial.begin(9600);
}
void loop(){
USsub();
if (distance < 15 ){
digitalWrite(autoclavePin, LOW);
}
else{
digitalWrite(autoclavePin, HIGH);
}
Serial.print(distance);
}
int USsub(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0,034/2 ;
return distance;
}

' ' '

Does it compile without errors?

Logic is reasonable.

Do you really need to check the distance at loop( ) speed, perhaps every 100 to 500ms is fast enough. :thinking:

Maybe print the distance only when it changes by a certain amount.

Should that comma not be a dot?

void loop(){
USsub();
if (distance < 15 ){
digitalWrite(autoclavePin, LOW);
}

Code is a lot better to deal with when its in code tags.

Why does the function USsub() return an int when the returned values is not used?

voide USsub(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0,034/2 ;
}

The OP may decide that running the ultrasonic thingy at loop() speed causes too many errors with the ultrasonics needing up to 60ms to fade away. By just running at loop() speed there may be residual ultrasonic waves.

unsigned long SpeedOfUntraSonicThingy = 600;
unsigned long pastTime = millis();

voiding loopy()
{
if( (millis()-pastTime) >= SpeedOfUltraSonicThingy )
{
USsub();
pastTime=millis();
}


}

Might be of interest to the OP or not.

So test it, usually that's the next step.

Yes it does compile without any errors.

Good first step. Now add serial.Print() statements so you can follow the logic and debug the program when you detect errors.

Interesting idea, i will try it. Thanks for the suggestion.

I don't have the components yet, i will try the simulation tomorrow.

Thanks for the suggestion. That was my first shot at writing the code, will sure try that.