Random turn

This commit is contained in:
Denis Zheleztsov 2018-11-21 16:13:53 +03:00
parent 0e3064ac3d
commit 6a43957bd6
Signed by: Difrex
GPG Key ID: B047A0E62A285621

64
car.ino
View File

@ -1,5 +1,8 @@
#include <hcsr04.h>
/* constans */
/* ******** */
/* Define your pins here */
/* Wheels */
const int left_wheel_1 = 0;
@ -11,36 +14,33 @@ const int right_wheel_2 = 3;
const int sensor_echo = 9;
const int sensor_trigger = 10;
/* Other constans */
const int move_delay = 500;
const int turn_delay = 500;
/* disconnected pin for random seed */
const int analog_disconnected = 0;
/* Initialize sensor class */
HCSR04 hcsr04(sensor_trigger, sensor_echo, 20, 4000);
/* Array bellow contains all the wheels */
int wheels[] = {left_wheel_1, left_wheel_2, right_wheel_1, right_wheel_2};
/* The counter */
int i;
int mm;
/* Ultrasonic sensor variables */
long duration;
int distance;
void setup() {
/* Setup pins */
/* wheels */
for (i = 0; i < sizeof(wheels) - 1; i++) {
for (int i = 0; i < sizeof(wheels) - 1; i++) {
pinMode(wheels[i], OUTPUT);
}
/* Ultrasonic sensor */
pinMode(sensor_echo, INPUT);
pinMode(sensor_trigger, OUTPUT);
/* Starts serial communication */
Serial.begin(9600);
Serial.println("Bot is ready");
}
/* Wheel actions */
/* ************* */
/* Forward */
void move_forward_wheel_left() {
@ -56,6 +56,7 @@ void move_forward_wheel_right() {
void move_forward() {
move_forward_wheel_left();
move_forward_wheel_right();
delay(move_delay);
}
/* Backward */
@ -72,11 +73,12 @@ void move_backward_wheel_right() {
void move_backward() {
move_backward_wheel_left();
move_backward_wheel_right();
delay(move_delay);
}
/* Stops */
void stop_all() {
for (i = 0; sizeof(wheels) - 1; i++) {
for (int i = 0; sizeof(wheels) - 1; i++) {
digitalWrite(wheels[i], LOW);
}
}
@ -104,11 +106,22 @@ void turn_right(int delayMS) {
delay(delayMS);
}
void turn_left_or_right(int delayMS) {
randomSeed(analogRead(analog_disconnected));
int rand_number = random(1, 99);
if (rand_number > 50) {
turn_right(delayMS);
} else {
turn_left(delayMS);
}
}
/* Ultrasonic sensor actions */
/* ************************* */
/* get_distance -- returns distance to an object in centimeters */
int get_distance() {
mm = hcsr04.distanceInMillimeters();
int mm = hcsr04.distanceInMillimeters();
if (mm > 0) {
return mm / 10;
}
@ -116,14 +129,25 @@ int get_distance() {
}
/* Main code */
/* ********* */
/* The idea:
If robot see an object in distance less than 25cm,
he must do the following actions:
* stop the wheels
* turn on wheels to go backward for 1 second
* stop wheels
* turn left or right
* then go forward
*/
void loop() {
if (get_distance() > 25) {
move_forward();
delay(1000);
} else {
turn_left(500);
stop_all();
move_backward();
delay(1000);
turn_right(500);
turn_left_or_right(turn_delay);
}
}