#include <Servo.h>
// Create a Servo object
Servo myServo;
// Define pin numbers
const int potPin = A0; // Potentiometer connected to analog pin A0
const int servoPin = 5;
int led = 3;
int motor = 12;
int motor2 = 11;
const int buttonPin = 2;
int buttonState = 0;
const int trigPin = 9; // Trigger pin connected to digital pin 9
const int echoPin = 10; // Echo pin connected to digital pin 10
void setup() {
// put your setup code here, to run once:
pinMode(led,OUTPUT);
pinMode(motor, OUTPUT);
pinMode(motor2, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
myServo.attach(servoPin);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH) {
Serial.println("button was pressed");
digitalWrite(led, HIGH);
} else {
Serial.println("nothing is happening");
digitalWrite(led, LOW);
int potValue = analogRead(potPin);
// Map the potentiometer value to the servo angle range (0 to 180 degrees)
int angle = map(potValue, 0, 1023, 0, 180);
// Write the mapped angle to the servo
myServo.write(angle);
// Add a small delay to stabilize the movement
delay(15);
}
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the pulse on the echo pin
long duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters (speed of sound = 34300 cm/s)
int distance = duration * 0.034 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Add a short delay
delay(100);
}