Hello everyone.
I'm working on a project for a class of mine and it involves Arduino. I'm having a little difficulty writing some code and was hoping someone could help me.
The project is a distance sensor. I have a Ultrasonic sensor attached to a servo motor. Right now when I press a button, the servo pans around and the ultrasonic reads distance from objects. The distance is displayed on an LCD screen.
Here's what I'm trying to do next. After the motor pans arounds, I want the system to display the the shortest distance the sensor read while it was panning. Here's a copy of my code so far.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int pingPin = 7;
#include <Servo.h>
Servo myservo;
int pos = 0;
const int scanButton = 9;
int buttonState = 0;
void setup()
{
Serial.begin(9600);
pinMode(scanButton, INPUT);
myservo.attach( 8 );
}
void loop()
{
buttonState=digitalRead(scanButton);
if (buttonState==HIGH)
{
delay(1500);
for(pos = 0; pos < 100; pos +=1)
{
myservo.write(pos);
delay(34);
long duration, inches;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = microsecondsToInches(duration);
lcd.begin(16, 2);
lcd.print("Dist: ");
lcd.print(inches);
lcd.print(" in");
}
delay(2500);
for(pos = 100; pos>=1; pos -=1)
{
myservo.write(pos);
delay(35);
long duration, inches;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = (microsecondsToInches(duration));
lcd.begin(16, 2);
lcd.print("Dist: ");
lcd.print(inches);
lcd.print(" in");
}
}
else
{
myservo.write(pos);
}
}
long microsecondsToFeet(long microseconds)
{
return microseconds / 876 / 2;
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
Any help would be great! Thank you!
Moderator edit:
</mark> <mark>[code]</mark> <mark>
</mark> <mark>[/code]</mark> <mark>
tags added.