Ultrasonic, 5V, Grd and Sig

I want to check my understanding on how to use digitalWrite for 5V and Grd and why this code isn't working.

This is for the Makeblock sensor

Consider the image here which says to plugin a wire to 5V, Grd and a signal pin.

My code does the following

#define h  22
#define l  24
#define sig 26

void setup() {
   Serial.begin(9600);
   pinModde(22, OUTPUT);
   pindMode(24, OUPUT);
   pinMode(sig, OUPUT);
   
   digitalWrite(h, HIGH);
   digitalWrite(l, LOW);
}

void loop() {
   digitalWrite(sig, LOW);
   delayMicroseconds(2);
   digitalWrite(sig, HIGH);
   delayMicroseconds(10);
   digitalWrite(sig, LOW);
   pinMode(sig, INPUT);
   long duration = pulseIn(sig, HIGH, 38000);
   delay(2500);
}

When I run this code duration is always 0. If I unplug 22 and 24 and use the board's 5V and Grd I get duration is 30001 no matter how far away an object is from the sensor. Meaning it's not sensing anything, just returning this number.

Fair disclosure that I'm using solder-less wires but I don't that would make this much of a difference?

So to summarize: why are 22 and 24 resulting in a 0 readout and not acting as 5V and Grd? My only thought is maybe too much voltage and a resister is needed?

Secondly: why is the sensor not working even when using 5V and Grd pins?

First of all, does it work with the example sketch and wiring in the Makeblock sensor link you posted? Why not check that, first? (Note that it says if you use Dupont wire, the header should be "welded" on the module :slight_smile: )

Next, your code will not compile due to typos (e.g., "pindMode" and "OUPUT").

Lastly, although you define sig to be an OUTPUT in setup(), you switch it to INPUT in loop(), and then never switch it back to OUTPUT. From the second loop on, your digitalWrites are just toggling the internal pullup on and off. So that your digitalWrites work as intended, add pinMode(sig,OUTPUT) at the beginning of loop.

PS: regarding your question... Yes, you should be able to power the sensor using digital pins held high and low, provided the sensor doesn't draw too much current (which seems unlikely, but the Makeblock sensor link you posted doesn't give that spec). But to eliminate variables, first get it working by connecting it directly to 5v and gnd. Then try the digital pins.