So, after giving up for awhile I'm having another go at Arduino.
I am a beginner using the arduino motor shield.
My Problem:
I want to have a PING sensor on Pin 7 measure distance values, then set up a simple if/else statement to tell the DC motor to run if reading a value over 12 inches. Please be patient with me.
I have a parallax PING sensor and have tested the general PING code. I want to add in something like:
if (inches > 12) , I want the motor to go, so digitalWrite (DIR_A, HIGH) and digitalWrite (BRAKE_A, LOW) and the motor speed controlled by analogWrite (PWM_A, 255)
else (inches < 12), I want the motor to brake, so digitalWrite (DIR_A, LOW) and digitalWrite (BRAKE_A, HIGH)
However, I do not know where or exactly how to add this.
const int
pingPin = 7,
PWM_A = 3,
DIR_A = 12,
BRAKE_A = 9;
void setup()
{
pinMode(BRAKE_A, OUTPUT);
pinMode(DIR_A, OUTPUT);
Serial.begin(9600);
}
void loop () {
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// The same pin is used to read the signal from the PING))): a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(10);
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}