Created
January 3, 2026 09:57
-
-
Save pprishchepa/679ad58a168627ca5e49893254b830bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <Servo.h> | |
| static const uint8_t SERVO_PIN = 9; | |
| static const uint8_t TRIG_PIN = 10; | |
| static const uint8_t ECHO_PIN = 11; | |
| Servo s; | |
| long readDistanceCm() { | |
| // Trigger pulse | |
| digitalWrite(TRIG_PIN, LOW); | |
| delayMicroseconds(2); | |
| digitalWrite(TRIG_PIN, HIGH); | |
| delayMicroseconds(10); | |
| digitalWrite(TRIG_PIN, LOW); | |
| // Echo pulse width (timeout ~ 25 ms => ~4m max) | |
| unsigned long us = pulseIn(ECHO_PIN, HIGH, 25000UL); | |
| if (us == 0) return -1; // timeout / no echo | |
| // Sound speed: 343 m/s => 29.1 us per cm round-trip is 58.2 us per cm | |
| long cm = (long)(us / 58UL); | |
| return cm; | |
| } | |
| void setup() { | |
| Serial.begin(115200); | |
| pinMode(TRIG_PIN, OUTPUT); | |
| pinMode(ECHO_PIN, INPUT); | |
| s.attach(SERVO_PIN); | |
| s.write(90); | |
| delay(400); | |
| } | |
| void loop() { | |
| // sweep 20 -> 160 | |
| for (int angle = 20; angle <= 160; angle += 10) { | |
| s.write(angle); | |
| delay(180); // give servo time to move | |
| long cm = readDistanceCm(); | |
| Serial.print("angle="); | |
| Serial.print(angle); | |
| Serial.print(" cm="); | |
| Serial.println(cm); | |
| delay(60); | |
| } | |
| // sweep back 160 -> 20 | |
| for (int angle = 160; angle >= 20; angle -= 10) { | |
| s.write(angle); | |
| delay(180); | |
| long cm = readDistanceCm(); | |
| Serial.print("angle="); | |
| Serial.print(angle); | |
| Serial.print(" cm="); | |
| Serial.println(cm); | |
| delay(60); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment