- #define trig 9
- #define echo 10
- #define motor1 5
- #define motor2 6
- int speed = 0;
- int ultra(int trg, int ech){
- while(1){
- digitalWrite(trg, LOW);
- delayMicroseconds(2);
- digitalWrite(trg, HIGH);
- delayMicroseconds(10);
- digitalWrite(trg, LOW);+
- int duration = pulseIn(ech,HIGH,5000);
- int distance = duration * 0.034/2;
- if(distance != 0){
- return distance;}
- }
- }
- void setup() {
- pinMode(trig,OUTPUT);
- pinMode(echo,INPUT);
- pinMode(motor1, OUTPUT);
- pinMode(motor2, OUTPUT);
- Serial.begin(9600);
- }
- void loop() {
- int a = ultra(trig,echo);
- Serial.println(a);
- if (a > 40){
- analogWrite(motor1, 255);
- digitalWrite(motor2, LOW);
- int a = ultra(trig,echo);
- }
- else if (a > 35 and a < 40){
- analogWrite(motor1, 125);
- analogWrite(motor2, 0);
- int a = ultra(trig,echo);
- }
- else if (a > 30 and a < 35){
- analogWrite(motor1, 63);
- analogWrite(motor2, 0);
- int a = ultra(trig,echo);
- }
- else if (a < 30 and a > 20){
- digitalWrite(motor1, 0);
- analogWrite(motor2, 0);
- int a = ultra(trig,echo);
- }
- else if (a < 20){
- digitalWrite(motor1, 0);
- digitalWrite(motor2, 1);
- }
- }
Recent Pastes