Hello Arduino World,
First i will give you an overview of the components i am using and what the goal will be (for now :D)
-arduino UNO
-HC-SR04 Ultrasonic distance sensor
-small DC motor (provided in ultimate starter kit)
-push button
Right now i have the program sending "pings" out every 29ms from the sensor, and the motor turned on (all of this will only happen after i push the push button). if the sensor reads a distance value "threshold" of 4cm or less, it shuts off the motor (and by having the push button in there, the motor wont turn back on if the object in front of the sensor moves away). The only problem i am seeing is that every once in a while the sensor picks up a zero reading and shuts off the motor, so i was thinking that i would like a code that would count the "ping" values, and if 3 readings in a row are under the "threshold" then the motor would shut off. this should avoid the "blooper" readings popping up every once in a while. Here is the code as it sits right now, please dont be mad, there is no attempt thus far for the counting section, i could not find any threads that were aimed at what was doing, and since this is my second day with my arduino, i didnt have a starting point.
#include <NewPing.h>
#define TRIGGER_PIN 11 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 12 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define buttonPin 2 // Pushbutton to activate circuit on/off
#define motorPin 9 // DC Motor output
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
int threshold = 4; // Distance with sensor tells motor to shut off
int motorSpeed = 120; // Go between 0 (stopped) and 255 (full speed)
int offSpeed = 0; // Motor off
void setup() {
pinMode(motorPin, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results.
}
void loop() {
int buttonState;
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) // if button is depressed
{
delay(29); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
Serial.print("Ping: ");
Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
Serial.println("cm");
if (uS / US_ROUNDTRIP_CM > threshold) {
analogWrite(motorPin, motorSpeed);
}
else {
analogWrite(motorPin, offSpeed);
}
}
}
Thank you in advance for your help, please let me know if i was unclear or more info is needed.