12:22 AM
0

Robot tránh vật cản dùng L298N và công tắc hành trình



Chuẩn bị:
1. Vỉ mạch cầu H,
2. arduino,
3. Khung xe có 2 moto
4. Nguồn,
5. Công tắc hành trình

Code nap:

*/
#define ENA 3  //enable A on pin 5 (needs to be a pwm pin)
#define IN1 7  //IN1 on pin 2 conrtols one side of bridge A
#define IN2 4  //IN2 on pin 4 controls other side of A
#define ENB 8  //enable B on pin 8 (needs to be a pwm pin)
#define IN3 9  //IN3 on pin 9 conrtols one side of bridge A
#define IN4 10  //IN4 on pin 10 controls other side of A
#define chanphat 5
#define chanthu 6
int thoigian,khoangcach;
int mode;
int percent;
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(chanphat, OUTPUT);
  pinMode(chanthu, INPUT);
}

void loop(){
digitalWrite(chanphat,HIGH);
delayMicroseconds(100);
digitalWrite(chanphat,LOW);
thoigian=pulseIn(chanthu,HIGH);
khoangcach=0.0344*(thoigian/2);
Serial.print(khoangcach);
Serial.println("cm");
if(khoangcach<30)
{
  //Dừng lại
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  analogWrite(ENA, 255);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(ENB, 255);
  delay(500);
  //Chay lui phan nua van toc
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  analogWrite(ENA, 100);
   digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(ENB, 255);
  delay(1000);
  //tắt
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  analogWrite(ENA, 255);
   digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(ENB, 255);
  delay(1000);
  }
 else
 {
   digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  analogWrite(ENA, 80);
   digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  analogWrite(ENB, 255);
  }
}

0 comments:

Post a Comment

 

Lập trình

-

Arduino Hải Phòng

,