How do I add button resetting angel of Ultrasonic Sensor here is my code hope you add code for button thanks!
// C++ code
//
#include <Servo.h>
#define trigPin 3
#define echoPin 2
Servo servo;
int sound = 250;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
servo.attach(4);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance < 100) {
Serial.println("the distance is more than 100");
servo.write(100);
}
else {
servo.write(0);
}
if (distance < 0 || distance <= 0){
Serial.println("The distance is less than 0");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
here is I'm trying to fix
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
int button = 8;
int trigpin = 11;
int echopin = 10;
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(button, INPUT);
pinMode(trigpin, OUTPUT);
Serial.begin(9600);
pinMode(echopin, INPUT);
}
void loop() {
long x, inches;
int buttonstate = digitalRead(button);
while(buttonstate == 1){
inches = microsecondsToInches(x);
delay(1000);
Serial.print("Inches = ");
Serial.println(inches);
if(inches > 18 && inches < 120){
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15 ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15 ms for the servo to reach the position
}
}
else {
digitalWrite (pos, LOW);
}
}//whileclose
}//coidclose
double microsecondsToInches(long duration){
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin, HIGH);
return duration /74/2;
}