Hi,
I am trying to work out the code to make a motor spin a single full turn when a body is sensed at a preset distance. I have managed to get the motor to trigger once when the body is sensed and not again until the body exits the ultrasonic field and re enters it again. Now I am trying to add in a reed switch that will tell the motor to stop once 1 full rotation has been completed. Obviously the reed switch will be 'high' when the motor is just waiting to turn also.... I'm new to programming and this has really stumped me so any help would be really appreciated! Here is my code so far:
#define trigPin 13
#define echoPin 12
#define motor 9
#define reed 5
int lasttrigger = false;
int trigger;
int trip;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(motor, OUTPUT);
pinMode(reed, INPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (reed == HIGH) {trip = true;}
else {trip = false;}
if (distance < 30) {trigger = true;}
else {trigger = false;}
if (trigger != lasttrigger && trigger == true){digitalWrite(motor, HIGH);}
else {digitalWrite(motor, LOW);}
lasttrigger = trigger;
if (distance >= 30){Serial.println("Out of range");}
else {
Serial.print(distance);
Serial.println(" cm");}
delay(300);
}