3:33 AM
1

Robot tránh vật cản dùng cảm ứng siêu âm HC-SR04



Chuẩn bị:
1. Vỉ mạch cầu H,
2. Arduino,
3. Khung xe có 2 moto
4. Nguồn, nên có 2 nguồn để tránh sụt áp
5. Cảm ứng khoảng cách
6. Dây, giắc kết nối

Code nạp

*/
#define ENA 1  //enable A on pin 5 (needs to be a pwm pin)
#define IN1 4  //IN1 on pin 2 conrtols one side of bridge A
#define IN2 5  //IN2 on pin 4 controls other side of A
#define ENB 2  //enable B on pin 8 (needs to be a pwm pin)
#define IN3 6  //IN3 on pin 9 conrtols one side of bridge A
#define IN4 7  //IN4 on pin 10 controls other side of A
#define trigPin 13
#define echoPin 12

void setup()
{
  //set all of the outputs
   Serial.begin(9600);
  pinMode(ENA, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(ENB, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  }
void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); - Removed this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance < 20) {  // This is where the LED On/Off happens

 
  //Dừng lại
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  analogWrite(ENA, 255);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(ENB, 255);
  delay(500);
   //LÙI LAI
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  analogWrite(ENA, 130);
   digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  analogWrite(ENB, 130);
  delay(200);
    //QUAY ĐẦU
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  analogWrite(ENA, 30);
   digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  analogWrite(ENB, 130);
  delay(500);
  //tắt
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  analogWrite(ENA, 255);
   digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(ENB, 255);
  delay(1000);
  }
 else
 {
//Đi thẳng
   digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  analogWrite(ENA, 200);
   digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  analogWrite(ENB, 200);
   
  }
 
}

1 comments:

 

Lập trình

-

Arduino Hải Phòng

,