You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.0 KiB
63 lines
1.0 KiB
4 years ago
|
|
||
|
|
||
|
#define TRIG 4
|
||
|
#define ECHO 5
|
||
|
#define MOTOR 9
|
||
|
#define SPEED A0
|
||
|
|
||
|
#define TRIG_DIST 150 // Min trigger distance (cm)
|
||
|
#define MOTOR_TIME 5000 // Motor rotation time
|
||
|
|
||
|
long duration, cm, old, mspeed;
|
||
|
|
||
|
void setup() {
|
||
|
Serial.begin(9600);
|
||
|
pinMode(TRIG, OUTPUT);
|
||
|
pinMode(ECHO, INPUT);
|
||
|
pinMode(MOTOR, OUTPUT);
|
||
|
|
||
|
mspeed = map(analogRead(SPEED), 0, 1024, 0, 255);
|
||
|
}
|
||
|
|
||
|
void loop() {
|
||
|
|
||
|
mspeed = map(analogRead(SPEED), 0, 1024, 0, 255);
|
||
|
|
||
|
digitalWrite(TRIG, LOW);
|
||
|
delayMicroseconds(2);
|
||
|
digitalWrite(TRIG, HIGH);
|
||
|
delayMicroseconds(10);
|
||
|
digitalWrite(TRIG, LOW);
|
||
|
duration = pulseIn(ECHO, HIGH);
|
||
|
cm = duration / 58;
|
||
|
|
||
|
Serial.println(cm);
|
||
|
|
||
|
if(cm <= TRIG_DIST) {
|
||
|
|
||
|
if(old > TRIG_DIST) {
|
||
|
for(int i=0; i<mspeed; i++) {
|
||
|
analogWrite(MOTOR, i);
|
||
|
delay(30);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
analogWrite(MOTOR, mspeed);
|
||
|
delay(MOTOR_TIME);
|
||
|
|
||
|
} else {
|
||
|
|
||
|
|
||
|
if(old <= TRIG_DIST) {
|
||
|
for(int i=mspeed; i>0; i--) {
|
||
|
analogWrite(MOTOR, i);
|
||
|
delay(20);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
analogWrite(MOTOR, 0);
|
||
|
}
|
||
|
|
||
|
old = cm;
|
||
|
}
|