Fun way to learn arduino
Image Credit: http://slideplayer.com/slide/9744477
HC-SR04 Ultrasonic Sensor
Motors + Wheels
L239D Motor Driver
Arduino
Human | Robot |
---|---|
Eyes | Distance sensor |
Nuerons | Wires |
Brain | Arduino |
Leg | Motor Driver + Motors + Wheels |
#include <NewPing.h>
#define PING_PIN 12
#define PING_MAX_DISTANCE 200
NewPing sonar(PING_PIN, PING_PIN, PING_MAX_DISTANCE);
void setup() {
Serial.begin(9600);
}
void loop() {
delay(500);
unsigned int distanceInCms = sonar.ping() / US_ROUNDTRIP_CM;
Serial.println("Distance: " + String(distanceInCms) + "cm");
}
int motor_left[] = {2, 3};
int motor_right[] = {7, 8};
void setup() {
for(int i = 0; i < 2; i++){
pinMode(motor_left[i], OUTPUT);
pinMode(motor_right[i], OUTPUT);
}
}
void loop() {
delay(50);
drive_forward();
}
void drive_forward() {
digitalWrite(motor_left[0], HIGH);
digitalWrite(motor_left[1], LOW);
digitalWrite(motor_right[0], HIGH);
digitalWrite(motor_right[1], LOW);
}
void drive_backward() {
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], HIGH);
digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], HIGH);
}
void turn_left() {
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], HIGH);
digitalWrite(motor_right[0], HIGH);
digitalWrite(motor_right[1], LOW);
}
void turn_right() {
digitalWrite(motor_left[0], HIGH);
digitalWrite(motor_left[1], LOW);
digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], HIGH);
}
void motor_stop(){
digitalWrite(motor_left[0], LOW);
digitalWrite(motor_left[1], LOW);
digitalWrite(motor_right[0], LOW);
digitalWrite(motor_right[1], LOW);
}
// ..... Setup code omitted
void loop() {
delay(50);
unsigned int distanceInCms = sonar.ping() / US_ROUNDTRIP_CM;
if(distanceInCms != NO_ECHO && distanceInCms < MAX_DISTANCE_FROM_OBSTACLE_IN_CMS) {
rotate_right(90);
} else {
drive_forward();
}
}
void rotate_right(int angleInDegrees) {
for(int i=0; i< angleInDegrees; i++) {
turn_right();
delay(25);
}
}
// .... Full code can be found in gist mentioned below