Skip to content

Instantly share code, notes, and snippets.

@maxpromer
Created May 18, 2025 17:41
Show Gist options
  • Save maxpromer/892586f96df3eb33413071e7e02ad7ae to your computer and use it in GitHub Desktop.
Save maxpromer/892586f96df3eb33413071e7e02ad7ae to your computer and use it in GitHub Desktop.
//Parameters
const int gp2y0a21Pin = A0;
//Variables
int gp2y0a21Val = 0;
void setup() {
//Init Serial USB
Serial.begin(9600);
Serial.println(F("Initialize System"));
//Init ditance ir
pinMode(gp2y0a21Pin, INPUT);
}
void loop() {
testGP2Y0A21();
}
void testGP2Y0A21( ) { /* function testGP2Y0A21 */
////Read distance sensor
gp2y0a21Val = analogRead(gp2y0a21Pin);
Serial.print(gp2y0a21Val); Serial.print(F(" - ")); Serial.println(distRawToPhys(gp2y0a21Val));
if (gp2y0a21Val < 200) {
Serial.println(F("Obstacle detected"));
} else {
Serial.println(F("No obstacle"));
}
}
int distRawToPhys(int raw) { /* function distRawToPhys */
////IR Distance sensor conversion rule
float Vout = float(raw) * 0.0048828125; // Conversion analog to voltage
int phys = 13 * pow(Vout, -1); // Conversion volt to distance
return phys;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment