Here is a basic code for an obstacle avoiding robot using an Arduino board and Ultrasonic Sensors:
Python Code:
#define trigPin 13 #define echoPin 12 #define motor1Pin1 7 #define motor1Pin2 6 #define motor2Pin1 5 #define motor2Pin2 4 void setup() { pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(motor1Pin1, OUTPUT); pinMode(motor1Pin2, OUTPUT); pinMode(motor2Pin1, OUTPUT); pinMode(motor2Pin2, OUTPUT); } void loop() { long duration, distance; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/2) / 29.1; if (distance <= 15) { digitalWrite(motor1Pin1, LOW); digitalWrite(motor1Pin2, HIGH); digitalWrite(motor2Pin1, LOW); digitalWrite(motor2Pin2, HIGH); delay(1000); digitalWrite(motor1Pin1, HIGH); digitalWrite(motor1Pin2, LOW); digitalWrite(motor2Pin1, LOW); digitalWrite(motor2Pin2, HIGH); delay(1000); } else { digitalWrite(motor1Pin1, LOW); digitalWrite(motor1Pin2, HIGH); digitalWrite(motor2Pin1, HIGH); digitalWrite(motor2Pin2, LOW); } }
Hardware and electronic items required:
- Arduino board (e.g. Arduino Uno)
- Ultrasonic Sensors (e.g. HC-SR04)
- Motor Driver (e.g. L298N)
- Motors
- Jumper wires
- Power supply (e.g. 9V battery)
- Breadboard (optional, for prototyping)
To connect the components, follow these steps:
- Connect the VCC pin of the ultrasonic sensor to 5V power supply and GND pin to GND.
- Connect the Trig pin to digital pin 13 on the Arduino board.
- Connect the Echo pin to digital pin 12 on the Arduino board.
- Connect the IN1, IN2, IN3, and IN4 pins of the motor driver to digital pins 7, 6, 5, and 4 on the Arduino board, respectively.
- Connect the GND pin of the motor driver to GND.
- Connect the VCC pin of the motor driver to a 9V battery.
The circuit is now complete and ready to be powered on. The code will automatically detect any obstacle in front of the robot and will try to avoid it by changing its direction.
No comments:
Post a Comment