if PIN is HIGH then execute one time until LOW and loop

Hello Guys,

Just started learning Arduino and did some amazing personal projects. but now I am a bit trouble by a simple project which is giving me errors.

1.) I am trying to make my own encoder disc to measure a distance when a pin is high.
2.) The encoder disc I used has 90 degree slots which will measure every 90 degree using a photo electric sensor.
3.) I encountered when my motor is not turning and a pin is high, the Arduino is still measuring.
4.) Motor is variable speed so i cannot use delays.

ninetydegree = digitalRead(7);

if (ninetydegree == HIGH) {
distanceSensor.startRanging();
while (!distanceSensor.checkForDataReady());
int distance = distanceSensor.getDistance();
distanceSensor.clearInterrupt();
distanceSensor.stopRanging();
Serial.println(distance);
}

I need to make one time measurement when pin(7) gets high. but my code just throws lots of data into serial even when my motor is not moving and pin(7) is high.

Could you guys help me with that? I hope I have explained my problem clearly.

Please follow the forum rules.

Show us a good schematic of your circuit.
Show us a good image of your ‘actual’ wiring.
Give links to components. Posting images:
https://forum.arduino.cc/index.php?topic=519037.0

Use CTRL T to format your code.
Attach your ‘complete’ sketch between code tags
[code]Paste your sketch here[/code]

Avoid while() since it can result in blocking code.

. . and, course, this could be true even if nothing is moving:

if (ninetydegree == HIGH) { . . .

You should probably look for a change of state, say the last reading was LOW and the current reading is HIGH, then act on that.

But you should post your entire sketch.

Thank you for noticing my post larryd. its a bit messy on a breadboard (rats nest). I am using a VL53L1x (I2C), H-Bridge for the motor(12V), a photoelectric sensor (below photo) on an Arduino Nano.

1 out of 6

Sorry evanmars, i dont get what you mean. i checked pinout of photo electric sensor and once its blocked the output goes low.
@6v6gt, doing it right now.

larryd asked for 6 things. You gave him one.
Actually not even that.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.