Skip to content

Instantly share code, notes, and snippets.

@suadanwar
Created August 1, 2019 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suadanwar/fa3408c5ae1b3e8610a4b38417a2e59f to your computer and use it in GitHub Desktop.
Save suadanwar/fa3408c5ae1b3e8610a4b38417a2e59f to your computer and use it in GitHub Desktop.
This sample code is for Control Servo and Display Sensor's Reading with the GUI on Arduino's Tutorial. [Arduino]
#include <Servo.h> // Include the Servo library
int servoPin = 3;
const int trigPin = 9;
const int echoPin = 10;
Servo myServo; // Create a servo object
int val = 0;
long duration;
int distance;
void setup() {
myServo.attach(servoPin);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); //start serial
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
distance = duration * 0.017; // Calculating the distance
Serial.println(distance);
if (Serial.available()) { //Check data
int val = Serial.read();
myServo.write(val);
delay(15);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment