Created
February 16, 2017 11:07
-
-
Save ptigas/3f6e7dcbc7c367a2190b6395e9a9ac23 to your computer and use it in GitHub Desktop.
workshop car
This file contains hidden or 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
// connect the distance sensor | |
#define trigPin 13 | |
#define echoPin 12 | |
// connect motor controller pins to Arduino digital pins | |
// motor one | |
int enA = 3; | |
int in1 = 4; | |
int in2 = 5; | |
// motor two | |
int in3 = 6; | |
int in4 = 7; | |
int enB = 9; | |
void setup() { | |
Serial.begin(9600); | |
pinMode(trigPin, OUTPUT); | |
pinMode(echoPin, INPUT); | |
// set all the motor control pins to outputs | |
pinMode(enA, OUTPUT); | |
pinMode(enB, OUTPUT); | |
pinMode(in1, OUTPUT); | |
pinMode(in2, OUTPUT); | |
pinMode(in3, OUTPUT); | |
pinMode(in4, OUTPUT); | |
} | |
void loop() { | |
if (getDistance() > 30) { | |
moveForward(); | |
} else { | |
turnUntilSafeDistanceAhead(); | |
} | |
} | |
long getDistance() { | |
long duration, distance; | |
digitalWrite(trigPin, LOW); // Added this line | |
delayMicroseconds(2); // Added this line | |
digitalWrite(trigPin, HIGH); | |
delayMicroseconds(10); // Added this line | |
digitalWrite(trigPin, LOW); | |
duration = pulseIn(echoPin, HIGH); | |
distance = (duration/2) / 29.1; | |
Serial.println(distance); | |
return distance; | |
} | |
void turnUntilSafeDistanceAhead() { | |
// move a bit forward and ask distance. | |
digitalWrite(in1, HIGH); | |
digitalWrite(in2, LOW); | |
// set speed to 200 out of possible range 0~255 | |
analogWrite(enA, 255); | |
// turn on motor B | |
digitalWrite(in3, HIGH); | |
digitalWrite(in4, LOW); | |
// set speed to 200 out of possible range 0~255 | |
analogWrite(enB, 255); | |
} | |
void moveForward() { | |
// move a bit forward and ask distance. | |
digitalWrite(in1, HIGH); | |
digitalWrite(in2, LOW); | |
// set speed to 200 out of possible range 0~255 | |
analogWrite(enA, 255); | |
// turn on motor B | |
digitalWrite(in3, LOW); | |
digitalWrite(in4, HIGH); | |
// set speed to 200 out of possible range 0~255 | |
analogWrite(enB, 255); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment