Some ultrasonic sensors (such as Seeed) combine the trigger pin and the echo pin. At present the code generated by Ardublock initializes both pins at the top of the subroutine so if both trigger and echo are set to the same pin the routine fails to work.
If the pinMode statement for the echo pin is moved to just before the pulseIn then the code works with both types of sensor.
int duration;
pinMode(trigPin, OUTPUT);
// pinMode(echoPin, INPUT); // move this line from here
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(20);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT); // <---- to here
duration = pulseIn(echoPin, HIGH);
duration = duration / 59;
return duration;
Some ultrasonic sensors (such as Seeed) combine the trigger pin and the echo pin. At present the code generated by Ardublock initializes both pins at the top of the subroutine so if both trigger and echo are set to the same pin the routine fails to work. If the pinMode statement for the echo pin is moved to just before the pulseIn then the code works with both types of sensor.
int duration; pinMode(trigPin, OUTPUT); // pinMode(echoPin, INPUT); // move this line from here digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(20); digitalWrite(trigPin, LOW); pinMode(echoPin, INPUT); // <---- to here duration = pulseIn(echoPin, HIGH); duration = duration / 59; return duration;