Ok it sounded like it wasn't working from your first post...
I am using a relay to switch the 9v circuit for the DC motor but the relay will not stay on constantly
Anyhoo....
You don't say what the metal detector tells you, but let's assume you can read it as a high or low on a digital pin. We'll assume it's active low, so you enable the pullup.
Below compiles but obviously not tested. If your detector is not active low, change the logic around in the "if"....
byte relayPin=2;
byte detectorPin=7;
bool metalDetected;
void setup() {
// put your setup code here, to run once:
pinMode(relayPin, OUTPUT);
//we'll assume the detector is active low and needs a pullup
//detector pin normally high, goes low when detects something
pinMode(detectorPin, INPUT_PULLUP);
}
void loop() {
// put your main code here, to run repeatedly:
metalDetected=digitalRead(detectorPin);
if (metalDetected==HIGH) //not detected, assuming active low
{
digitalWrite(relayPin, HIGH); //drive the car
}
else //it's LOW, metal is detected
{
digitalWrite(relayPin, LOW); //stop the car
}
}