The code.
Here you can see the code we made to control the parts.
The sensor.
The sensor sends a pulse of sound every 12 microseconds and measures how long it takes to come back. And using the formula (duration X 0,0343)/2 you can get the distance in centimeters. You can see the code below.
const int trigPin = 12;
const int echoPin = 8;
float duration;
float distance;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicrosecond(2);
digitalWrite(trigPin, HIGH);
delayMicrosecond(10);
digitalWrite(trigPin, Low);
duration = pulseIn(echoPin, HIGH);
distance = (duration*0,0343)/2;
Serial.print("Afstand: ");
Serial.println(distance);
delay(100);
}
The motors.
The motor stops for 10 seconds, spins in one direction for 10 seconds then spins in the other direction for 10 seconds and repears the loop. You can see the code below.
//Setup Motor Pins
#define in1 2
#define in2 4
#define ENA 5
void setup() {
Serial.begin(9600);
//set the pins for output
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(ENA, OUTPUT);
//set the pins to low - this wil keep the motor from moving.
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(ENA, LOW);
}
void loop() {
//stop the motor
digitalWrite(ENA, LOW);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
//waits 10 seconds
delay(10000);
//spin the motor in one direction
digitalWrite(ENA, HIGH);
digitalWrite(in1, HIGH);
digitalWrite(in2, HIGH);
//waits 10 seconds
delay(10000);
//spin motor in the other direction
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
//waits 10 seconds
delay(10000);
}