I am brand new to C++ and am working with the Arduino micro controller. The project I've been working on for my university requires me to write code to do the following:
If the ultrasonic sensor detects a distance within a certain range, output HIGH to activate an electric motor
If the sensor detects distance outside this range, outputs LOW to deactivate the motor
I hope to create an array that will average the readings from the ultrasonic sensor over a .5 sec - 1 second interval and then output that average.
I started with a rangefinder script that went along with a tutorial provided on Arduino's website, so my goal is to modify that script to fit into my goals to output HIGH or LOW based on the code that I've tested and already works well to test for distance.
I am looking for any tips to create an array to average the distance from the sensor, then using a for
loop to test whether it is in the interval and output HIGH or LOW.
Any help and direction would be appreciated!
const int TriggerPin = 8; //sensor trigger pin const int EchoPin = 9; //sensor echo pin const int MotorPin = 7; //motor out pin long Duration = 0; void setup(){ pinMode(TriggerPin,OUTPUT); //sets trigger as output pinMode(EchoPin,INPUT); //sets echo as input pinMode(MotorPin,OUTPUT); //sets motor as output Serial.begin(9600); //displays to serial monitor } void loop(){ digitalWrite(TriggerPin,LOW); //trigger pin to 0V delayMicroseconds(2); //waits 2 us digitalWrite(TriggerPin,HIGH); //trigger pin to 5V delayMicroseconds(10); //10 us delay to recieve ping digitalWrite(TriggerPin,LOW); Duration = pulseIn(EchoPin,HIGH); //waits for echo pin to get high //pulseIn returns the Duration in microseconds long Distance_mm = Distance(Duration); //uses function to calc. distance delay(100); //delay half second, do next measurement } long Distance(long time); { long DistanceCalc; //calculation variable DistanceCalc = ((time /2.9) / 2); //want to average this DistanceCalc reading over 10 readings, then use this value to compare to the desired range void loop(){ if (dist_avg < 600 && dist_avg > 400); digitalWrite(MotorPin,HIGH); else digitalWrite(MotorPin,LOW); } //if average distance is within .4-.6 meter range, output HIGH; turns motor on //if avergae distance is outside .4-.6 meter range, outut LOW; turns motor off
HIGH
andLOW
defined? With the way they're named, I assume they're macros.\$\endgroup\$