Lesson 25/31: Car-3 Smart Car Avoids Obstacle Using Infrared Sensors
Lesson 25: Car-3 Smart Car Avoids Obstacle Using Infrared Sensors | SunFounder Robojax
In this lesson we learn how to use Infrared Obstacle Avoidance with SunFounder Smart Card which is part of the Arduino Kit from SunFounder.
First code is explained, wiring shown and then code is demonstrated so we know when objects is located in front of the car, the IR sensor on the right or left will detect it and the car is moved to the opposite direction. Then the code is modified to add stop and finally the project is demonstrated.
Topics in this lesson
Use Chapters from timeline or click on the time
- 00:00 Introduction
- 1:23 Introduction to IR obstacle Avoidance
- 3:45 Wiring explained
- 5:39 Code explained
- 9:09 Code demonstration
- 10:27 Stop the car Added
- 11:40 StopTheCar code demonstration
- 12:12 Smtar Car Infrared Obstacle Avoidance Demonstration
/*
Watch video instruction for this code on YouTube https://youtu.be/XEObTOE8JM8
Resource page for this lesson and code:
http://robojax.com/course2/lecture25
Tutoril by Robojax.com
*/
const int in1 = 5;
const int in2 = 6;
const int in3 = 9;
const int in4 = 10;
const int rightIR = 7;
const int leftIR = 8;
void setup() {
Serial.begin(9600);
//motor
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
//IR obstacle
pinMode(leftIR, INPUT);
pinMode(rightIR, INPUT);
}
void loop() {
int left = digitalRead(leftIR); // 0: Obstructed 1: Empty
int right = digitalRead(rightIR);
int speed = 150;
if (!left && right) {
backLeft(speed);
} else if (left && !right) {
backRight(speed);
} else if (!left && !right) {
moveBackward(speed);
} else {
moveForward(speed);
}
}
void moveForward(int speed) {
analogWrite(in1, 0);
analogWrite(in2, speed);
analogWrite(in3, speed);
analogWrite(in4, 0);
}
void moveBackward(int speed) {
analogWrite(in1, speed);
analogWrite(in2, 0);
analogWrite(in3, 0);
analogWrite(in4, speed);
}
void backLeft(int speed) {
analogWrite(in1, speed);
analogWrite(in2, 0);
analogWrite(in3, 0);
analogWrite(in4, 0);
}
void backRight(int speed) {
analogWrite(in1, 0);
analogWrite(in2, 0);
analogWrite(in3, 0);
analogWrite(in4, speed);
}