new_thea/Embedded/pallet_sensor/pallet_sensor.ino
2021-09-21 12:41:06 +01:00

40 lines
919 B
C++

const int trig_pin = 14;
const int echo_pin = 15;
long duration_1;
int distance_1;
void setup() {
pinMode(trig_pin, OUTPUT); // Sets the trigPin as an Output
pinMode(echo_pin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void pulse_pin(int trig_pin) {
digitalWrite(trig_pin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trig_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trig_pin, LOW);
}
int get_distance(int trig_pin, int echo_pin){
pulse_pin(trig_pin);
long duration = pulseIn(echo_pin, HIGH, 50000);
if (duration == 0) duration = 50000;
// Serial.println(duration);
long distance = duration*0.034/2;
return distance;
}
void loop() {
distance_1 = get_distance(trig_pin, echo_pin);
Serial.print(" | ");
Serial.print(distance_1);
Serial.println(" | ");
delay(1);
}