Created
December 5, 2014 05:33
-
-
Save goFrendiAsgard/56b4b5afab9ad2832932 to your computer and use it in GitHub Desktop.
Arduino Sonar Sensor & LED
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Gunvarrel v 0.0.2 | |
* Purpose: To emulate simple sonar robot | |
* Description: Far from perfect. I use LED instead of motor | |
* Author: Go Frendi Gunawan | |
*/ | |
int left_motor = 12; // left motor | |
int right_motor = 13; // right motor | |
int sonar_trig = 8; // sonar trigger | |
int sonar_echo = 7; // sonar echo | |
void setup(){ | |
Serial.begin(9600); | |
pinMode(left_motor, OUTPUT); | |
pinMode(right_motor, OUTPUT); | |
pinMode(sonar_trig, OUTPUT); | |
pinMode(sonar_echo, INPUT ); | |
} | |
void straight(){ | |
digitalWrite(left_motor, HIGH); | |
digitalWrite(right_motor, HIGH); | |
delay(100); | |
} | |
void turn(){ | |
digitalWrite(left_motor, LOW); | |
digitalWrite(right_motor, HIGH); | |
delay(100); | |
} | |
void loop(){ | |
// shout out | |
digitalWrite(sonar_trig, LOW); | |
digitalWrite(sonar_trig, HIGH); | |
delayMicroseconds(20); | |
digitalWrite(sonar_trig, LOW); | |
// listen | |
int duration = pulseIn(sonar_echo, HIGH); | |
int distance = (duration/2) / 29.1; | |
Serial.println(distance); | |
if(distance < 20){ | |
turn(); | |
}else{ | |
straight(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment